Compare commits

..

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

218 changed files with 3888 additions and 18195 deletions

View File

@ -1,87 +1,4 @@
# Changelog
## [0.16.0] - 2025-06-27
### Added
- Sistema de logs en tiempo real.
### Improved
- Se ha mejorado el comportamiento de algunos filtros en la parte de trazas.
---
## [0.15.0] - 2025-06-26
### Added
- Se ha añadido integracion con OgGit. Ahora se pueden crear y desplegar imagenes.
- Ahora se pueden gestionar cola de acciones y vaciarlas tanto a nivel de aula como de cliente.
- Nuevos componentes que ayudan a la mejora general de la UX
- Mejora en el comportamiento de los asistentes.
- Se puede cancelar tareas desde la parte de Trazas
### Changed
- Se ha cambiado la vista de las imagenes de Git
---
## [0.14.1] - 2025-06-09
### Fixed
- Se han corregido los errores en produccion que hacia que no salieran mensajes desde la API correctamente.
---
## [0.14.0] - 2025-06-02
### Added
- Se ha añadido funcionalidad de usuarios/roles para separar las vistas segun los permisos.
- Nuevo boton de "mover" en la pantalla de grupos, para mover equipos entre aulas y grupos.
### Improved
- Se ha completado la opcion de inicion de sesion y eliminar imagen cache.
---
## [0.13.1] - 2025-05-23
### Changed
- Desactivado temporalmente la funcionalidad de ogGit.
---
## [0.13.0] - 2025-05-20
### Added
- Se ha añadido nuevo campo "SSL_ENABLED" en el apartado configuracion.
### Improved
- Mejoras en el asistente de particionado.
- Se han añadido mejoras en los filtros de las trazas.
---
## [0.12.0] - 2025-5-13
### Added
- Se ha añadido un nuevo modal del detalle de las acciones ejecutadas por cada cliente.
- Se ha añadido un modulo para la gestion de las tareas y acciones programadas.
- Se han añadido nuevos campos en el listado general de clientes.
### Improved
- Se ha cambiado la pagina de detalles de un cliente, por un modal.
- Se han actualizado gran parte de las ayudas contextuales de las distintas parrillas de datos.
- Se ha mejorado y corregido los errores del particionador.
- Mejoras en la pantalla de trazas.
- Cambios en la estetica general de la aplicacion
- Añadida la primera version de la la integracion con ogGit
- Se ha mejorado la responsividad de la aplicacion, para pantallas pequeñas.
### Fixed
- Se ha corregido un error que hacia que no apareciesen los calendarios en la pantalla de editar OU.
- En la pantalla de hacer deploy, al seleccionar imagen ahora deja desmarcarla.
## [0.11.2] - 2025-4-16
### Fixed
- Se ha corregido un error en la actualizacion del estado de los pcs en la vista tarjetas.
---
## [0.11.1] - 2025-4-16
### Improved
- Nuevos campos en la tabla de clientes. Tipo de firmware y mac.
## Fixed
- Se ha corregido error al crear OUs, que no refrescaba la web.
- Se ha corregido error en el formulario de creacion de imagenes. Si se seleccionaba una imagen para un versionado, no dejaba deseleccionar.
- Se ha corregido un bug en el particionador que impedia ejecutar, cuando eliminabamos una particion.
---
## [0.11.0] - 2025-4-11
### Added
- Se ha diseñado el nuevo formulario para poder ejecutar script. Sistema mejorado con variables etiquetadas.

4
debian/control vendored
View File

@ -9,5 +9,5 @@ Package: oggui
Architecture: any
Maintainer: Nicolas Arenas <nicolas.arenas@qindel.com>
Depends: ${shlibs:Depends}, ${misc:Depends}, nginx
Description: OpenGnsys GUI created for the Opengnsys Team
Opengnsys Graphical Intercface
Description: OpenGnsys GUI
Una interfaz gráfica para OpenGnsys.

29
debian/oggui.postinst vendored
View File

@ -1,7 +1,6 @@
#!/bin/bash
set -e
set -x
. /usr/share/debconf/confmodule
@ -14,28 +13,12 @@ OGMERCURE_URL="$RET"
USER="opengnsys"
CONFIG_FILE="/opt/opengnsys/oggui/browser/assets/config.json"
restore_config_if_modified() {
local new="$1"
local backup="$1.bak"
if [ -f "$backup" ]; then
if ! cmp -s "$new" "$backup"; then
echo ">>> Archivo modificado por el usuario detectado en $new"
echo " - Guardando archivo nuevo como ${new}.new"
mv -f "$new" "${new}.new"
echo " - Restaurando archivo anterior desde backup"
mv -f "$backup" "$new"
else
echo ">>> El archivo $new no ha cambiado desde la última versión, eliminando backup"
rm -f "$backup"
fi
fi
}
# Detectar si es una instalación nueva o una actualización
if [ "$1" = "configure" ] && [ -z "$2" ]; then
jq --arg apiUrl "$OGCORE_URL" --arg mercureUrl "$OGMERCURE_URL" '.apiUrl = $apiUrl | .mercureUrl = $mercureUrl' "$CONFIG_FILE" > "${CONFIG_FILE}.tmp" && mv "${CONFIG_FILE}.tmp" "$CONFIG_FILE"
if [ ! -f "$CONFIG_FILE" ]; then
jq --arg apiUrl "$OGCORE_URL" --arg mercureUrl "$OGMERCURE_URL" \
'.apiUrl = $apiUrl | .mercureUrl = $mercureUrl' "$CONFIG_FILE" > "${CONFIG_FILE}.tmp" && mv "${CONFIG_FILE}.tmp" "$CONFIG_FILE"
fi
ln -s /opt/opengnsys/oggui/etc/nginx/oggui.conf /etc/nginx/sites-enabled/oggui.conf
ln -s $CONFIG_FILE /opt/opengnsys/oggui/etc/config.json
mkdir -p /etc/nginx/certs/
@ -46,10 +29,6 @@ if [ "$1" = "configure" ] && [ -z "$2" ]; then
elif [ "$1" = "configure" ] && [ -n "$2" ]; then
cd /opt/opengnsys/oggui
echo "Actualización desde la versión $2"
# Si upgrade recupero los archivos de configuracion
echo ">>> Backup de archivos de configuración reales en /opt/opengnsys"
restore_config_if_modified "/opt/opengnsys/oggui/etc/nginx/oggui.conf"
restore_config_if_modified "$CONFIG_FILE"
fi
# Cambiar la propiedad de los archivos al usuario especificado

19
debian/oggui.preinst vendored
View File

@ -2,16 +2,6 @@
set -e
backup_file_if_exists() {
local original="$1"
local backup="$1.bak"
if [ -e "$original" ]; then
echo " - Guardando backup de $original en $backup"
cp -a "$original" "$backup"
fi
}
CONFIG_FILE="/opt/opengnsys/oggui/browser/assets/config.json"
# Asegurarse de que el usuario exista
USER="opengnsys"
HOME_DIR="/opt/opengnsys"
@ -22,11 +12,4 @@ else
useradd -m -d "$HOME_DIR" -s /bin/bash "$USER"
fi
# Si upgrade hago backup del archivo de configuración
if [ "$1" = "upgrade" ]; then
echo ">>> Backup de archivos de configuración reales en /opt/opengnsys"
backup_file_if_exists "/opt/opengnsys/oggui/etc/nginx/sites-available/oggui.conf"
backup_file_if_exists "$CONFIG_FILE"
fi
exit 0
exit 0

View File

@ -63,8 +63,8 @@
},
{
"type": "anyComponentStyle",
"maximumWarning": "35kb",
"maximumError": "40kb"
"maximumWarning": "7kb",
"maximumError": "10kb"
}
],
"outputHashing": "all"

View File

@ -3,26 +3,30 @@ import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AuthLayoutComponent } from './layout/auth-layout/auth-layout.component';
import { LoginComponent } from './components/login/login.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { PageNotFoundComponent } from './shared/page-not-found/page-not-found.component';
import { AdminComponent } from './components/admin/admin.component';
import { UsersComponent } from './components/admin/users/users/users.component';
import { RolesComponent } from './components/admin/roles/roles/roles.component';
import { GroupsComponent } from './components/groups/groups.component';
import { PXEimagesComponent } from './components/ogboot/pxe-images/pxe-images.component';
import { PxeComponent } from './components/ogboot/pxe/pxe.component';
import { PxeBootFilesComponent } from './components/ogboot/pxe-boot-files/pxe-boot-files.component';
import { OgbootStatusComponent } from "./components/ogboot/ogboot-status/ogboot-status.component";
import {OgbootStatusComponent} from "./components/ogboot/ogboot-status/ogboot-status.component";
import { CalendarComponent } from "./components/calendar/calendar.component";
import { CommandsComponent } from './components/commands/main-commands/commands.component';
import { CommandsGroupsComponent } from './components/commands/commands-groups/commands-groups.component';
import { CommandsTaskComponent } from './components/commands/commands-task/commands-task.component';
import { TaskLogsComponent } from './components/task-logs/task-logs.component';
import { SoftwareComponent } from "./components/software/software.component";
import { SoftwareProfileComponent } from "./components/software-profile/software-profile.component";
import { OperativeSystemComponent } from "./components/operative-system/operative-system.component";
import { TaskLogsComponent } from './components/commands/commands-task/task-logs/task-logs.component';
import { ClientMainViewComponent } from './components/groups/components/client-main-view/client-main-view.component';
import { ImagesComponent } from './components/images/images.component';
import {SoftwareComponent} from "./components/software/software.component";
import {SoftwareProfileComponent} from "./components/software-profile/software-profile.component";
import {OperativeSystemComponent} from "./components/operative-system/operative-system.component";
import {
PartitionAssistantComponent
} from "./components/groups/components/client-main-view/partition-assistant/partition-assistant.component";
import { RepositoriesComponent } from "./components/repositories/repositories.component";
import {RepositoriesComponent} from "./components/repositories/repositories.component";
import {
CreateClientImageComponent
} from "./components/groups/components/client-main-view/create-image/create-image.component";
@ -32,52 +36,52 @@ import {
import {
MainRepositoryViewComponent
} from "./components/repositories/main-repository-view/main-repository-view.component";
import { EnvVarsComponent } from "./components/admin/env-vars/env-vars.component";
import { MenusComponent } from "./components/menus/menus.component";
import { OgDhcpSubnetsComponent } from "./components/ogdhcp/og-dhcp-subnets.component";
import { StatusComponent } from "./components/ogdhcp/status/status.component";
import {EnvVarsComponent} from "./components/admin/env-vars/env-vars.component";
import {MenusComponent} from "./components/menus/menus.component";
import {OgDhcpSubnetsComponent} from "./components/ogdhcp/og-dhcp-subnets.component";
import {StatusComponent} from "./components/ogdhcp/status/status.component";
import {
RunScriptAssistantComponent
} from "./components/groups/components/client-main-view/run-script-assistant/run-script-assistant.component";
import { roleGuard } from './guards/role.guard';
import { LogoutGuard } from './guards/logout.guard';
const routes: Routes = [
{ path: '', redirectTo: 'auth/login', pathMatch: 'full' },
{
path: '', component: MainLayoutComponent,
{ path: '', component: MainLayoutComponent,
children: [
{ path: 'users', component: UsersComponent, 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: 'dashboard', component: DashboardComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'users', component: UsersComponent },
{ path: 'env-vars', component: EnvVarsComponent },
{ path: 'user-groups', component: RolesComponent },
{ path: 'groups', component: GroupsComponent },
{ 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-boot-file', component: PxeBootFilesComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'ogboot-status', component: OgbootStatusComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'subnets', component: OgDhcpSubnetsComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'ogdhcp-status', component: StatusComponent, 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-task', component: CommandsTaskComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ 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: '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'] } },
{ 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'] } },
{ 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: 'software', component: SoftwareComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'software-profiles', component: SoftwareProfileComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'operative-systems', component: OperativeSystemComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'menus', component: MenusComponent, canActivate: [roleGuard], data: { allowedRoles: ['super-admin', 'ou-admin'] } },
{ path: 'pxe-images', component: PXEimagesComponent },
{ path: 'pxe', component: PxeComponent },
{ path: 'pxe-boot-file', component: PxeBootFilesComponent },
{ path: 'ogboot-status', component: OgbootStatusComponent },
{ path: 'subnets', component: OgDhcpSubnetsComponent },
{ path: 'ogdhcp-status', component: StatusComponent },
{ path: 'commands', component: CommandsComponent },
{ path: 'commands-groups', component: CommandsGroupsComponent },
{ path: 'commands-task', component: CommandsTaskComponent },
{ path: 'commands-logs', component: TaskLogsComponent },
{ path: 'calendars', component: CalendarComponent },
{ path: 'clients/deploy-image', component: DeployImageComponent },
{ path: 'clients/partition-assistant', component: PartitionAssistantComponent },
{ path: 'clients/run-script', component: RunScriptAssistantComponent },
{ path: 'clients/:id', component: ClientMainViewComponent },
{ path: 'clients/:id/create-image', component: CreateClientImageComponent },
{ path: 'repositories', component: RepositoriesComponent },
{ path: 'repository/:id', component: MainRepositoryViewComponent },
{ path: 'software', component: SoftwareComponent },
{ path: 'software-profiles', component: SoftwareProfileComponent },
{ path: 'operative-systems', component: OperativeSystemComponent },
{ path: 'menus', component: MenusComponent },
],
},
{
path: 'auth',
component: AuthLayoutComponent,
children: [
{ path: 'login', component: LoginComponent, canActivate: [LogoutGuard] },
{ path: 'login', component: LoginComponent },
],
},
{ path: '**', component: PageNotFoundComponent },

View File

@ -17,6 +17,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatSidenavModule } from '@angular/material/sidenav';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AdminComponent } from './components/admin/admin.component';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
@ -66,7 +67,7 @@ import { PXEimagesComponent } from './components/ogboot/pxe-images/pxe-images.co
import { CreatePXEImageComponent } from './components/ogboot/pxe-images/create-image/create-image/create-image.component';
import { InfoImageComponent } from './components/ogboot/pxe-images/info-image/info-image/info-image.component';
import { PxeComponent } from './components/ogboot/pxe/pxe.component';
import { CreatePxeTemplateComponent } from './components/ogboot/pxe/manage-pxeTemplate/create-pxe-template.component';
import { CreatePxeTemplateComponent } from './components/ogboot/pxe/create-pxeTemplate/create-pxe-template.component';
import { PxeBootFilesComponent } from './components/ogboot/pxe-boot-files/pxe-boot-files.component';
import { MatExpansionPanel, MatExpansionPanelDescription, MatExpansionPanelTitle } from "@angular/material/expansion";
import { OgbootStatusComponent } from './components/ogboot/ogboot-status/ogboot-status.component';
@ -86,12 +87,12 @@ import { CreateCommandGroupComponent } from './components/commands/commands-grou
import { DetailCommandGroupComponent } from './components/commands/commands-groups/detail-command-group/detail-command-group.component';
import { CreateTaskComponent } from './components/commands/commands-task/create-task/create-task.component';
import { DetailTaskComponent } from './components/commands/commands-task/detail-task/detail-task.component';
import { TaskLogsComponent } from './components/task-logs/task-logs.component';
import { TaskLogsComponent } from './components/commands/commands-task/task-logs/task-logs.component';
import { MatSliderModule } from '@angular/material/slider';
import { ClientMainViewComponent } from './components/groups/components/client-main-view/client-main-view.component';
import { ImagesComponent } from './components/images/images.component';
import { CreateImageComponent } from './components/images/create-image/create-image.component';
import { CreateClientImageComponent } from './components/groups/components/client-main-view/create-image/create-image.component';
import { CreateRepositoryModalComponent } from './components/groups/components/client-main-view/create-image/create-repository-modal/create-repository-modal.component';
import { PartitionAssistantComponent } from './components/groups/components/client-main-view/partition-assistant/partition-assistant.component';
import { SoftwareComponent } from './components/software/software.component';
import { CreateSoftwareComponent } from './components/software/create-software/create-software.component';
@ -117,7 +118,7 @@ import { CreateMultipleClientComponent } from './components/groups/shared/client
import { ExportImageComponent } from './components/images/export-image/export-image.component';
import { ImportImageComponent } from "./components/repositories/import-image/import-image.component";
import { LoadingComponent } from './shared/loading/loading.component';
import { InputDialogComponent } from './components/task-logs/input-dialog/input-dialog.component';
import { InputDialogComponent } from './components/commands/commands-task/task-logs/input-dialog/input-dialog.component';
import { ManageOrganizationalUnitComponent } from './components/groups/shared/organizational-units/manage-organizational-unit/manage-organizational-unit.component';
import { BackupImageComponent } from './components/repositories/backup-image/backup-image.component';
import { ServerInfoDialogComponent } from "./components/ogdhcp/server-info-dialog/server-info-dialog.component";
@ -129,7 +130,7 @@ import { ShowClientsComponent } from './components/ogdhcp/show-clients/show-clie
import { OperationResultDialogComponent } from './components/ogdhcp/operation-result-dialog/operation-result-dialog.component';
import { ManageClientComponent } from './components/groups/shared/clients/manage-client/manage-client.component';
import { ConvertImageComponent } from './components/repositories/convert-image/convert-image.component';
import {NgOptimizedImage, registerLocaleData} from '@angular/common';
import { registerLocaleData } from '@angular/common';
import localeEs from '@angular/common/locales/es';
import { GlobalStatusComponent } from './components/global-status/global-status.component';
import { ShowMonoliticImagesComponent } from './components/repositories/show-monolitic-images/show-monolitic-images.component';
@ -140,25 +141,8 @@ import {
SaveScriptComponent
} from "./components/groups/components/client-main-view/run-script-assistant/save-script/save-script.component";
import { EditImageComponent } from './components/repositories/edit-image/edit-image.component';
import { ShowGitCommitsComponent } from './components/repositories/show-git-images/show-git-images.component';
import { ShowGitImagesComponent } from './components/repositories/show-git-images/show-git-images.component';
import { RenameImageComponent } from './components/repositories/rename-image/rename-image.component';
import { ClientDetailsComponent } from './components/groups/shared/client-details/client-details.component';
import { PartitionTypeOrganizatorComponent } from './components/groups/shared/partition-type-organizator/partition-type-organizator.component';
import { CreateTaskScheduleComponent } from './components/commands/commands-task/create-task-schedule/create-task-schedule.component';
import { ShowTaskScheduleComponent } from './components/commands/commands-task/show-task-schedule/show-task-schedule.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 { ViewParametersModalComponent } from './components/commands/commands-task/show-task-script/view-parameters-modal/view-parameters-modal.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 { 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 { 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 { ClientPendingTasksComponent } from './components/task-logs/client-pending-tasks/client-pending-tasks.component';
import { QueueConfirmationModalComponent } from './shared/queue-confirmation-modal/queue-confirmation-modal.component';
import { ModalOverlayComponent } from './shared/modal-overlay/modal-overlay.component';
import { ScrollToTopComponent } from './shared/scroll-to-top/scroll-to-top.component';
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './locale/', '.json');
@ -178,6 +162,7 @@ registerLocaleData(localeEs, 'es-ES');
HeaderComponent,
SidebarComponent,
LoginComponent,
AdminComponent,
MainLayoutComponent,
UsersComponent,
RolesComponent,
@ -187,7 +172,6 @@ registerLocaleData(localeEs, 'es-ES');
GroupsComponent,
ManageClientComponent,
DeleteModalComponent,
QueueConfirmationModalComponent,
ClassroomViewComponent,
ClientViewComponent,
ShowOrganizationalUnitComponent,
@ -210,8 +194,6 @@ registerLocaleData(localeEs, 'es-ES');
CalendarComponent,
CreateCalendarComponent,
CreateClientImageComponent,
CreateRepositoryModalComponent,
PartitionAssistantComponent,
CreateCalendarRuleComponent,
CommandsGroupsComponent,
CommandsTaskComponent,
@ -222,8 +204,10 @@ registerLocaleData(localeEs, 'es-ES');
TaskLogsComponent,
ServerInfoDialogComponent,
StatusComponent,
ClientMainViewComponent,
ImagesComponent,
CreateImageComponent,
PartitionAssistantComponent,
SoftwareComponent,
CreateSoftwareComponent,
SoftwareProfileComponent,
@ -237,6 +221,7 @@ registerLocaleData(localeEs, 'es-ES');
ExecuteCommandOuComponent,
DeployImageComponent,
MainRepositoryViewComponent,
ExecuteCommandOuComponent,
EnvVarsComponent,
MenusComponent,
CreateMenuComponent,
@ -257,24 +242,8 @@ registerLocaleData(localeEs, 'es-ES');
RunScriptAssistantComponent,
SaveScriptComponent,
EditImageComponent,
ShowGitCommitsComponent,
RenameImageComponent,
ClientDetailsComponent,
PartitionTypeOrganizatorComponent,
CreateTaskScheduleComponent,
ShowTaskScheduleComponent,
ShowTaskScriptComponent,
CreateTaskScriptComponent,
ViewParametersModalComponent,
OutputDialogComponent,
ClientTaskLogsComponent,
BootSoPartitionComponent,
RemoveCacheImageComponent,
ChangeParentComponent,
SoftwareProfilePartitionComponent,
ClientPendingTasksComponent,
ModalOverlayComponent,
ScrollToTopComponent
ShowGitImagesComponent,
RenameImageComponent
],
bootstrap: [AppComponent],
imports: [BrowserModule,
@ -323,7 +292,7 @@ registerLocaleData(localeEs, 'es-ES');
progressAnimation: 'increasing',
closeButton: true
}
), MatGridList, MatTree, MatTreeNode, MatNestedTreeNode, MatTreeNodeToggle, MatTreeNodeDef, MatTreeNodePadding, MatTreeNodeOutlet, MatPaginator, MatGridTile, MatExpansionPanel, MatExpansionPanelTitle, MatExpansionPanelDescription, MatRadioGroup, MatRadioButton, MatAutocompleteTrigger, NgOptimizedImage
), MatGridList, MatTree, MatTreeNode, MatNestedTreeNode, MatTreeNodeToggle, MatTreeNodeDef, MatTreeNodePadding, MatTreeNodeOutlet, MatPaginator, MatGridTile, MatExpansionPanel, MatExpansionPanelTitle, MatExpansionPanelDescription, MatRadioGroup, MatRadioButton, MatAutocompleteTrigger
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,

View File

@ -0,0 +1,48 @@
/* Estilos del contenedor para centrar los botones */
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* Estilos del contenedor de cada botón y texto */
.button-container {
display: flex;
flex-direction: column;
align-items: center;
margin: 0 10px;
}
/* Estilos del texto debajo de los botones */
span{
margin: 0;
font-size: 20px;
text-align: center;
}
/* Media query para hacer los botones responsive */
@media (max-width: 900px) {
button {
height: 120px;
width: 120px;
}
}
@media (max-width: 600px) {
button {
height: 90px;
width: 90px;
}
}
@media (max-width: 400px) {
button {
height: 70px;
width: 70px;
}
span{
font-size: 14px;
}
}

View File

@ -0,0 +1,10 @@
<div class="container">
<button class="action-button" routerLink="/users">
<mat-icon>group</mat-icon>
<span>{{ 'labelUsers' | translate }}</span>
</button>
<button class="action-button" routerLink="/user-groups">
<mat-icon>admin_panel_settings</mat-icon>
<span>{{ 'labelRoles' | translate }}</span>
</button>
</div>

View File

@ -0,0 +1,48 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AdminComponent } from './admin.component';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
import { Router } from '@angular/router';
describe('AdminComponent', () => {
let component: AdminComponent;
let fixture: ComponentFixture<AdminComponent>;
let router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AdminComponent],
imports: [
RouterTestingModule,
MatButtonModule,
MatIconModule,
TranslateModule.forRoot()
]
}).compileComponents();
router = TestBed.inject(Router);
});
beforeEach(() => {
fixture = TestBed.createComponent(AdminComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('debería crear el componente', () => {
expect(component).toBeTruthy();
});
it('debería renderizar dos botones', () => {
const buttons = fixture.nativeElement.querySelectorAll('button');
expect(buttons.length).toBe(2);
});
it('debería tener un botón con routerLink a "/users"', () => {
const button = fixture.nativeElement.querySelector('button[routerLink="/users"]');
expect(button).toBeTruthy();
expect(button.querySelector('mat-icon').textContent.trim()).toBe('group');
});
});

View File

@ -0,0 +1,13 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrl: './admin.component.css'
})
export class AdminComponent {
}

View File

@ -16,20 +16,12 @@
<ng-container matColumnDef="value">
<mat-header-cell *matHeaderCellDef> Valor </mat-header-cell>
<mat-cell *matCellDef="let variable">
<!-- Si es booleano, usamos checkbox -->
<mat-checkbox *ngIf="isBoolean(variable.value)"
[checked]="variable.value === 'true'"
(change)="variable.value = $event.checked ? 'true' : 'false'">
</mat-checkbox>
<!-- Si no es booleano, usamos input -->
<mat-form-field *ngIf="!isBoolean(variable.value)" class="value-input">
<mat-form-field class="value-input">
<input matInput [(ngModel)]="variable.value" />
</mat-form-field>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
@ -38,4 +30,4 @@
<button class="action-button" (click)="loadEnvVars()">Recargar</button>
<button class="submit-button" (click)="saveEnvVars()">Guardar Cambios</button>
</div>
</div>
</div>

View File

@ -31,15 +31,12 @@ export class EnvVarsComponent {
this.envVars = Object.entries(response.vars).map(([name, value]) => ({ name, value }));
},
error: (err) => {
console.error('Error al cargar las variables de entorno:', err);
this.toastService.error('No se pudieron cargar las variables de entorno.');
}
});
}
isBoolean(value: string): boolean {
return value === 'true' || value === 'false';
}
saveEnvVars(): void {
const vars = this.envVars.reduce((acc, variable) => {
acc[variable.name] = variable.value;

View File

@ -22,12 +22,7 @@
.time-fields {
display: flex;
gap: 15px;
}
.hour-fields {
display: flex;
gap: 15px;
gap: 15px; /* Espacio entre los campos */
}
.time-field {
@ -39,74 +34,4 @@
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.custom-text {
font-style: italic;
font-size: 0.875rem;
color: #666;
margin: 4px 0 12px;
}
.weekday-toggle-group {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 40px 0 40px 0;
width: 100%;
justify-content: space-between;
}
.weekday-toggle {
flex: 1 1 calc(14.28% - 10px);
padding: 10px 0;
border-radius: 999px;
border: 1px solid #ccc;
background-color: #f5f5f5;
cursor: pointer;
font-size: 14px;
text-align: center;
transition: all 0.2s ease;
min-width: 40px;
}
.weekday-toggle.selected {
background-color: #1976d2;
color: white;
border-color: #1976d2;
}
.availability-summary {
background-color: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 12px 16px;
margin-top: 16px;
border-radius: 6px;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
.summary-text {
color: #0d47a1;
line-height: 1.4;
}
.unavailability-summary {
background-color: #ffebee;
border-left: 4px solid #d32f2f;
padding: 12px 16px;
margin-top: 16px;
border-radius: 6px;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
.summary-text {
color: #b71c1c;
line-height: 1.4;
}
}

View File

@ -1,26 +1,24 @@
<h2 mat-dialog-title>{{ isEditMode ? ('editCalendar' | translate) : ('addCalendar' | translate) }}</h2>
<mat-dialog-content class="form-container">
<mat-checkbox [(ngModel)]="isRemoteAvailable">
<mat-slide-toggle [(ngModel)]="isRemoteAvailable" class="example-margin">
{{ 'remoteAvailability' | translate }}
</mat-checkbox>
<mat-divider style="margin: 10px 0;"></mat-divider>
</mat-slide-toggle>
<div *ngIf="!isRemoteAvailable" class="form-group">
<mat-label>{{ 'selectWeekDays' | translate }}</mat-label>
<p class="custom-text"> (Los dias y horas seleccionados se marcarán como aula no disponible para remote pc.) </p>
<div class="weekday-toggle-group full-width">
<button
*ngFor="let day of weekDays"
type="button"
class="weekday-toggle"
[class.selected]="busyWeekDays[day]"
(click)="busyWeekDays[day] = !busyWeekDays[day]">
{{ day.slice(0, 3) }}
</button>
<div class="row">
<div class="col-md-6 checkbox-group">
<mat-checkbox *ngFor="let day of weekDays.slice(0, (weekDays.length / 2) + 1)" [(ngModel)]="busyWeekDays[day]">
{{ day }}
</mat-checkbox>
</div>
<div class="col-md-6 checkbox-group">
<mat-checkbox *ngFor="let day of weekDays.slice(weekDays.length / 2 + 1)" [(ngModel)]="busyWeekDays[day]">
{{ day }}
</mat-checkbox>
</div>
</div>
<div class="time-fields">
<mat-form-field appearance="fill" class="time-field">
<mat-label>{{ 'startTime' | translate }}</mat-label>
@ -32,24 +30,12 @@
<input matInput [(ngModel)]="busyToHour" type="time" placeholder="{{ 'endTimePlaceholder' | translate }}" [required]="!isRemoteAvailable">
</mat-form-field>
</div>
<mat-divider></mat-divider>
<div class="unavailability-summary" *ngIf="busyFromHour && busyToHour && busyWeekDays && getSelectedDays().length">
<mat-icon style="width: 50px;" color="warn">block</mat-icon>
<span class="summary-text">
El aula estará <strong>no disponible</strong> para Remote PC los días:
<strong>{{ getSelectedDays().join(', ') }}</strong> de
<strong>{{ busyFromHour }}</strong> a <strong>{{ busyToHour }}</strong>.
</span>
</div>
</div>
<div *ngIf="isRemoteAvailable" class="form-group">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'reasonLabel' | translate }}</mat-label>
<input matInput [(ngModel)]="availableReason" placeholder="{{ 'reasonPlaceholder' | translate }}" [required]="isRemoteAvailable">
<mat-hint>Razón por la cual el aula SI está disponible para su uso en Remote PC</mat-hint>
</mat-form-field>
<div class="time-fields">
<mat-form-field appearance="fill" class="full-width">
@ -67,32 +53,6 @@
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
<div class="hour-fields">
<mat-form-field appearance="fill" class="time-field">
<mat-label>{{ 'startTime' | translate }}</mat-label>
<input matInput [(ngModel)]="busyFromHour" type="time" placeholder="{{ 'startTimePlaceholder' | translate }}" [required]="!isRemoteAvailable">
</mat-form-field>
<mat-form-field appearance="fill" class="time-field">
<mat-label>{{ 'endTime' | translate }}</mat-label>
<input matInput [(ngModel)]="busyToHour" type="time" placeholder="{{ 'endTimePlaceholder' | translate }}" [required]="!isRemoteAvailable">
</mat-form-field>
</div>
<mat-divider></mat-divider>
<div class="availability-summary" *ngIf="availableFromDate && availableToDate">
<mat-icon color="primary" style="width: 50px;">info</mat-icon>
<span class="summary-text">
El aula estará <strong>disponible</strong> para reserva desde el
<strong>{{ availableFromDate | date:'fullDate' }}</strong> hasta el
<strong>{{ availableToDate | date:'fullDate' }}</strong>
<span *ngIf="busyFromHour && busyToHour">
en el horario de <strong>{{ busyFromHour }}</strong> a <strong>{{ busyToHour }}</strong>.
</span>
</span>
</div>
</div>
</mat-dialog-content>

View File

@ -64,8 +64,8 @@ export class CreateCalendarRuleComponent {
this.dialogRef.close();
}
getSelectedDays(): string[] {
return Object.keys(this.busyWeekDays || {}).filter(day => this.busyWeekDays[day]);
toggleAdditionalForm(): void {
this.showAdditionalForm = !this.showAdditionalForm;
}
getSelectedDaysIndices() {
@ -74,11 +74,6 @@ export class CreateCalendarRuleComponent {
.filter(index => index !== -1);
}
convertDateToLocalISO(date: Date): string {
const adjustedDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
return adjustedDate.toISOString();
}
submitRule(): void {
this.getSelectedDaysIndices()
const selectedDaysArray = Object.keys(this.busyWeekDays).map((day, index) => this.busyWeekDays[index]);
@ -88,8 +83,8 @@ export class CreateCalendarRuleComponent {
busyWeekDays: this.selectedDaysIndices,
busyFromHour: this.busyFromHour,
busyToHour: this.busyToHour,
availableFromDate: this.availableFromDate ? this.convertDateToLocalISO(this.availableFromDate) : null,
availableToDate: this.availableToDate ? this.convertDateToLocalISO(this.availableToDate) : null,
availableFromDate: this.availableFromDate,
availableToDate: this.availableToDate,
isRemoteAvailable: this.isRemoteAvailable,
availableReason: this.availableReason
};
@ -98,7 +93,7 @@ export class CreateCalendarRuleComponent {
this.http.put(`${this.baseUrl}${this.ruleId}`, formData)
.subscribe({
next: (response) => {
this.toastService.success('Calendar rule updated successfully');
this.toastService.success('Calendar updated successfully');
this.dialogRef.close(true);
},
error: (error) => {
@ -110,7 +105,7 @@ export class CreateCalendarRuleComponent {
this.http.post(`${this.baseUrl}/remote-calendar-rules`, formData)
.subscribe({
next: (response) => {
this.toastService.success('Calendar rule created successfully');
this.toastService.success('Calendar created successfully');
this.dialogRef.close(true);
},
error: (error) => {

View File

@ -25,7 +25,7 @@
.time-fields {
display: flex;
gap: 15px;
gap: 15px; /* Espacio entre los campos */
}
.time-field {
@ -34,25 +34,24 @@
.list-item-content {
display: flex;
align-items: flex-start;
justify-content: space-between;
width: 100%;
align-items: flex-start; /* Alinea el contenido al inicio */
justify-content: space-between; /* Espacio entre los textos y los íconos */
width: 100%; /* Asegúrate de que el contenido ocupe todo el ancho */
}
.text-content {
flex-grow: 1;
margin-right: 16px;
flex-grow: 1; /* Permite que este contenedor ocupe el espacio disponible */
margin-right: 16px; /* Espaciado a la derecha para separar de los íconos */
margin-left: 10px;
margin-bottom: 16px;
}
.icon-container {
display: flex;
align-items: center;
align-items: center; /* Alinea los íconos verticalmente */
}
.right-icon {
margin-left: 8px;
margin-left: 8px; /* Espaciado entre los íconos */
cursor: pointer;
}
@ -61,15 +60,4 @@
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.rule-available {
background-color: #e8f5e9;
border-left: 4px solid #4caf50;
}
.rule-unavailable {
background-color: #ffebee;
border-left: 4px solid #f44336;
}
}

View File

@ -6,7 +6,7 @@
<input matInput [(ngModel)]="name" required>
<mat-icon *ngIf="isEditMode" matSuffix (click)="submitForm()">mode_edit</mat-icon>
</mat-form-field>
<div style="display: flex; justify-content: space-between; align-items: center;">
<div *ngIf="isEditMode" mat-subheader>{{ 'rulesHeader' | translate }}</div>
<button class="action-button" *ngIf="isEditMode" (click)="createRule()" style="padding: 10px;">
@ -18,20 +18,14 @@
<mat-list *ngIf="isEditMode">
<ng-container *ngFor="let rule of remoteCalendarRules;">
<mat-list-item
[ngClass]="{
'rule-available': rule.isRemoteAvailable,
'rule-unavailable': !rule.isRemoteAvailable
}"
>
<mat-list-item>
<div class="list-item-content">
<mat-icon matListItemIcon>event_available</mat-icon>
<div class="text-content">
<div matListItemTitle>{{ rule.isRemoteAvailable ? ('remotePcStatusAvailable' | translate) : ('remotePcStatusUnavailable' | translate) }}</div>
<div matListItemLine *ngIf="!rule.isRemoteAvailable">Días: <strong>{{ rule.busyWeekDaysMap }}</strong></div>
<div matListItemLine *ngIf="rule.isRemoteAvailable">Razón: {{ rule.availableReason }}</div>
<div matListItemLine *ngIf="rule.isRemoteAvailable">Días: <strong>{{ rule.availableFromDate | date }} - {{ rule.availableToDate | date }}</strong></div>
<div matListItemLine>Horario: {{ rule.busyFromHour }} - {{ rule.busyToHour }}</div>
<div matListItemTitle>{{ rule.isRemoteAvailable ? ('statusAvailable' | translate) : ('statusUnavailable' | translate) }}</div>
<div matListItemLine *ngIf="!rule.isRemoteAvailable">{{ rule.busyFromHour }} - {{ rule.busyToHour }}</div>
<div matListItemLine *ngIf="!rule.isRemoteAvailable">{{ rule.busyWeekDaysMap }}</div>
<div matListItemLine *ngIf="rule.isRemoteAvailable">{{ rule.availableReason }} | {{ rule.availableFromDate | date }} - {{ rule.availableToDate | date }}</div>
</div>
<div class="icon-container">
<button mat-icon-button color="primary" class="right-icon" (click)="createRule(rule)">

View File

@ -33,6 +33,15 @@
<ng-container *ngIf="column.columnDef !== 'commands'">
{{ column.cell(commandGroup) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'commands'" joyrideStep="viewCommandsStep" text="{{ 'viewCommandsStepText' | translate }}">
<button class="action-button" [matMenuTriggerFor]="menu">{{ 'viewCommands' | translate }}</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngFor="let command of commandGroup.commands">
{{ command.name }}
</button>
</mat-menu>
</ng-container>
</td>
</ng-container>

View File

@ -1,5 +1,3 @@
<app-loading [isLoading]="loading"></app-loading>
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
@ -25,28 +23,36 @@
<div *ngIf="!loading">
<table mat-table [dataSource]="tasks" class="mat-elevation-z8" joyrideStep="tableStep" text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let task">
<ng-container *ngIf="column.columnDef !== 'management'">
{{ column.cell(task) }}
</ng-container>
<ng-container matColumnDef="taskid">
<th mat-header-cell *matHeaderCellDef> {{ 'idColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.id }} </td>
</ng-container>
<ng-container *ngIf="column.columnDef === 'management'">
<button class="action-button" (click)="openShowScheduleDialog(task)"> Programaciones</button>
<button class="action-button" style="margin-left: 0.5vw;" (click)="openShowScriptDialog(task)">Acciones</button>
</ng-container>
</td>
<ng-container matColumnDef="notes">
<th mat-header-cell *matHeaderCellDef> {{ 'infoColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.notes }} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> {{ 'createdByColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.createdBy }} </td>
</ng-container>
<ng-container matColumnDef="scheduledDate">
<th mat-header-cell *matHeaderCellDef> {{ 'executionDateColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.dateTime | date:'short' }} </td>
</ng-container>
<ng-container matColumnDef="enabled">
<th mat-header-cell *matHeaderCellDef> {{ 'statusColumn' | translate }} </th>
<td mat-cell *matCellDef="let task"> {{ task.enabled ? ('enabled' | translate) : ('disabled' | translate) }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef style="text-align: center;">{{ 'columnActions' | translate }}</th>
<td mat-cell *matCellDef="let task" style="text-align: center;" joyrideStep="actionsStep" text="{{ 'actionsStepText' | translate }}">
<button mat-icon-button color="primary" (click)="manageScheduleAction(task)">
<mat-icon>watch</mat-icon>
</button>
<button mat-icon-button color="primary" (click)="manageScriptAction(task)">
<mat-icon>code-blocks</mat-icon>
<button mat-icon-button color="info" (click)="viewTaskDetails(task)">
<mat-icon>visibility</mat-icon>
</button>
<button mat-icon-button color="primary" (click)="editTask(task)">
<mat-icon>edit</mat-icon>

View File

@ -7,13 +7,6 @@ import { DetailTaskComponent } from './detail-task/detail-task.component';
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';
import {CreateTaskScheduleComponent} from "./create-task-schedule/create-task-schedule.component";
import {ShowClientsComponent} from "../../ogdhcp/show-clients/show-clients.component";
import {Subnet} from "../../ogdhcp/og-dhcp-subnets.component";
import {ShowTaskScheduleComponent} from "./show-task-schedule/show-task-schedule.component";
import {ShowTaskScriptComponent} from "./show-task-script/show-task-script.component";
import {CreateTaskScriptComponent} from "./create-task-script/create-task-script.component";
import {DatePipe} from "@angular/common";
@Component({
selector: 'app-commands-task',
@ -28,18 +21,7 @@ export class CommandsTaskComponent implements OnInit {
itemsPerPage: number = 10;
page: number = 1;
pageSizeOptions: number[] = [5, 10, 20, 40, 100];
datePipe: DatePipe = new DatePipe('es-ES');
columns = [
{ columnDef: 'id', header: 'ID', cell: (task: any) => task.id },
{ columnDef: 'name', header: 'Nombre de tarea', cell: (task: any) => task.name },
{ columnDef: 'organizationalUnit', header: 'Ámbito', cell: (task: any) => task.organizationalUnit.name },
{ columnDef: 'management', header: 'Gestiones', cell: (task: any) => task.schedules },
{ columnDef: 'nextExecution', header: 'Próxima ejecución', cell: (task: any) => this.datePipe.transform(task.nextExecution, 'dd/MM/yyyy HH:mm:ss', 'UTC') },
{ columnDef: 'createdBy', header: 'Creado por', cell: (task: any) => task.createdBy },
];
displayedColumns: string[] = ['id', 'name', 'organizationalUnit', 'management', 'nextExecution', 'createdBy', 'actions'];
displayedColumns: string[] = ['taskid', 'notes', 'name', 'scheduledDate', 'enabled', 'actions'];
loading: boolean = false;
private apiUrl: string;
@ -74,25 +56,24 @@ export class CommandsTaskComponent implements OnInit {
);
}
viewTaskDetails(task: any): void {
this.dialog.open(DetailTaskComponent, {
width: '800px',
data: { task },
}).afterClosed().subscribe(() => this.loadTasks());
}
openCreateTaskModal(): void {
this.dialog.open(CreateTaskComponent, {
width: '800px',
}).afterClosed().subscribe(result => {
if (result) {
this.loadTasks();
}
})
}).afterClosed().subscribe(() => this.loadTasks());
}
editTask(task: any): void {
this.dialog.open(CreateTaskComponent, {
width: '800px',
data: { task },
}).afterClosed().subscribe(result => {
if (result) {
this.loadTasks();
}
})
}).afterClosed().subscribe(() => this.loadTasks());
}
deleteTask(task: any): void {
@ -114,66 +95,12 @@ export class CommandsTaskComponent implements OnInit {
});
}
manageScheduleAction(task: any): void {
this.dialog.open(CreateTaskScheduleComponent, {
width: '800px',
data: { task },
}).afterClosed().subscribe( result => {
if (result) {
this.loadTasks();
}
})
}
manageScriptAction(task: any): void {
this.dialog.open(CreateTaskScriptComponent, {
width: '900px',
data: { task },
}).afterClosed().subscribe( result => {
if (result) {
this.loadTasks();
}
})
}
onPageChange(event: any): void {
this.page = event.pageIndex + 1;
this.itemsPerPage = event.pageSize;
this.loadTasks();
}
openShowScheduleDialog(commandTask: any) {
const dialogRef = this.dialog.open(ShowTaskScheduleComponent, {
width: '85vw',
height: '85vh',
maxWidth: '85vw',
maxHeight: '85vh',
data: { commandTask: commandTask }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.loadTasks();
}
});
}
openShowScriptDialog(commandTask: any) {
const dialogRef = this.dialog.open(ShowTaskScriptComponent, {
width: '85vw',
height: '85vh',
maxWidth: '85vw',
maxHeight: '85vh',
data: { commandTask: commandTask }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.loadTasks();
}
});
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [

View File

@ -1,128 +0,0 @@
.dialog-title {
font-weight: bold;
}
.task-form {
padding: 20px;
}
.full-width {
width: 100%;
}
.custom-time {
display: flex;
gap: 15px;
}
.w-half {
width: 50%;
}
mat-form-field {
margin-bottom: 16px;
}
form {
display: flex;
flex-direction: column;
gap: 16px;
margin: auto;
}
mat-form-field {
width: 100%;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.weekday-toggle-group {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 16px;
}
.weekday-toggle {
flex: 1;
padding: 8px 0;
border: 1px solid #ccc;
border-radius: 4px;
background: #f5f5f5;
cursor: pointer;
font-weight: 500;
transition: background 0.2s ease;
}
.weekday-toggle.selected {
background: #1976d2;
color: white;
border-color: #1976d2;
}
.month-toggle-group {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 16px;
}
.month-toggle-row {
display: flex;
gap: 8px;
margin-bottom: 8px;
justify-content: space-between;
}
.month-toggle {
flex: 1;
padding: 8px;
min-width: 48px;
border: 1px solid #ccc;
border-radius: 6px;
background-color: #f0f0f0;
text-align: center;
cursor: pointer;
transition: background-color 0.2s ease;
}
.month-toggle.selected {
background-color: #4caf50;
color: white;
border-color: #4caf50;
}
.summary-card {
background: #f9fafb;
border-left: 5px solid #3f51b5;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border-radius: 12px;
padding: 16px;
transition: box-shadow 0.3s ease;
}
.summary-card:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.summary-card {
background-color: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 12px 16px;
margin-top: 16px;
border-radius: 6px;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
.summary-text {
color: #0d47a1;
line-height: 1.4;
}

View File

@ -1,87 +0,0 @@
<h2 mat-dialog-title class="dialog-title">Programar accion</h2>
<mat-dialog-content class="dialog-content">
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="task-form">
<mat-form-field appearance="fill" class="w-full">
<mat-label>Repetición</mat-label>
<mat-select formControlName="recurrenceType">
<mat-option *ngFor="let type of recurrenceTypes" [value]="type">{{ type | titlecase }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="w-full" *ngIf="form.get('recurrenceType')?.value === 'none'">
<mat-label>Fecha de ejecución</mat-label>
<input matInput [matDatepicker]="oneTimePicker" formControlName="executionDate">
<mat-datepicker-toggle matSuffix [for]="oneTimePicker"></mat-datepicker-toggle>
<mat-datepicker #oneTimePicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="fill" class="w-full">
<mat-label>Hora</mat-label>
<input matInput formControlName="executionTime" placeholder="08:00" type="time">
</mat-form-field>
<!-- Mostrar solo si no es 'none' -->
<div *ngIf="form.get('recurrenceType')?.value !== 'none'" class="mb-4">
<label>Días de la semana:</label>
<div class="weekday-toggle-group">
<button
*ngFor="let day of weekDays"
type="button"
class="weekday-toggle"
[class.selected]="selectedDays[day]"
(click)="toggleDay(day)">
{{ day.slice(0, 3) }}
</button>
</div>
</div>
<!-- Selección de meses -->
<div *ngIf="form.get('recurrenceType')?.value !== 'none'" >
<label>Meses:</label>
<div class="month-toggle-row" *ngFor="let row of monthRows">
<button
*ngFor="let month of row"
type="button"
class="month-toggle"
[class.selected]="selectedMonths[month]"
(click)="toggleMonth(month)">
{{ month.slice(0, 3) }}
</button>
</div>
</div>
<!-- Rango de fechas -->
<div *ngIf="form.get('recurrenceType')?.value !== 'none'" class="custom-time" formGroupName="recurrenceDetails">
<mat-form-field appearance="fill" class="w-half">
<mat-label>Desde</mat-label>
<input matInput [matDatepicker]="fromPicker" formControlName="initDate">
<mat-datepicker-toggle matSuffix [for]="fromPicker"></mat-datepicker-toggle>
<mat-datepicker #fromPicker></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="fill" class="w-half">
<mat-label>Hasta</mat-label>
<input matInput [matDatepicker]="toPicker" formControlName="endDate">
<mat-datepicker-toggle matSuffix [for]="toPicker"></mat-datepicker-toggle>
<mat-datepicker #toPicker></mat-datepicker>
</mat-form-field>
</div>
<mat-checkbox formControlName="enabled">Activar tarea</mat-checkbox>
<mat-card *ngIf="summaryText" class="summary-card">
<mat-icon color="primary" style="width: 50px;">info</mat-icon>
<span class="summary-text">
{{ summaryText }}
</span>
</mat-card>
</form>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onCancel()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()" >{{ 'buttonSave' | translate }}</button>
</mat-dialog-actions>

View File

@ -1,100 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CreateTaskScheduleComponent } from './create-task-schedule.component';
import {LoadingComponent} from "../../../../shared/loading/loading.component";
import {HttpClientTestingModule} from "@angular/common/http/testing";
import {ToastrModule} from "ngx-toastr";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatDividerModule} from "@angular/material/divider";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatIconModule} from "@angular/material/icon";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
import {MatPaginatorModule} from "@angular/material/paginator";
import {MatTooltipModule} from "@angular/material/tooltip";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatSelectModule} from "@angular/material/select";
import {MatTabsModule} from "@angular/material/tabs";
import {MatAutocompleteModule} from "@angular/material/autocomplete";
import {MatListModule} from "@angular/material/list";
import {MatCardModule} from "@angular/material/card";
import {MatMenuModule} from "@angular/material/menu";
import {MatTreeModule} from "@angular/material/tree";
import {TranslateModule, TranslateService} from "@ngx-translate/core";
import {JoyrideModule} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute} from "@angular/router";
import {MatDatepickerModule} from "@angular/material/datepicker";
import {MatButtonToggleModule} from "@angular/material/button-toggle";
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_NATIVE_DATE_FORMATS,
MatNativeDateModule,
provideNativeDateAdapter
} from "@angular/material/core";
import {MatCheckboxModule} from "@angular/material/checkbox";
describe('CreateTaskScheduleComponent', () => {
let component: CreateTaskScheduleComponent;
let fixture: ComponentFixture<CreateTaskScheduleComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [CreateTaskScheduleComponent, LoadingComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
MatDividerModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatButtonModule,
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
ReactiveFormsModule,
MatProgressSpinnerModule,
MatDialogModule,
MatSelectModule,
MatTabsModule,
MatAutocompleteModule,
MatListModule,
MatCardModule,
MatMenuModule,
MatTreeModule,
MatDatepickerModule,
MatButtonToggleModule,
MatNativeDateModule,
MatCheckboxModule,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: { data: { id: 123 } } },
{ provide: ConfigService, useValue: mockConfigService },
{ provide: ActivatedRoute, useValue: { queryParams: { subscribe: () => {} } } },
{ provide: MAT_DATE_FORMATS, useValue: MAT_NATIVE_DATE_FORMATS },
]
}).compileComponents();
fixture = TestBed.createComponent(CreateTaskScheduleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,203 +0,0 @@
import {Component, Inject, OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
import {ConfigService} from "@services/config.service";
@Component({
selector: 'app-create-task-schedule',
templateUrl: './create-task-schedule.component.html',
styleUrl: './create-task-schedule.component.css'
})
export class CreateTaskScheduleComponent implements OnInit{
form: FormGroup;
baseUrl: string;
apiUrl: string;
recurrenceTypes = ['none', 'custom'];
weekDays: string[] = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
isSingleDateSelected: boolean = true;
monthsList: string[] = [
'january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december'
];
monthRows: string[][] = [];
editing: boolean = false;
selectedMonths: { [key: string]: boolean } = {};
selectedDays: { [key: string]: boolean } = {};
constructor(
private fb: FormBuilder,
public dialogRef: MatDialogRef<CreateTaskScheduleComponent>,
private http: HttpClient,
private toastr: ToastrService,
private configService: ConfigService,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-task-schedules`;
this.form = this.fb.group({
executionDate: [new Date()],
executionTime: ['08:00'],
recurrenceType: ['none'],
recurrenceDetails: this.fb.group({
daysOfWeek: [[]],
months: this.fb.control([]),
initDate: [null],
endDate: [null]
}),
enabled: [true]
});
if (this.data.schedule) {
this.editing = true;
this.loadData();
}
this.form.get('recurrenceType')?.valueChanges.subscribe((value) => {
if (value === 'none') {
this.form.get('recurrenceDetails')?.disable();
} else {
this.form.get('recurrenceDetails')?.enable();
}
});
}
ngOnInit(): void {
this.monthRows = [
this.monthsList.slice(0, 6),
this.monthsList.slice(6, 12)
];
}
loadData(): void {
this.http.get<any>(`${this.baseUrl}${this.data.schedule['@id']}`).subscribe(
(data) => {
const formattedExecutionTime = this.formatExecutionTime(data.executionTime);
this.form.patchValue({
executionDate: data.executionDate,
executionTime: formattedExecutionTime,
recurrenceType: data.recurrenceType,
recurrenceDetails: {
...data.recurrenceDetails,
initDate: data.recurrenceDetails.initDate || null,
endDate: data.recurrenceDetails.endDate || null,
daysOfWeek: data.recurrenceDetails.daysOfWeek || [],
months: data.recurrenceDetails.months || []
},
enabled: data.enabled
});
this.selectedDays = data.recurrenceDetails.daysOfWeek.reduce((acc: any, day: string) => {
acc[day] = true;
return acc;
}, {});
this.selectedMonths = data.recurrenceDetails.months.reduce((acc: any, month: string) => {
acc[month] = true;
return acc;
}, {});
},
(error) => {
console.error('Error loading schedule data', error);
}
);
}
formatExecutionTime(time: string | Date): string {
const date = (time instanceof Date) ? time : new Date(time);
if (isNaN(date.getTime())) {
console.error('Invalid execution time:', time);
return '';
}
return date.toISOString().substring(11, 16);
}
convertDateToLocalISO(date: Date): string {
date = new Date(date);
const adjustedDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
return adjustedDate.toISOString();
}
onSubmit() {
const formData = this.form.value;
const payload: any = {
commandTask: this.data.task['@id'],
executionDate: formData.recurrenceType === 'none' ? this.convertDateToLocalISO(formData.executionDate) : null,
executionTime: formData.executionTime,
recurrenceType: formData.recurrenceType,
recurrenceDetails: {
...formData.recurrenceDetails,
initDate: formData.recurrenceDetails?.initDate || null,
endDate: formData.recurrenceDetails?.endDate || null,
daysOfWeek: formData.recurrenceDetails?.daysOfWeek || [],
months: formData.recurrenceDetails?.months || []
},
enabled: formData.enabled
}
if (this.editing) {
const taskId = this.data.task.uuid;
this.http.patch<any>(`${this.baseUrl}${this.data.schedule['@id']}`, payload).subscribe({
next: () => {
this.toastr.success('Programacion de tarea actualizada con éxito');
this.dialogRef.close(true);
},
error: () => {
this.toastr.error('Error al actualizar la tarea');
}
});
} else {
this.http.post<any>(this.apiUrl, payload).subscribe({
next: () => {
this.toastr.success('Programacion de tarea creada con éxito');
this.dialogRef.close(true);
},
error: () => {
this.toastr.error('Error al crear la tarea');
}
});
}
}
onCancel(): void {
this.dialogRef.close(false);
}
get summaryText(): string {
const recurrence = this.form.get('recurrenceType')?.value;
const start = this.form.get('recurrenceType')?.value === 'none' ? this.form.get('executionDate')?.value : this.form.get('recurrenceDetails.initDate')?.value;
const end = this.form.get('recurrenceType')?.value === 'none' ? this.form.get('executionDate')?.value : this.form.get('recurrenceDetails.endDate')?.value;
const time = this.form.get('executionTime')?.value;
const days = Object.keys(this.selectedDays).filter(day => this.selectedDays[day]);
const months = Object.keys(this.selectedMonths).filter(month => this.selectedMonths[month]);
if (recurrence === 'none') {
return `Esta acción se ejecutará una sola vez el ${ this.formatDate(start)} a las ${time}.`;
}
return `Esta acción se ejecutará todos los ${days.join(', ')} de ${months.join(', ')}, desde el ${this.formatDate(start)} hasta el ${this.formatDate(end)} a las ${time}.`;
}
formatDate(date: string | Date): string {
const realDate = (date instanceof Date) ? date : new Date(date);
return new Intl.DateTimeFormat('es-ES', { dateStyle: 'long' }).format(realDate);
}
toggleDay(day: string) {
this.selectedDays[day] = !this.selectedDays[day];
const days = Object.keys(this.selectedDays).filter(d => this.selectedDays[d]);
this.form.get('recurrenceDetails.daysOfWeek')?.setValue(days);
}
toggleMonth(month: string) {
this.selectedMonths[month] = !this.selectedMonths[month];
const months = Object.keys(this.selectedMonths).filter(m => this.selectedMonths[m]);
this.form.get('recurrenceDetails.months')?.setValue(months);
}
}

View File

@ -1,284 +0,0 @@
.divider {
margin: 20px 0;
}
table {
width: 100%;
margin-top: 50px;
}
.task-form {
padding: 20px;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.deploy-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
gap: 10px;
}
.script-container {
gap: 20px;
padding: 20px;
background-color: #eaeff6;
border-radius: 12px;
margin-top: 20px;
}
.script-content {
flex: 2;
min-width: 60%;
}
.script-params {
flex: 1;
min-width: 35%;
}
@media (max-width: 768px) {
.script-container {
flex-direction: column;
}
.script-content, .script-params {
min-width: 100%;
}
}
.select-container {
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.input-group {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-top: 20px;
}
.input-field {
flex: 1 1 calc(33.33% - 16px);
min-width: 250px;
}
.script-preview {
background-color: #f4f4f4;
border: 1px solid #ccc;
padding: 10px;
border-radius: 5px;
font-family: monospace;
white-space: pre-wrap;
min-height: 50px;
}
.custom-width {
width: 50%;
margin-bottom: 16px;
}
.search-string {
flex: 2;
padding: 5px;
}
.search-boolean {
flex: 1;
padding: 5px;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.client-item {
position: relative;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.client-details {
margin-top: 4px;
}
.client-name {
font-size: 0.9em;
font-weight: 600;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
display: block;
font-size: 0.9em;
color: #666;
}
.header-container-title {
flex-grow: 1;
text-align: left;
padding-left: 1em;
}
.button-row {
display: flex;
padding-right: 1em;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
::ng-deep .custom-tooltip {
white-space: pre-line !important;
max-width: 200px;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px;
border-radius: 4px;
}
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.button-row {
display: flex;
padding-right: 1em;
}
.disabled-client {
pointer-events: none;
opacity: 0.5;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.new-command-container {
display: flex;
flex-direction: column;
gap: 10px;
padding: 15px;
background-color: #eaeff6;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
margin-top: 15px;
}
.new-command-container mat-form-field {
width: 100%;
}
.new-command-container textarea {
font-family: monospace;
resize: vertical;
}
.new-command-container .action-button {
align-self: flex-end;
color: white;
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.full-width {
width: 100%;
}
.script-selector-card {
margin: 20px 20px;
padding: 16px;
}
.toggle-options {
display: flex;
justify-content: start;
margin: 16px 0;
}

View File

@ -1,65 +0,0 @@
<h2 mat-dialog-title class="dialog-title">Añadir acción a: {{ data.task?.name }}</h2>
<mat-dialog-content class="dialog-content">
<div class="task-form">
<div class="toggle-options">
<mat-button-toggle-group [(ngModel)]="commandType" exclusive>
<mat-button-toggle value="new">
<mat-icon>edit</mat-icon> Nuevo Script
</mat-button-toggle>
<mat-button-toggle value="existing">
<mat-icon>storage</mat-icon> Script Guardado
</mat-button-toggle>
</mat-button-toggle-group>
</div>
<div *ngIf="commandType === 'new'" class="new-command-container">
<mat-form-field appearance="fill" class="custom-width">
<mat-label>Orden de ejecucion </mat-label>
<input matInput type="number" [(ngModel)]="executionOrder" placeholder="Orden de ejecución">
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Ingrese el script</mat-label>
<textarea matInput [(ngModel)]="newScript" rows="6" placeholder="Escriba su script aquí"></textarea>
</mat-form-field>
<button mat-flat-button color="primary" (click)="saveNewScript()">Guardar Script</button>
</div>
<div *ngIf="commandType === 'existing'">
<mat-form-field appearance="fill" class="custom-width">
<mat-label>Seleccione script a ejecutar</mat-label>
<mat-select [(ngModel)]="selectedScript" (selectionChange)="onScriptChange()">
<mat-option *ngFor="let script of scripts" [value]="script">{{ script.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div *ngIf="selectedScript && commandType === 'existing'" class="script-container">
<mat-form-field appearance="fill" class="custom-width">
<mat-label>Orden de ejecucion </mat-label>
<input matInput type="number" [(ngModel)]="executionOrder" placeholder="Orden de ejecución">
</mat-form-field>
<div class="script-content">
<h3>Script:</h3>
<div class="script-preview" [innerHTML]="scriptContent"></div>
</div>
<div class="script-params" *ngIf="parameterNames.length > 0">
<h3>Ingrese los parámetros:</h3>
<div *ngFor="let paramName of parameterNames">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ paramName }}</mat-label>
<input matInput [ngModel]="parameters[paramName]" (ngModelChange)="onParamChange(paramName, $event)" placeholder="Valor para {{ paramName }}">
</mat-form-field>
</div>
</div>
</div>
</div>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onCancel()">{{ 'buttonCancel' | translate }}</button>
<button class="submit-button" (click)="onSubmit()" >{{ 'buttonSave' | translate }}</button>
</mat-dialog-actions>

View File

@ -1,89 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CreateTaskScriptComponent } from './create-task-script.component';
import {GroupsComponent} from "../../../groups/groups.component";
import {ExecuteCommandComponent} from "../../main-commands/execute-command/execute-command.component";
import {LoadingComponent} from "../../../../shared/loading/loading.component";
import {HttpClientTestingModule} from "@angular/common/http/testing";
import {ToastrModule} from "ngx-toastr";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatDividerModule} from "@angular/material/divider";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatIconModule} from "@angular/material/icon";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
import {MatPaginatorModule} from "@angular/material/paginator";
import {MatTooltipModule} from "@angular/material/tooltip";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatSelectModule} from "@angular/material/select";
import {MatTabsModule} from "@angular/material/tabs";
import {MatAutocompleteModule} from "@angular/material/autocomplete";
import {MatListModule} from "@angular/material/list";
import {MatCardModule} from "@angular/material/card";
import {MatMenuModule} from "@angular/material/menu";
import {MatTreeModule} from "@angular/material/tree";
import {TranslateModule, TranslateService} from "@ngx-translate/core";
import {JoyrideModule} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute} from "@angular/router";
import {MatButtonToggleModule} from "@angular/material/button-toggle";
describe('CreateTaskScriptComponent', () => {
let component: CreateTaskScriptComponent;
let fixture: ComponentFixture<CreateTaskScriptComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [CreateTaskScriptComponent, LoadingComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
MatDividerModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatButtonModule,
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
ReactiveFormsModule,
MatProgressSpinnerModule,
MatDialogModule,
MatSelectModule,
MatTabsModule,
MatAutocompleteModule,
MatListModule,
MatCardModule,
MatMenuModule,
MatButtonToggleModule,
MatTreeModule,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: { data: { id: 123 } } },
{ provide: ConfigService, useValue: mockConfigService },
{ provide: ActivatedRoute, useValue: { queryParams: { subscribe: () => {} } } },
]
}).compileComponents();
fixture = TestBed.createComponent(CreateTaskScriptComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,138 +0,0 @@
import {Component, EventEmitter, Inject, OnInit, Output} from '@angular/core';
import {SelectionModel} from "@angular/cdk/collections";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute, Router} from "@angular/router";
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog";
import {
SaveScriptComponent
} from "../../../groups/components/client-main-view/run-script-assistant/save-script/save-script.component";
import {FormBuilder, FormGroup} from "@angular/forms";
@Component({
selector: 'app-create-task-script',
templateUrl: './create-task-script.component.html',
styleUrl: './create-task-script.component.css'
})
export class CreateTaskScriptComponent implements OnInit {
form: FormGroup;
baseUrl: string;
@Output() dataChange = new EventEmitter<any>();
errorMessage = '';
loading: boolean = false;
scripts: any[] = [];
scriptContent: string = "";
parameters: any = {};
commandType: string = 'existing';
selectedScript: any = null;
newScript: string = '';
executionOrder: Number = 0;
selection = new SelectionModel(true, []);
parameterNames: string[] = Object.keys(this.parameters);
constructor(
private fb: FormBuilder,
private http: HttpClient,
public dialogRef: MatDialogRef<CreateTaskScriptComponent>,
private toastService: ToastrService,
private configService: ConfigService,
private router: Router,
private dialog: MatDialog,
private route: ActivatedRoute,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.loadScripts()
this.form = this.fb.group({
content: [''],
order: [''],
})
}
ngOnInit(): void {
}
loadScripts(): void {
this.loading = true;
this.http.get(`${this.baseUrl}/commands?readOnly=false&enabled=true`).subscribe((data: any) => {
this.scripts = data['hydra:member'];
this.loading = false;
}, (error) => {
this.toastService.error(error.error['hydra:description']);
this.loading = false;
});
}
saveNewScript() {
if (!this.newScript.trim()) {
this.toastService.error('Debe ingresar un script antes de guardar.');
return;
}
const dialogRef = this.dialog.open(SaveScriptComponent, {
width: '400px',
data: this.newScript
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.toastService.success('Script guardado correctamente');
}
});
}
onScriptChange() {
if (this.selectedScript) {
this.scriptContent = this.selectedScript.script;
const matches = this.scriptContent.match(/@(\w+)/g) || [];
const uniqueParams = Array.from(new Set(matches.map(m => m.slice(1))));
this.parameters = {};
uniqueParams.forEach(param => this.parameters[param] = '');
this.parameterNames = uniqueParams;
this.updateScript();
}
}
onParamChange(name: string, value: string): void {
this.parameters[name] = value;
this.updateScript();
}
updateScript(): void {
let updatedScript = this.selectedScript.script;
for (const [key, value] of Object.entries(this.parameters)) {
const regex = new RegExp(`@${key}\\b`, 'g');
updatedScript = updatedScript.replace(regex, value || `@${key}`);
}
this.scriptContent = updatedScript;
}
onSubmit() {
this.http.post(`${this.baseUrl}/command-task-scripts`, {
commandTask: this.data.task['@id'],
content: this.commandType === 'existing' ? this.scriptContent : this.newScript,
order: this.executionOrder,
type: 'run-script',
}).subscribe({
next: () => {
this.toastService.success('Tarea creada con éxito');
this.dialogRef.close(true);
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
}
})
}
onCancel(): void {
this.dialogRef.close(false);
}
}

View File

@ -6,24 +6,19 @@
padding: 20px;
}
.select-task {
padding: 20px;
margin-bottom: 16px;
}
.full-width {
width: 100%;
}
mat-form-field {
margin-bottom: 16px;
.button-container {
display: flex;
justify-content: flex-end;
margin-top: 20px;
padding: 1.5rem;
}
.loading-spinner {
display: block;
margin: 0 auto;
align-items: center;
justify-content: center;
mat-form-field {
margin-bottom: 16px;
}
.section-title {
@ -31,35 +26,3 @@ mat-form-field {
margin-bottom: 8px;
font-weight: 500;
}
.summary-section {
background-color: #f9f9f9;
border-bottom: 1px solid #ddd;
margin-bottom: 10px;
}
.summary-block {
margin-top: 10px;
}
.date-time-row {
display: flex;
gap: 16px;
margin-top: 12px;
}
.half-width {
flex: 1;
min-width: 0;
}
.full-width {
width: 100%;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}

View File

@ -1,83 +1,106 @@
<h2 mat-dialog-title class="dialog-title">
{{ editing ? ('editTask' | translate) : ('createTask' | translate) }}
</h2>
<h2 mat-dialog-title class="dialog-title">{{ editing ? ('editTask' | translate) : ('createTask' | translate) }}</h2>
<mat-dialog-content class="dialog-content">
<mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<form [formGroup]="taskForm" class="task-form">
<mat-dialog-content>
<!-- Toggle entre crear o añadir -->
<mat-radio-group *ngIf="data?.source === 'assistant'" [(ngModel)]="taskMode" class="task-mode-selection" name="taskMode">
<mat-radio-button value="create">Crear tarea</mat-radio-button>
<mat-radio-button value="add">Introducir en tarea existente</mat-radio-button>
</mat-radio-group>
<!-- Selección de tarea existente -->
<div *ngIf="taskMode === 'add'" class="select-task">
<h3 class="section-title">Información</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccione una tarea</mat-label>
<mat-select [(ngModel)]="selectedExistingTask" name="existingTask">
<mat-option *ngFor="let task of existingTasks" [value]="task">{{ task.name }}</mat-option>
</mat-select>
<mat-label>Información</mat-label>
<textarea matInput formControlName="notes" placeholder="Ingresa tus notas aquí"></textarea>
</mat-form-field>
<h3 class="section-title">{{ 'informationSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Orden de ejecución</mat-label>
<input
matInput
type="number"
[(ngModel)]="executionOrder"
name="executionOrder"
min="1"
placeholder="Introduce el orden"
>
</mat-form-field>
</div>
<!-- Formulario de nueva tarea -->
<form *ngIf="taskMode === 'create' && taskForm && !loading" [formGroup]="taskForm" class="task-form">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'nameLabel' | translate }}</mat-label>
<input matInput formControlName="name" placeholder="{{ 'nameLabel' | translate }}">
<mat-error *ngIf="taskForm.get('name')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'notesLabel' | translate }}</mat-label>
<mat-label>{{ 'informationLabel' | translate }}</mat-label>
<textarea matInput formControlName="notes" placeholder="{{ 'notesPlaceholder' | translate }}"></textarea>
</mat-form-field>
<h3 class="section-title">{{ 'commandSelectionSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Ámbito</mat-label>
<mat-select formControlName="scope" (selectionChange)="onScopeChange($event.value)">
<mat-option value="organizational-unit">Unidad Organizativa</mat-option>
<mat-option value="classrooms-group">Grupo de aulas</mat-option>
<mat-option value="classroom">Aulas</mat-option>
<mat-option value="clients-group">Grupos de clientes</mat-option>
<mat-label>{{ 'selectCommandsLabel' | translate }}</mat-label>
<mat-select formControlName="commandGroup" (selectionChange)="onCommandGroupChange()">
<mat-option *ngFor="let group of availableCommandGroups" [value]="group.uuid">
{{ group.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('commandGroup')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'organizationalUnitLabel' | translate }}</mat-label>
<mat-select formControlName="organizationalUnit">
<mat-option *ngFor="let unit of availableOrganizationalUnits" [value]="unit['@id']">
<div class="unit-name">{{ unit.name }}</div>
<div style="font-size: smaller; color: gray;">{{ unit.path }}</div>
<mat-label>{{ 'selectIndividualCommandsLabel' | translate }}</mat-label>
<mat-select formControlName="extraCommands" multiple>
<mat-option *ngFor="let command of availableIndividualCommands" [value]="command.uuid">
{{ command.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-checkbox *ngIf="!editing" formControlName="scheduleAfterCreate">
¿Quieres programar la tarea al finalizar su creación?
</mat-checkbox>
</form>
</mat-dialog-content>
<h3 class="section-title">{{ 'executionDateTimeSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'executionDateLabel' | translate }}</mat-label>
<input matInput [matDatepicker]="picker" formControlName="date" placeholder="{{ 'selectDatePlaceholder' | translate }}">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="taskForm.get('date')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">{{ 'buttonCancel' | translate }}</button>
<button
class="submit-button"
(click)="taskMode === 'create' ? saveTask() : addToExistingTask()"
>
{{ 'buttonSave' | translate }}
</button>
</mat-dialog-actions>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'executionTimeLabel' | translate }}</mat-label>
<input matInput type="time" formControlName="time" placeholder="{{ 'selectTimePlaceholder' | translate }}">
<mat-error *ngIf="taskForm.get('time')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<h3 class="section-title">{{ 'destinationSelectionSectionTitle' | translate }}</h3>
<mat-divider></mat-divider>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectOrganizationalUnitLabel' | translate }}</mat-label>
<mat-select formControlName="organizationalUnit" (selectionChange)="onOrganizationalUnitChange()">
<mat-option *ngFor="let unit of availableOrganizationalUnits" [value]="unit['@id']">
{{ unit.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="taskForm.get('organizationalUnit')?.invalid">{{ 'requiredFieldError' | translate }}</mat-error>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectClassroomLabel' | translate }}</mat-label>
<mat-select formControlName="selectedChild" (selectionChange)="onChildChange()">
<mat-option *ngFor="let child of selectedUnitChildren" [value]="child['@id']">
{{ child.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ 'selectClientsLabel' | translate }}</mat-label>
<mat-select formControlName="selectedClients" multiple>
<mat-option (click)="toggleSelectAll()" [selected]="areAllSelected()">
{{ 'selectAllClients' | translate }}
</mat-option>
<mat-option *ngFor="let client of selectedClients" [value]="client.uuid">
{{ client.name }} ({{ client.ip }})
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Selecciona Clientes</mat-label>
<mat-select formControlName="selectedClients" multiple>
<mat-option (click)="toggleSelectAll()" [selected]="areAllSelected()">
Seleccionar todos
</mat-option>
<mat-option *ngFor="let client of selectedClients" [value]="client.uuid">
{{ client.name }} ({{ client.ip }})
</mat-option>
</mat-select>
</mat-form-field>
</mat-dialog-content>
</form>
<div class="button-container">
<button class="submit-button" (click)="saveTask()">{{ 'buttonSave' | translate }}</button>
</div>

View File

@ -1,12 +1,9 @@
import { Component, OnInit, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ConfigService } from '@services/config.service';
import {of} from "rxjs";
import {startWith, switchMap} from "rxjs/operators";
import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component";
@Component({
selector: 'app-create-task',
@ -22,185 +19,171 @@ export class CreateTaskComponent implements OnInit {
apiUrl: string;
editing: boolean = false;
availableOrganizationalUnits: any[] = [];
clients: any[] = [];
allOrganizationalUnits: any[] = [];
loading: boolean = false;
taskMode: 'create' | 'add' = 'create';
existingTasks: any[] = [];
selectedExistingTask: string | null = null;
executionOrder: number | null = null;
selectedUnitChildren: any[] = [];
selectedClients: any[] = [];
selectedClientIds: Set<string> = new Set();
constructor(
private fb: FormBuilder,
private http: HttpClient,
private configService: ConfigService,
private toastr: ToastrService,
private dialog: MatDialog,
public dialogRef: MatDialogRef<CreateTaskComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/command-tasks`;
this.taskForm = this.fb.group({
scope: [ this.data?.scope ? this.data.scope : '', Validators.required],
name: ['', Validators.required],
organizationalUnit: [ this.data?.organizationalUnit ? this.data.organizationalUnit : null, Validators.required],
commandGroup: ['', Validators.required],
extraCommands: [[]],
date: ['', Validators.required],
time: ['', Validators.required],
notes: [''],
scheduleAfterCreate: [false]
organizationalUnit: ['', Validators.required],
selectedChild: [''],
selectedClients: [[]]
});
}
ngOnInit(): void {
this.loading = true;
const observables = [
this.loadCommandGroups(),
this.loadIndividualCommands(),
this.loadOrganizationalUnits(),
this.startUnitsFilter(),
this.loadTasks()
];
Promise.all(observables).then(() => {
if (this.data.task) {
this.editing = true;
this.loadData().then(() => {
this.loading = false;
})
} else {
this.loading = false;
}
}).catch(() => {
this.loading = false;
})
this.loadCommandGroups();
this.loadIndividualCommands();
this.loadOrganizationalUnits();
if (this.data && this.data.task) {
this.editing = true;
this.loadTaskData(this.data.task);
}
}
loadData(): Promise<void> {
return new Promise((resolve, reject) => {
this.http.get<any>(`${this.baseUrl}${this.data.task['@id']}`).subscribe(
(data) => {
this.taskForm.patchValue({
name: data.name,
scope: data.scope,
organizationalUnit: data.organizationalUnit ? data.organizationalUnit['@id'] : null,
notes: data.notes,
});
resolve();
},
(error) => {
this.toastr.error('Error al cargar los datos de la tarea');
reject(error);
}
);
})
}
loadTasks(): Promise<void> {
return new Promise((resolve, reject) => {
this.http.get<any>(`${this.apiUrl}?page=1&itemsPerPage=100`).subscribe(
(data) => {
this.existingTasks = data['hydra:member'];
resolve();
},
(error) => {
this.toastr.error('Error al cargar las tareas existentes');
reject(error);
}
);
});
}
onScopeChange(scope: string): void {
this.filterUnits(scope).subscribe(filteredUnits => {
this.availableOrganizationalUnits = filteredUnits;
this.taskForm.get('organizationalUnit')?.setValue('');
});
}
startUnitsFilter(): Promise<void> {
return new Promise((resolve, reject) => {
this.taskForm.get('scope')?.valueChanges.pipe(
startWith(this.taskForm.get('scope')?.value),
switchMap((value) => this.filterUnits(value))
).subscribe(filteredUnits => {
this.availableOrganizationalUnits = filteredUnits;
resolve();
}, error => {
this.toastr.error('Error al filtrar las unidades organizacionales');
reject(error);
});
})
}
filterUnits(value: string) {
const filtered = this.allOrganizationalUnits.filter(unit => unit.type === value);
return of(filtered);
}
loadCommandGroups(): Promise<void> {
return new Promise((resolve, reject) => {
loadCommandGroups(): void {
this.http.get<any>(`${this.baseUrl}/command-groups`).subscribe(
(data) => {
this.availableCommandGroups = data['hydra:member'];
resolve();
},
(error) => {
this.toastr.error('Error al cargar los grupos de comandos');
reject(error);
});
});
}
);
}
loadIndividualCommands(): Promise<void> {
return new Promise((resolve, reject) => {
this.http.get<any>(`${this.baseUrl}/commands`).subscribe(
(data) => {
this.availableIndividualCommands = data['hydra:member'];
resolve();
},
(error) => {
this.toastr.error('Error al cargar los comandos individuales');
reject(error);
});
});
loadIndividualCommands(): void {
this.http.get<any>(`${this.baseUrl}/commands`).subscribe(
(data) => {
this.availableIndividualCommands = data['hydra:member'];
},
(error) => {
this.toastr.error('Error al cargar los comandos individuales');
}
);
}
loadOrganizationalUnits(): Promise<void> {
return new Promise((resolve, reject) => {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=100`).subscribe(
(data) => {
this.allOrganizationalUnits = data['hydra:member'];
this.availableOrganizationalUnits = [...this.allOrganizationalUnits];
resolve();
},
(error) => {
this.toastr.error('Error al cargar las unidades organizacionales');
reject(error);
loadOrganizationalUnits(): void {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=30`).subscribe(
(data) => {
this.availableOrganizationalUnits = data['hydra:member'].filter((unit: any) => unit['type'] === 'organizational-unit');
},
(error) => {
this.toastr.error('Error al cargar las unidades organizacionales');
}
);
}
loadTaskData(task: any): void {
this.taskForm.patchValue({
commandGroup: task.commandGroup ? task.commandGroup['@id'] : '',
extraCommands: task.commands ? task.commands.map((cmd: any) => cmd['@id']) : [],
date: task.dateTime ? task.dateTime.split('T')[0] : '',
time: task.dateTime ? task.dateTime.split('T')[1].slice(0, 5) : '',
notes: task.notes || '',
organizationalUnit: task.organizationalUnit ? task.organizationalUnit['@id'] : ''
});
if (task.commandGroup) {
this.selectedGroupCommands = task.commandGroup.commands;
}
}
private collectClassrooms(unit: any): any[] {
let classrooms = [];
if (unit.type === 'classroom') {
classrooms.push(unit);
}
if (unit.children && unit.children.length > 0) {
for (let child of unit.children) {
classrooms = classrooms.concat(this.collectClassrooms(child));
}
}
return classrooms;
}
onOrganizationalUnitChange(): void {
const selectedUnitId = this.taskForm.get('organizationalUnit')?.value;
const selectedUnit = this.availableOrganizationalUnits.find(unit => unit['@id'] === selectedUnitId);
if (selectedUnit) {
this.selectedUnitChildren = this.collectClassrooms(selectedUnit);
} else {
this.selectedUnitChildren = [];
}
this.taskForm.patchValue({ selectedChild: '', selectedClients: [] });
this.selectedClients = [];
this.selectedClientIds.clear();
}
onChildChange(): void {
const selectedChildId = this.taskForm.get('selectedChild')?.value;
if (!selectedChildId) {
this.selectedClients = [];
return;
}
const url = `${this.baseUrl}${selectedChildId}`.replace(/([^:]\/)\/+/g, '$1');
this.http.get<any>(url).subscribe(
(data) => {
if (Array.isArray(data.clients) && data.clients.length > 0) {
this.selectedClients = data.clients;
} else {
this.selectedClients = [];
this.toastr.warning('El aula seleccionada no tiene clientes.');
}
);
});
this.taskForm.patchValue({ selectedClients: [] });
this.selectedClientIds.clear();
},
(error) => {
this.toastr.error('Error al cargar los detalles del aula seleccionada');
}
);
}
addToExistingTask() {
if (!this.selectedExistingTask) {
this.toastr.error('Debes seleccionar una tarea existente.');
return;
toggleSelectAll() {
const allSelected = this.areAllSelected();
if (allSelected) {
this.selectedClientIds.clear();
} else {
this.selectedClients.forEach(client => this.selectedClientIds.add(client.uuid));
}
if (this.executionOrder == null || this.executionOrder < 1) {
this.toastr.error('Debes introducir un orden de ejecución válido (mayor que 0).');
return;
}
const data = {
taskId: this.selectedExistingTask,
executionOrder: this.executionOrder
};
this.toastr.success('Tarea actualizada con éxito');
this.dialogRef.close(data);
this.taskForm.get('selectedClients')!.setValue(Array.from(this.selectedClientIds));
}
areAllSelected(): boolean {
return this.selectedClients.length > 0 && this.selectedClients.every(client => this.selectedClientIds.has(client.uuid));
}
onCommandGroupChange(): void {
const selectedGroupId = this.taskForm.get('commandGroup')?.value;
this.http.get<any>(`${this.baseUrl}/command-groups/${selectedGroupId}`).subscribe(
(data) => {
this.selectedGroupCommands = data.commands;
},
(error) => {
this.toastr.error('Error al cargar los comandos del grupo seleccionado');
}
);
}
saveTask(): void {
if (this.taskForm.invalid) {
@ -209,14 +192,22 @@ export class CreateTaskComponent implements OnInit {
}
const formData = this.taskForm.value;
const dateTime = this.combineDateAndTime(formData.date, formData.time);
const selectedCommands = formData.extraCommands && formData.extraCommands.length > 0
? formData.extraCommands.map((id: any) => `/commands/${id}`)
: null;
const payload: any = {
name: formData.name,
scope: formData.scope,
organizationalUnit: formData.organizationalUnit,
commandGroups: formData.commandGroup ? [`/command-groups/${formData.commandGroup}`] : null,
dateTime: dateTime,
notes: formData.notes || '',
clients: Array.from(this.selectedClientIds).map((uuid: string) => `/clients/${uuid}`),
};
if (selectedCommands) {
payload.commands = selectedCommands;
}
if (this.editing) {
const taskId = this.data.task.uuid;
this.http.patch<any>(`${this.apiUrl}/${taskId}`, payload).subscribe({
@ -230,21 +221,9 @@ export class CreateTaskComponent implements OnInit {
});
} else {
this.http.post<any>(this.apiUrl, payload).subscribe({
next: response => {
next: () => {
this.toastr.success('Tarea creada con éxito');
this.dialogRef.close(response);
if (formData.scheduleAfterCreate) {
const dialogRef = this.dialog.open(CreateTaskScheduleComponent, {
width: '800px',
data: { task: response }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.toastr.success('Tarea programada correctamente');
}
});
}
this.dialogRef.close(true);
},
error: () => {
this.toastr.error('Error al crear la tarea');
@ -253,7 +232,14 @@ export class CreateTaskComponent implements OnInit {
}
}
combineDateAndTime(date: string, time: string): string {
const dateObj = new Date(date);
const [hours, minutes] = time.split(':').map(Number);
dateObj.setHours(hours, minutes, 0);
return dateObj.toISOString();
}
close(): void {
this.dialogRef.close(false);
this.dialogRef.close();
}
}

View File

@ -1,89 +0,0 @@
.full-width {
width: 100%;
}
form {
padding: 20px;
}
.spacing-container {
margin-top: 20px;
margin-bottom: 16px;
}
.list-item-content {
display: flex;
align-items: flex-start;
justify-content: space-between;
width: 100%;
}
.text-content {
flex-grow: 1;
margin-right: 16px;
margin-left: 10px;
}
.icon-container {
display: flex;
align-items: center;
}
.right-icon {
margin-left: 8px;
cursor: pointer;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.lists-container {
padding: 16px;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
box-sizing: border-box;
}
.search-string {
flex: 1;
padding: 5px;
}
.search-select {
flex: 1;
padding: 5px;
}
table {
width: 100%;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
mat-spinner {
margin: 0 auto;
align-self: center;
}
.subnets-button-row {
display: flex;
gap: 15px;
}

View File

@ -1,100 +0,0 @@
<app-loading [isLoading]="loading"></app-loading>
<h2 mat-dialog-title>Gestionar programaciones de tareas en {{ data.commandTask?.name }}</h2>
<mat-dialog-content>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string" joyrideStep="searchNameStep"
text="Busca subredes por nombre para localizar una subred específica rápidamente.">
<mat-label i18n="@@searchLabel">Buscar nombre del cliente</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" i18n-placeholder="@@searchPlaceholder"
(keyup.enter)="loadData()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<button *ngIf="filters['name']" mat-icon-button matSuffix aria-label="Clear tree search"
(click)="filters['name'] = ''; loadData()">
<mat-icon>close</mat-icon>
</button>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
<mat-form-field appearance="fill" class="search-string" joyrideStep="searchIpStep" text="Busca programaciones por tipo.">
<mat-label i18n="@@searchLabel">Buscar por tipo</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['recurrence']" i18n-placeholder="@@searchPlaceholder"
(keyup.enter)="loadData()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<button *ngIf="filters['ip']" mat-icon-button matSuffix aria-label="Clear tree search"
(click)="filters['ip'] = ''; loadData()">
<mat-icon>close</mat-icon>
</button>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<app-loading [isLoading]="loading"></app-loading>
<table *ngIf="!loading" mat-table [dataSource]="dataSource" class="mat-elevation-z8" joyrideStep="tableStep"
text="Visualiza y administra las subredes listadas según los filtros aplicados.">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let schedule">
<ng-container *ngIf="column.columnDef === 'recurrenceType'">
<mat-chip style="padding: 10px; margin: 5px;">
<ng-container *ngIf="column.cell(schedule) === 'none'; else scheduledTemplate">
No programado
<div style="font-size: 12px;">
{{ schedule.executionDate | date }}
</div>
</ng-container>
<ng-template #scheduledTemplate>
Programado
<div style="font-size: 12px;">
{{ schedule.recurrenceDetails.initDate | date }} → {{ schedule.recurrenceDetails.endDate | date}}
</div>
</ng-template>
</mat-chip>
</ng-container>
<ng-container *ngIf="column.columnDef === 'executionTime'">
{{ schedule.executionTime | date: 'HH:mm' }}
</ng-container>
<ng-container *ngIf="column.columnDef !== 'recurrenceType' && column.columnDef !== 'executionTime' && column.columnDef !== 'enabled'">
{{ column.cell(schedule) }}
</ng-container>
<ng-container *ngIf="column.columnDef === 'enabled'">
<mat-chip>
<ng-container *ngIf="schedule.enabled">
Activo
</ng-container>
<ng-container *ngIf="!schedule.enabled">
Inactivo
</ng-container>
</mat-chip>
</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let schedule" style="text-align: center;">
<button mat-icon-button color="primary" (click)="editSchedule(schedule)">
<mat-icon i18n="@@deleteElementTooltip">edit</mat-icon>
</button>
<button mat-icon-button color="warn" (click)="deleteSchedule(schedule)">
<mat-icon i18n="@@deleteElementTooltip">delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div class="paginator-container" joyrideStep="paginationStep"
text="Navega entre las páginas de subredes usando el paginador.">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">Cerrar</button>
</mat-dialog-actions>

View File

@ -1,86 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ShowTaskScheduleComponent } from './show-task-schedule.component';
import {LoadingComponent} from "../../../../shared/loading/loading.component";
import {HttpClientTestingModule} from "@angular/common/http/testing";
import {ToastrModule} from "ngx-toastr";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatDividerModule} from "@angular/material/divider";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatIconModule} from "@angular/material/icon";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
import {MatPaginatorModule} from "@angular/material/paginator";
import {MatTooltipModule} from "@angular/material/tooltip";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatSelectModule} from "@angular/material/select";
import {MatTabsModule} from "@angular/material/tabs";
import {MatAutocompleteModule} from "@angular/material/autocomplete";
import {MatListModule} from "@angular/material/list";
import {MatCardModule} from "@angular/material/card";
import {MatMenuModule} from "@angular/material/menu";
import {MatTreeModule} from "@angular/material/tree";
import {TranslateModule} from "@ngx-translate/core";
import {JoyrideModule} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute} from "@angular/router";
import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component";
describe('ShowTaskScheduleComponent', () => {
let component: ShowTaskScheduleComponent;
let fixture: ComponentFixture<ShowTaskScheduleComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [ShowTaskScheduleComponent, LoadingComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
MatDividerModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatButtonModule,
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
ReactiveFormsModule,
MatProgressSpinnerModule,
MatDialogModule,
MatSelectModule,
MatTabsModule,
MatAutocompleteModule,
MatListModule,
MatCardModule,
MatMenuModule,
MatTreeModule,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: { data: { id: 123 } } },
{ provide: ConfigService, useValue: mockConfigService },
{ provide: ActivatedRoute, useValue: { queryParams: { subscribe: () => {} } } },
]
}).compileComponents();
fixture = TestBed.createComponent(ShowTaskScheduleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,107 +0,0 @@
import {Component, Inject, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {Client} from "../../../groups/model/model";
import {ToastrService} from "ngx-toastr";
import {HttpClient} from "@angular/common/http";
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog";
import {ConfigService} from "@services/config.service";
import {DeleteModalComponent} from "../../../../shared/delete_modal/delete-modal/delete-modal.component";
import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component";
import {DatePipe} from "@angular/common";
@Component({
selector: 'app-show-task-schedule',
templateUrl: './show-task-schedule.component.html',
styleUrl: './show-task-schedule.component.css'
})
export class ShowTaskScheduleComponent implements OnInit{
baseUrl: string;
dataSource = new MatTableDataSource<any>([]);
length = 0;
itemsPerPage: number = 10;
pageSizeOptions: number[] = [5, 10, 20];
page = 0;
loading: boolean = false;
filters: { [key: string]: string } = {};
datePipe: DatePipe = new DatePipe('es-ES');
columns = [
{ columnDef: 'id', header: 'ID', cell: (schedule: any) => schedule.id },
{ columnDef: 'recurrenceType', header: 'Recurrencia', cell: (schedule: any) => schedule.recurrenceType },
{ columnDef: 'time', header: 'Hora de ejecución', cell: (schedule: any) => this.datePipe.transform(schedule.executionTime, 'HH:mm', 'UTC') },
{ columnDef: 'daysOfWeek', header: 'Dias de la semana', cell: (schedule: any) => schedule.recurrenceDetails.daysOfWeek },
{ columnDef: 'months', header: 'Meses', cell: (schedule: any) => schedule.recurrenceDetails.months },
{ columnDef: 'enabled', header: 'Activo', cell: (schedule: any) => schedule.enabled }
];
displayedColumns: string[] = ['id', 'recurrenceType', 'time', 'daysOfWeek', 'months', 'enabled', 'actions'];
constructor(
private toastService: ToastrService,
private http: HttpClient,
public dialogRef: MatDialogRef<ShowTaskScheduleComponent>,
public dialog: MatDialog,
private configService: ConfigService,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
}
ngOnInit(): void {
if (this.data) {
this.loadData();
}
}
loadData() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/command-task-schedules?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}&commandTask.id=${this.data.commandTask?.id}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
this.loading = false;
}
);
}
editSchedule(schedule: any): void {
this.dialog.open(CreateTaskScheduleComponent, {
width: '800px',
data: { schedule: schedule, task: this.data.commandTask }
}).afterClosed().subscribe(() => this.loadData());
}
deleteSchedule(schedule: any): void {
const dialogRef = this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: 'tarea programada' }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.http.delete(`${this.baseUrl}${schedule['@id']}`).subscribe(
() => {
this.toastService.success('Programación eliminada correctamente');
this.loadData();
},
(error) => {
this.toastService.error(error.error['hydra:description']);
}
);
}
})
}
onNoClick(): void {
this.dialogRef.close(false);
}
onPageChange(event: any) {
this.page = event.pageIndex;
this.itemsPerPage = event.pageSize;
this.loadData()
}
}

View File

@ -1,89 +0,0 @@
.full-width {
width: 100%;
}
form {
padding: 20px;
}
.spacing-container {
margin-top: 20px;
margin-bottom: 16px;
}
.list-item-content {
display: flex;
align-items: flex-start;
justify-content: space-between;
width: 100%;
}
.text-content {
flex-grow: 1;
margin-right: 16px;
margin-left: 10px;
}
.icon-container {
display: flex;
align-items: center;
}
.right-icon {
margin-left: 8px;
cursor: pointer;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.lists-container {
padding: 16px;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
margin: 1.5rem 0rem 1.5rem 0rem;
box-sizing: border-box;
}
.search-string {
flex: 1;
padding: 5px;
}
.search-select {
flex: 1;
padding: 5px;
}
table {
width: 100%;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
mat-spinner {
margin: 0 auto;
align-self: center;
}
.subnets-button-row {
display: flex;
gap: 15px;
}

View File

@ -1,70 +0,0 @@
<app-loading [isLoading]="loading"></app-loading>
<h2 mat-dialog-title>Gestionar scripts de tareas en {{ data.commandTask?.name }}</h2>
<mat-dialog-content>
<div class="search-container">
<mat-form-field appearance="fill" class="search-string" joyrideStep="searchNameStep"
text="Busca subredes por nombre para localizar una subred específica rápidamente.">
<mat-label i18n="@@searchLabel">Buscar contenido de script</mat-label>
<input matInput placeholder="Búsqueda" [(ngModel)]="filters['name']" i18n-placeholder="@@searchPlaceholder"
(keyup.enter)="loadData()" i18n-placeholder="@@searchPlaceholder">
<mat-icon matSuffix>search</mat-icon>
<button *ngIf="filters['name']" mat-icon-button matSuffix aria-label="Clear tree search"
(click)="filters['name'] = ''; loadData()">
<mat-icon>close</mat-icon>
</button>
<mat-hint i18n="@@searchHint">Pulsar 'enter' para buscar</mat-hint>
</mat-form-field>
</div>
<app-loading [isLoading]="loading"></app-loading>
<table *ngIf="!loading" mat-table [dataSource]="dataSource" class="mat-elevation-z8" joyrideStep="tableStep"
text="Visualiza y administra las subredes listadas según los filtros aplicados.">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let schedule">
<ng-container *ngIf="column.columnDef === 'content'; else checkOtherColumn">
<div style="background-color: #f5f5f5; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-family: monospace; white-space: pre-wrap; font-size: 13px;">
{{ column.cell(schedule) }}
</div>
</ng-container>
<ng-template #checkOtherColumn>
<ng-container *ngIf="column.columnDef === 'parameters'; else normalCell">
<button mat-stroked-button color="primary" (click)="openParametersModal(schedule.parameters)">
Ver parámetros
</button>
</ng-container>
</ng-template>
<ng-template #normalCell>
{{ column.cell(schedule) }}
</ng-template>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: center;">Acciones</th>
<td mat-cell *matCellDef="let schedule" style="text-align: center;">
<button mat-icon-button color="warn" (click)="deleteTaskScript(schedule)">
<mat-icon i18n="@@deleteElementTooltip">delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<div class="paginator-container" joyrideStep="paginationStep"
text="Navega entre las páginas de subredes usando el paginador.">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>
</mat-dialog-content>
<mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="onNoClick()">Cerrar</button>
</mat-dialog-actions>

View File

@ -1,86 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ShowTaskScriptComponent } from './show-task-script.component';
import {LoadingComponent} from "../../../../shared/loading/loading.component";
import {HttpClientTestingModule} from "@angular/common/http/testing";
import {ToastrModule} from "ngx-toastr";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatDividerModule} from "@angular/material/divider";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatIconModule} from "@angular/material/icon";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
import {MatPaginatorModule} from "@angular/material/paginator";
import {MatTooltipModule} from "@angular/material/tooltip";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatSelectModule} from "@angular/material/select";
import {MatTabsModule} from "@angular/material/tabs";
import {MatAutocompleteModule} from "@angular/material/autocomplete";
import {MatListModule} from "@angular/material/list";
import {MatCardModule} from "@angular/material/card";
import {MatMenuModule} from "@angular/material/menu";
import {MatTreeModule} from "@angular/material/tree";
import {TranslateModule} from "@ngx-translate/core";
import {JoyrideModule} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute} from "@angular/router";
import {ShowTaskScheduleComponent} from "../show-task-schedule/show-task-schedule.component";
describe('ShowTaskScriptComponent', () => {
let component: ShowTaskScriptComponent;
let fixture: ComponentFixture<ShowTaskScriptComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [ShowTaskScriptComponent, LoadingComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
MatDividerModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatButtonModule,
MatTableModule,
MatPaginatorModule,
MatTooltipModule,
FormsModule,
ReactiveFormsModule,
MatProgressSpinnerModule,
MatDialogModule,
MatSelectModule,
MatTabsModule,
MatAutocompleteModule,
MatListModule,
MatCardModule,
MatMenuModule,
MatTreeModule,
TranslateModule.forRoot(),
JoyrideModule.forRoot(),
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: { data: { id: 123 } } },
{ provide: ConfigService, useValue: mockConfigService },
{ provide: ActivatedRoute, useValue: { queryParams: { subscribe: () => {} } } },
]
}).compileComponents();
fixture = TestBed.createComponent(ShowTaskScriptComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,104 +0,0 @@
import {Component, Inject, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {ToastrService} from "ngx-toastr";
import {HttpClient} from "@angular/common/http";
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog";
import {ConfigService} from "@services/config.service";
import {CreateTaskScheduleComponent} from "../create-task-schedule/create-task-schedule.component";
import {DeleteModalComponent} from "../../../../shared/delete_modal/delete-modal/delete-modal.component";
import {ViewParametersModalComponent} from "./view-parameters-modal/view-parameters-modal.component";
@Component({
selector: 'app-show-task-script',
templateUrl: './show-task-script.component.html',
styleUrl: './show-task-script.component.css'
})
export class ShowTaskScriptComponent implements OnInit{
baseUrl: string;
dataSource = new MatTableDataSource<any>([]);
length = 0;
itemsPerPage: number = 10;
pageSizeOptions: number[] = [5, 10, 20];
page = 0;
loading: boolean = false;
filters: { [key: string]: string } = {};
columns = [
{ columnDef: 'id', header: 'ID', cell: (client: any) => client.id },
{ columnDef: 'order', header: 'Orden', cell: (client: any) => client.order },
{ columnDef: 'content', header: 'Script', cell: (client: any) => client.content },
{ columnDef: 'type', header: 'Type', cell: (client: any) => client.type },
{ columnDef: 'parameters', header: 'Parameters', cell: (client: any) => client.parameters },
];
displayedColumns: string[] = ['id', 'order', 'type', 'parameters', 'content', 'actions'];
constructor(
private toastService: ToastrService,
private http: HttpClient,
public dialogRef: MatDialogRef<ShowTaskScriptComponent>,
public dialog: MatDialog,
private configService: ConfigService,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
}
ngOnInit(): void {
if (this.data) {
this.loadData();
}
}
loadData() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/command-task-scripts?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}&commandTask.id=${this.data.commandTask?.id}`, { params: this.filters }).subscribe(
(data) => {
this.dataSource.data = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.loading = false;
},
(error) => {
this.loading = false;
}
);
}
deleteTaskScript(schedule: any): void {
const dialogRef = this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: 'script de una tarea' }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.http.delete(`${this.baseUrl}${schedule['@id']}`).subscribe(
() => {
this.toastService.success('Eliminado correctamente');
this.loadData();
},
(error) => {
this.toastService.error(error.error['hydra:description']);
}
);
}
})
}
onNoClick(): void {
this.dialogRef.close(false);
}
openParametersModal(parameters: any): void {
this.dialog.open(ViewParametersModalComponent, {
width: '900px',
data: parameters
});
}
onPageChange(event: any) {
this.page = event.pageIndex;
this.itemsPerPage = event.pageSize;
this.loadData()
}
}

View File

@ -1,7 +0,0 @@
<h2 mat-dialog-title>Parámetros</h2>
<mat-dialog-content>
<pre>{{ data | json }}</pre>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="close()">Cerrar</button>
</mat-dialog-actions>

View File

@ -1,69 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ViewParametersModalComponent } from './view-parameters-modal.component';
import {LoadingComponent} from "../../../../../shared/loading/loading.component";
import {HttpClientTestingModule, provideHttpClientTesting} from "@angular/common/http/testing";
import {ToastrModule, ToastrService} from "ngx-toastr";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatDividerModule} from "@angular/material/divider";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatIconModule} from "@angular/material/icon";
import {MatButtonModule} from "@angular/material/button";
import {MatTableModule} from "@angular/material/table";
import {MatPaginatorModule} from "@angular/material/paginator";
import {MatTooltipModule} from "@angular/material/tooltip";
import {FormBuilder, FormsModule, ReactiveFormsModule} from "@angular/forms";
import {MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatSelectModule} from "@angular/material/select";
import {MatTabsModule} from "@angular/material/tabs";
import {MatAutocompleteModule} from "@angular/material/autocomplete";
import {MatListModule} from "@angular/material/list";
import {MatCardModule} from "@angular/material/card";
import {MatMenuModule} from "@angular/material/menu";
import {MatTreeModule} from "@angular/material/tree";
import {TranslateModule} from "@ngx-translate/core";
import {JoyrideModule} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute} from "@angular/router";
import {InputDialogComponent} from "../../../../task-logs/input-dialog/input-dialog.component";
import {provideHttpClient} from "@angular/common/http";
describe('ViewParametersModalComponent', () => {
let component: ViewParametersModalComponent;
let fixture: ComponentFixture<ViewParametersModalComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ViewParametersModalComponent],
imports: [
MatDialogModule,
TranslateModule.forRoot(),
],
providers: [
FormBuilder,
ToastrService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {}
}
]
})
.compileComponents();
fixture = TestBed.createComponent(ViewParametersModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

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-parameters-modal',
templateUrl: './view-parameters-modal.component.html',
styleUrl: './view-parameters-modal.component.css'
})
export class ViewParametersModalComponent {
constructor(
public dialogRef: MatDialogRef<ViewParametersModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {}
close(): void {
this.dialogRef.close();
}
}

View File

@ -0,0 +1,118 @@
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
margin-left: 1em;
}
.calendar-button-row {
display: flex;
gap: 15px;
}
.lists-container {
padding: 16px;
}
.imagesLists-container {
flex: 1;
}
.card.unidad-card {
height: 100%;
box-sizing: border-box;
}
table {
width: 100%;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
margin: 1.5rem 0rem 1.5rem 0rem;
box-sizing: border-box;
}
.search-string {
flex: 1;
padding: 5px;
}
.search-boolean {
flex: 1;
padding: 5px;
}
.search-select {
flex: 2;
padding: 5px;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2);
}
.progress-container {
display: flex;
align-items: center;
gap: 10px;
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
.chip-failed {
background-color: #e87979 !important;
color: white;
}
.chip-success {
background-color: #46c446 !important;
color: white;
}
.chip-pending {
background-color: #bebdbd !important;
color: black;
}
.chip-in-progress {
background-color: #f5a623 !important;
color: white;
}
.status-progress-flex {
display: flex;
align-items: center;
gap: 8px;
}
button.cancel-button {
display: flex;
align-items: center;
justify-content: center;
padding: 5px;
}
.cancel-button {
color: red;
background-color: transparent;
border: none;
padding: 0;
}
.cancel-button mat-icon {
color: red;
}

View File

@ -0,0 +1,128 @@
<div class="header-container">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="titleStep" text="{{ 'titleStepText' | translate }}">{{ 'adminCommandsTitle' |
translate }}</h2>
</div>
<div class="images-button-row">
<button class="action-button" (click)="resetFilters()" joyrideStep="resetFiltersStep"
text="{{ 'resetFiltersStepText' | translate }}">
{{ 'resetFilters' | translate }}
</button>
</div>
</div>
<div class="search-container">
<mat-form-field appearance="fill" class="search-select" joyrideStep="clientSelectStep"
text="{{ 'clientSelectStepText' | translate }}">
<input type="text" matInput [formControl]="clientControl" [matAutocomplete]="clientAuto"
placeholder="{{ 'filterClientPlaceholder' | translate }}">
<mat-autocomplete #clientAuto="matAutocomplete" [displayWith]="displayFnClient"
(optionSelected)="onOptionClientSelected($event.option.value)">
<mat-option *ngFor="let client of filteredClients | async" [value]="client">
{{ client.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field appearance="fill" class="search-select" joyrideStep="commandSelectStep"
text="{{ 'commandSelectStepText' | translate }}">
<input type="text" matInput [formControl]="commandControl" [matAutocomplete]="commandAuto"
placeholder="{{ 'filterCommandPlaceholder' | translate }}">
<mat-autocomplete #commandAuto="matAutocomplete" [displayWith]="displayFnCommand"
(optionSelected)="onOptionCommandSelected($event.option.value)">
<mat-option *ngFor="let command of filteredCommands | async" [value]="command">
{{ command.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field appearance="fill" class="search-boolean">
<mat-label i18n="@@searchLabel">Estado</mat-label>
<mat-select [(ngModel)]="filters['status']" (selectionChange)="loadTraces()" placeholder="Seleccionar opción">
<mat-option [value]="undefined">Todos</mat-option>
<mat-option [value]="'failed'">Fallido</mat-option>
<mat-option [value]="'pending'">Pendiente de ejecutar</mat-option>
<mat-option [value]="'in-progress'">Ejecutando</mat-option>
<mat-option [value]="'success'">Completado con éxito</mat-option>
<mat-option [value]="'cancelled'">Cancelado</mat-option>
</mat-select>
</mat-form-field>
</div>
<app-loading [isLoading]="loading"></app-loading>
<div *ngIf="!loading">
<table mat-table [dataSource]="traces" class="mat-elevation-z8" joyrideStep="tableStep"
text="{{ 'tableStepText' | translate }}">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef> {{ column.header }} </th>
<td mat-cell *matCellDef="let trace">
<ng-container [ngSwitch]="column.columnDef">
<ng-container *ngSwitchCase="'status'">
<ng-container *ngIf="trace.status === 'in-progress' && trace.progress; else statusChip">
<div class="progress-container">
<mat-progress-bar class="example-margin" [mode]="mode" [value]="trace.progress" [bufferValue]="bufferValue">
</mat-progress-bar>
<span>{{trace.progress}}%</span>
</div>
</ng-container>
<ng-template #statusChip>
<div class="status-progress-flex">
<mat-chip [ngClass]="{
'chip-failed': trace.status === 'failed',
'chip-success': trace.status === 'success',
'chip-pending': trace.status === 'pending',
'chip-in-progress': trace.status === 'in-progress',
'chip-cancelled': trace.status === 'cancelled'
}">
{{
trace.status === 'failed' ? 'Fallido' :
trace.status === 'in-progress' ? 'En ejecución' :
trace.status === 'success' ? 'Finalizado con éxito' :
trace.status === 'pending' ? 'Pendiente de ejecutar' :
trace.status === 'cancelled' ? 'Cancelado' :
trace.status
}}
</mat-chip>
<button *ngIf="trace.status === 'in-progress' && trace.command === 'deploy-image'"
mat-icon-button
(click)="cancelTrace(trace)"
class="cancel-button"
matTooltip="Cancelar transmisión de imagen">
<mat-icon>cancel</mat-icon>
</button>
</div>
</ng-template>
</ng-container>
<ng-container *ngSwitchCase="'input'">
<button mat-icon-button (click)="openInputModal(trace.input)">
<mat-icon>info</mat-icon>
</button>
</ng-container>
<ng-container *ngSwitchDefault>
{{ column.cell(trace) }}
</ng-container>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div class="paginator-container" joyrideStep="paginationStep" text="{{ 'paginationStepText' | translate }}">
<mat-paginator [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page" [pageSizeOptions]="pageSizeOptions"
(page)="onPageChange($event)">
</mat-paginator>
</div>

View File

@ -0,0 +1,309 @@
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, forkJoin } from 'rxjs';
import { FormControl } from '@angular/forms';
import { map, startWith } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
import { JoyrideService } from 'ngx-joyride';
import { MatDialog } from "@angular/material/dialog";
import { InputDialogComponent } from "./input-dialog/input-dialog.component";
import { ProgressBarMode } from '@angular/material/progress-bar';
import { DeleteModalComponent } from "../../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-task-logs',
templateUrl: './task-logs.component.html',
styleUrls: ['./task-logs.component.css']
})
export class TaskLogsComponent implements OnInit {
baseUrl: string;
mercureUrl: string;
traces: any[] = [];
groupedTraces: any[] = [];
commands: any[] = [];
clients: any[] = [];
length: number = 0;
itemsPerPage: number = 20;
page: number = 0;
loading: boolean = true;
pageSizeOptions: number[] = [10, 20, 30, 50];
datePipe: DatePipe = new DatePipe('es-ES');
mode: ProgressBarMode = 'buffer';
progress = 0;
bufferValue = 0;
columns = [
{
columnDef: 'id',
header: 'ID',
cell: (trace: any) => `${trace.id}`,
},
{
columnDef: 'command',
header: 'Comando',
cell: (trace: any) => `${trace.command}`
},
{
columnDef: 'client',
header: 'Client',
cell: (trace: any) => `${trace.client?.name}`
},
{
columnDef: 'status',
header: 'Estado',
cell: (trace: any) => `${trace.status}`
},
{
columnDef: 'jobId',
header: 'Hilo de trabajo',
cell: (trace: any) => `${trace.jobId}`
},
{
columnDef: 'input',
header: 'Input',
cell: (trace: any) => `${trace.input}`
},
{
columnDef: 'output',
header: 'Logs',
cell: (trace: any) => `${trace.output}`
},
{
columnDef: 'executedAt',
header: 'Programación de ejecución',
cell: (trace: any) => `${this.datePipe.transform(trace.executedAt, 'dd/MM/yyyy hh:mm:ss')}`,
},
{
columnDef: 'finishedAt',
header: 'Finalización',
cell: (trace: any) => `${this.datePipe.transform(trace.finishedAt, 'dd/MM/yyyy hh:mm:ss')}`,
},
];
displayedColumns = [...this.columns.map(column => column.columnDef)];
filters: { [key: string]: string } = {};
filteredClients!: Observable<any[]>;
clientControl = new FormControl();
filteredCommands!: Observable<any[]>;
commandControl = new FormControl();
constructor(private http: HttpClient,
private joyrideService: JoyrideService,
private dialog: MatDialog,
private cdr: ChangeDetectorRef,
private configService: ConfigService,
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
this.mercureUrl = this.configService.mercureUrl;
}
ngOnInit(): void {
this.loadTraces();
this.loadCommands();
//this.loadClients();
this.filteredCommands = this.commandControl.valueChanges.pipe(
startWith(''),
map(value => (typeof value === 'string' ? value : value?.name)),
map(name => (name ? this._filterCommands(name) : this.commands.slice()))
);
this.filteredClients = this.clientControl.valueChanges.pipe(
startWith(''),
map(value => (typeof value === 'string' ? value : value?.name)),
map(name => (name ? this._filterClients(name) : this.clients.slice()))
);
const eventSource = new EventSource(`${this.mercureUrl}?topic=`
+ encodeURIComponent(`traces`));
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data && data['@id']) {
this.updateTracesStatus(data['@id'], data.status, data.progress);
}
}
}
private updateTracesStatus(clientUuid: string, newStatus: string, progress: Number): void {
const traceIndex = this.traces.findIndex(trace => trace['@id'] === clientUuid);
if (traceIndex !== -1) {
const updatedTraces = [...this.traces];
updatedTraces[traceIndex] = {
...updatedTraces[traceIndex],
status: newStatus,
progress: progress
};
this.traces = updatedTraces;
this.cdr.detectChanges();
console.log(`Estado actualizado para la traza ${clientUuid}: ${newStatus}`);
} else {
console.warn(`Traza con UUID ${clientUuid} no encontrado en la lista.`);
}
}
private _filterClients(name: string): any[] {
const filterValue = name.toLowerCase();
return this.clients.filter(client => client.name.toLowerCase().includes(filterValue));
}
private _filterCommands(name: string): any[] {
const filterValue = name.toLowerCase();
return this.commands.filter(command => command.name.toLowerCase().includes(filterValue));
}
displayFnClient(client: any): string {
return client && client.name ? client.name : '';
}
displayFnCommand(command: any): string {
return command && command.name ? command.name : '';
}
onOptionCommandSelected(selectedCommand: any): void {
this.filters['command.id'] = selectedCommand.id;
this.loadTraces();
}
onOptionClientSelected(selectedClient: any): void {
this.filters['client.id'] = selectedClient.id;
this.loadTraces();
}
openInputModal(inputData: any): void {
this.dialog.open(InputDialogComponent, {
width: '700px',
data: { input: inputData }
});
}
cancelTrace(trace: any): void {
this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: trace.jobId },
}).afterClosed().subscribe((result) => {
if (result) {
this.http.post(`${this.baseUrl}/traces/server/${trace.uuid}/cancel`, {}).subscribe({
next: () => {
this.toastService.success('Transmision de imagen cancelada');
this.loadTraces();
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
console.error(error.error['hydra:description']);
}
});
}
});
}
loadTraces(): void {
this.loading = true;
const url = `${this.baseUrl}/traces?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`;
const params = { ...this.filters };
if (params['status'] === undefined) {
delete params['status'];
}
this.http.get<any>(url, { params }).subscribe(
(data) => {
this.traces = data['hydra:member'];
this.length = data['hydra:totalItems'];
this.groupedTraces = this.groupByCommandId(this.traces);
this.loading = false;
},
(error) => {
console.error('Error fetching traces', error);
this.loading = false;
}
);
}
loadCommands() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/commands?&page=1&itemsPerPage=10000`).subscribe(
response => {
this.commands = response['hydra:member'];
this.loading = false;
},
error => {
console.error('Error fetching commands:', error);
this.loading = false;
}
);
}
loadClients() {
this.loading = true;
this.http.get<any>(`${this.baseUrl}/clients?&page=1&itemsPerPage=10000`).subscribe(
response => {
const clientIds = response['hydra:member'].map((client: any) => client['@id']);
const clientDetailsRequests: Observable<any>[] = clientIds.map((id: string) => this.http.get<any>(`${this.baseUrl}${id}`));
forkJoin(clientDetailsRequests).subscribe(
(clients: any[]) => {
this.clients = clients;
this.loading = false;
},
(error: any) => {
console.error('Error fetching client details:', error);
this.loading = false;
}
);
},
(error: any) => {
console.error('Error fetching clients:', error);
this.loading = false;
}
);
}
resetFilters() {
this.loading = true;
this.filters = {};
this.loadTraces();
}
groupByCommandId(traces: any[]): any[] {
const grouped: { [key: string]: any[] } = {};
traces.forEach(trace => {
const commandId = trace.command.id;
if (!grouped[commandId]) {
grouped[commandId] = [];
}
grouped[commandId].push(trace);
});
return Object.keys(grouped).map(key => ({
commandId: key,
traces: grouped[key]
}));
}
onPageChange(event: any): void {
this.page = event.pageIndex;
this.itemsPerPage = event.pageSize;
this.length = event.length;
this.loadTraces();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'resetFiltersStep',
'clientSelectStep',
'commandSelectStep',
'tableStep',
'paginationStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}

View File

@ -75,7 +75,6 @@ export class CreateCommandComponent implements OnInit{
readOnly: this.createCommandForm.value.readOnly,
enabled: this.createCommandForm.value.enabled,
comments: this.createCommandForm.value.comments,
parameters: this.createCommandForm.value.parameters,
};
if (this.commandId) {

View File

@ -1,117 +0,0 @@
.dialog-content {
display: flex;
flex-direction: column;
padding: 40px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.select-container {
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.button-row {
display: flex;
padding-right: 1em;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.client-item {
position: relative;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.loading-spinner {
display: block;
margin: 0 auto;
align-items: center;
justify-content: center;
}
.client-details {
margin-top: 4px;
}
.client-name {
font-size: 0.9em;
font-weight: 600;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
display: block;
font-size: 0.9em;
color: #666;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
@media (max-width: 600px) {
.form-field {
width: 100%;
}
.dialog-actions {
flex-direction: column;
align-items: stretch;
}
button {
width: 100%;
margin-left: 0;
margin-bottom: 8px;
}
}

View File

@ -1,100 +0,0 @@
<h2 mat-dialog-title> Seleccionar particion para arrancar SO</h2>
<mat-dialog-content class="dialog-content">
<mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<div *ngIf="!loading" class="select-container">
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title> Clientes </mat-panel-title>
<mat-panel-description>
Listado de clientes para arrancar un SO
<mat-icon>desktop_windows</mat-icon>
</mat-panel-description>
</mat-expansion-panel-header>
<div class="button-row">
<button class="action-button" (click)="toggleSelectAll()">
{{ allSelected ? 'Desmarcar todos' : 'Marcar todos' }}
</button>
</div>
<div class="clients-grid">
<div *ngFor="let client of data.clients" class="client-item">
<div class="client-card"
(click)="toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}" >
<img
[src]="'assets/images/computer_' + client.status + '.svg'"
alt="Client Icon"
class="client-image" />
<div class="client-details">
<span class="client-name">{{ client.name | slice:0:20 }}</span>
<span class="client-ip">{{ client.ip }}</span>
<span class="client-ip">{{ client.mac }}</span>
</div>
<mat-divider></mat-divider>
<mat-radio-group [(ngModel)]="selectedModelClient" (change)="loadPartitions(selectedModelClient)">
<mat-radio-button [value]="client"
color="primary"
[disabled]="!client.selected"
(click)="$event.stopPropagation()">
Modelo
</mat-radio-button>
</mat-radio-group>
</div>
</div>
</div>
</mat-expansion-panel>
</div>
<mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider>
<div *ngIf="!loading" class="partition-table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">Seleccionar partición</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group
[(ngModel)]="selectedPartition"
[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 }} </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>
</mat-dialog-content>
<div mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">Cancelar</button>
<button class="submit-button" (click)="execute()" [disabled]="!selectedPartition">Ejecutar</button>
</div>

View File

@ -1,82 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BootSoPartitionComponent } from './boot-so-partition.component';
import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from "@angular/material/dialog";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatCheckboxModule } from "@angular/material/checkbox";
import { MatButtonModule } from "@angular/material/button";
import { MatMenuModule } from "@angular/material/menu";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { MatTableModule } from "@angular/material/table";
import { MatSelectModule } from "@angular/material/select";
import { MatIconModule } from "@angular/material/icon";
import { ToastrModule, ToastrService } from "ngx-toastr";
import { TranslateModule } from "@ngx-translate/core";
import { DataService } from "../../data.service";
import { provideHttpClient } from "@angular/common/http";
import { provideHttpClientTesting } from "@angular/common/http/testing";
import { ConfigService } from "@services/config.service";
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDividerModule } from '@angular/material/divider';
describe('BootSoPartitionComponent', () => {
let component: BootSoPartitionComponent;
let fixture: ComponentFixture<BootSoPartitionComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [BootSoPartitionComponent],
imports: [
ReactiveFormsModule,
FormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
MatCheckboxModule,
MatButtonModule,
MatExpansionModule,
MatMenuModule,
BrowserAnimationsModule,
MatTableModule,
MatDividerModule,
MatSelectModule,
MatIconModule,
ToastrModule.forRoot(),
TranslateModule.forRoot()
],
providers: [
FormBuilder,
ToastrService,
DataService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {
clients: []
}
},
{ provide: ConfigService, useValue: mockConfigService }
]
})
.compileComponents();
fixture = TestBed.createComponent(BootSoPartitionComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,146 +0,0 @@
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { MatTableDataSource } from "@angular/material/table";
import { ConfigService } from "@services/config.service";
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
@Component({
selector: 'app-boot-so-partition',
templateUrl: './boot-so-partition.component.html',
styleUrl: './boot-so-partition.component.css'
})
export class BootSoPartitionComponent implements OnInit {
baseUrl: string;
selectedPartition: any = null;
dataSource = new MatTableDataSource<any>();
clientId: string | null = null;
selectedClients: any[] = [];
selectedModelClient: any = null;
filteredPartitions: any[] = [];
allSelected: boolean = false;
clientData: any[] = [];
loading: boolean = false;
columns = [
{
columnDef: 'diskNumber',
header: 'Disco',
cell: (partition: any) => partition.diskNumber
},
{
columnDef: 'partitionNumber',
header: 'Particion',
cell: (partition: any) => partition.partitionNumber
},
{
columnDef: 'size',
header: 'Tamaño',
cell: (partition: any) => `${partition.size} MB`
},
{
columnDef: 'partitionCode',
header: 'Tipo de partición',
cell: (partition: any) => partition.partitionCode
},
{
columnDef: 'filesystem',
header: 'Sistema de ficheros',
cell: (partition: any) => partition.filesystem
},
{
columnDef: 'operativeSystem',
header: 'SO',
cell: (partition: any) => partition.operativeSystem?.name
}
];
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
constructor(
@Inject(MAT_DIALOG_DATA) public data: { clients: any },
private dialogRef: MatDialogRef<BootSoPartitionComponent>,
private configService: ConfigService,
private http: HttpClient,
private toastService: ToastrService,
) {
this.baseUrl = this.configService.apiUrl;
this.clientId = this.data.clients?.length ? this.data.clients[0]['@id'] : null;
this.data.clients.forEach((client: { selected: boolean; status: string }) => client.selected = true);
this.selectedClients = this.data.clients.filter((client: { selected: boolean }) => client.selected);
this.selectedModelClient = this.data.clients.find((client: { selected: boolean }) => client.selected) || null;
if (this.selectedModelClient) {
this.loadPartitions(this.selectedModelClient);
}
}
ngOnInit() {
}
loadPartitions(client: any) {
const url = `${this.baseUrl}${client.uuid}`;
this.http.get(url).subscribe(
(response: any) => {
if (response.partitions) {
this.dataSource.data = response.partitions.filter((partition: any) => {
return partition.partitionNumber !== 0;
});
}
},
(error) => {
console.error('Error al cargar los datos del cliente:', error);
}
);
}
toggleClientSelection(client: any) {
client.selected = !client.selected;
this.updateSelectedClients();
}
updateSelectedClients() {
this.selectedClients = this.data.clients.filter(
(client: { selected: boolean; state: string }) => client.selected && client.state === "og-live"
);
if (!this.selectedClients.includes(this.selectedModelClient)) {
this.selectedModelClient = null;
this.filteredPartitions = [];
}
}
toggleSelectAll() {
this.allSelected = !this.allSelected;
this.data.clients.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected;
}
});
}
close() {
this.dialogRef.close();
}
execute(): void {
this.loading = true;
this.http.post(`${this.baseUrl}/clients/server/boot-client`, {
clients: this.selectedClients.map((client: any) => client.uuid),
partition: this.selectedPartition['@id']
}).subscribe(
response => {
this.toastService.success('Cliente actualizado correctamente');
this.dialogRef.close();
this.loading = false;
},
error => {
this.toastService.error(error.error['hydra:description']);
this.loading = false;
}
);
}
}

View File

@ -8,17 +8,12 @@
[matMenuTriggerFor]="commandMenu">
{{ buttonText }}
</button>
<button mat-menu-item *ngSwitchCase="'menu-item'" [matMenuTriggerFor]="commandMenu" [disabled]="disabled">
<mat-icon>{{ icon }}</mat-icon>
<span>{{ buttonText }}</span>
</button>
</ng-container>
<mat-menu #commandMenu="matMenu">
<button mat-menu-item [disabled]="command.disabled
|| (command.slug === 'create-image' && clientData.length > 1)" *ngFor="let command of arrayCommands"
(click)="onCommandSelect(command.slug)">
{{ command.translationKey | translate }}
|| (command.slug === 'create-image' && clientData.length > 1)"
*ngFor="let command of arrayCommands" (click)="onCommandSelect(command.slug)">
{{ command.name }}
</button>
</mat-menu>
</mat-menu>

View File

@ -3,11 +3,6 @@ import { HttpClient } from '@angular/common/http';
import { Router } from "@angular/router";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';
import { BootSoPartitionComponent } from "./boot-so-partition/boot-so-partition.component";
import { MatDialog } from "@angular/material/dialog";
import { RemoveCacheImageComponent } from "./remove-cache-image/remove-cache-image.component";
import { AuthService } from '@services/auth.service';
import {SoftwareProfilePartitionComponent} from "./software-profile-partition/software-profile-partition.component";
@Component({
selector: 'app-execute-command',
@ -15,10 +10,8 @@ import {SoftwareProfilePartitionComponent} from "./software-profile-partition/so
styleUrls: ['./execute-command.component.css']
})
export class ExecuteCommandComponent implements OnInit {
@Input() runScriptContext: any = null;
@Input() clientState: string = 'off';
@Input() clientData: any[] = [];
@Input() buttonType: 'icon' | 'text' | 'menu-item' = 'icon';
@Input() buttonType: 'icon' | 'text' = 'icon';
@Input() buttonText: string = 'Ejecutar Comandos';
@Input() icon: string = 'terminal';
@Input() disabled: boolean = false;
@ -26,17 +19,17 @@ export class ExecuteCommandComponent implements OnInit {
loading: boolean = true;
arrayCommands: any[] = [
{ translationKey: 'executeCommands.powerOn', slug: 'power-on', disabled: false },
{ translationKey: 'executeCommands.powerOff', slug: 'power-off', disabled: false },
{ translationKey: 'executeCommands.reboot', slug: 'reboot', disabled: false },
{ translationKey: 'executeCommands.login', slug: 'login', disabled: true },
{ translationKey: 'executeCommands.createImage', slug: 'create-image', disabled: false },
{ translationKey: 'executeCommands.deployImage', slug: 'deploy-image', disabled: false },
{ translationKey: 'executeCommands.deleteImageCache', slug: 'remove-cache-image', disabled: false },
{ translationKey: 'executeCommands.partition', slug: 'partition', disabled: false },
{ translationKey: 'executeCommands.softwareInventory', slug: 'software-inventory', disabled: false },
{ translationKey: 'executeCommands.hardwareInventory', slug: 'hardware-inventory', disabled: true },
{ translationKey: 'executeCommands.runScript', slug: 'run-script', disabled: false },
{ name: 'Enceder', slug: 'power-on', disabled: false },
{ name: 'Apagar', slug: 'power-off', disabled: false },
{ name: 'Reiniciar', slug: 'reboot', disabled: false },
{ name: 'Iniciar Sesión', slug: 'login', disabled: true },
{ name: 'Crear imagen', slug: 'create-image', disabled: false },
{ name: 'Clonar/desplegar imagen', slug: 'deploy-image', disabled: false },
{ name: 'Eliminar Imagen Cache', slug: 'delete-image-cache', disabled: true },
{ name: 'Particionar y Formatear', slug: 'partition', disabled: false },
{ name: 'Inventario Software', slug: 'software-inventory', disabled: true },
{ name: 'Inventario Hardware', slug: 'hardware-inventory', disabled: true },
{ name: 'Ejecutar comando', slug: 'run-script', disabled: false },
];
client: any = {};
@ -45,88 +38,13 @@ export class ExecuteCommandComponent implements OnInit {
private http: HttpClient,
private router: Router,
private configService: ConfigService,
private toastService: ToastrService,
public auth: AuthService,
private dialog: MatDialog,
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
}
ngOnInit(): void {
this.clientData = this.clientData || [];
const allowed = this.getAllowedCommandsByRole();
this.arrayCommands = this.arrayCommands.filter(c => allowed.includes(c.slug));
this.updateCommandStates();
}
ngOnChanges(): void {
this.updateCommandStates();
}
private getAllowedCommandsByRole(): string[] {
const role = this.auth.userCategory;
const permissions: Record<string, string[]> = {
'super-admin': ['*'],
'ou-admin': ['*'],
'ou-operator': [
'power-on',
'power-off',
'reboot',
'login',
'deploy-image',
'software-inventory',
'hardware-inventory',
'remove-cache-image',
'partition'
],
'ou-minimal': [
'power-on',
'power-off'
]
};
const allowed = permissions[role] || [];
return allowed.includes('*') ? this.arrayCommands.map(c => c.slug) : allowed;
}
private updateCommandStates(): void {
let states: string[] = [];
if (this.clientData.length > 0) {
states = this.clientData.map(client => client.status);
} else if (this.clientState) {
states = [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;
this.arrayCommands = this.arrayCommands.map(command => {
if (allOffOrDisconnected) {
command.disabled = command.slug !== 'power-on';
} else if (allSameState) {
if (states[0] === 'off' || states[0] === 'disconnected') {
command.disabled = command.slug !== 'power-on';
} else {
command.disabled = !['power-off', 'reboot', 'login', 'create-image', 'deploy-image', 'remove-cache-image', 'partition', 'run-script', 'software-inventory'].includes(command.slug);
}
} else {
if (command.slug === 'create-image'|| command.slug === 'software-inventory') {
command.disabled = multipleClients;
} else if (
['power-on', 'power-off', 'reboot', 'login', 'deploy-image', 'partition', 'remove-cache-image', 'run-script'].includes(command.slug)
) {
command.disabled = false;
} else {
command.disabled = true;
}
}
return command;
});
}
onCommandSelect(action: any): void {
@ -161,18 +79,6 @@ export class ExecuteCommandComponent implements OnInit {
if (action === 'power-on') {
this.powerOnClient();
}
if (action === 'remove-cache-image') {
this.removeImageCache();
}
if (action === 'hardware-inventory') {
this.hardwareInventory();
}
if (action === 'software-inventory') {
this.softwareInventory();
}
}
rebootClient(): void {
@ -183,108 +89,24 @@ export class ExecuteCommandComponent implements OnInit {
this.toastService.success('Cliente actualizado correctamente');
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
this.toastService.error('Error de conexión con el cliente');
}
);
}
loginClient(): void {
const clientDataToSend = this.clientData.map(client => ({
name: client.name,
mac: client.mac,
uuid: '/clients/' + client.uuid,
status: client.status,
partitions: client.partitions,
firmwareType: client.firmwareType,
ip: client.ip
}));
const dialogRef = this.dialog.open(BootSoPartitionComponent, {
width: '70vw',
height: 'auto',
data: { clients: clientDataToSend }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.toastService.success('Petición de arranque de SO enviada correctamente');
}
});
}
removeImageCache(): void {
const clientDataToSend = this.clientData.map(client => ({
name: client.name,
mac: client.mac,
uuid: '/clients/' + client.uuid,
status: client.status,
partitions: client.partitions,
firmwareType: client.firmwareType,
ip: client.ip
}));
const dialogRef = this.dialog.open(RemoveCacheImageComponent, {
width: '70vw',
height: 'auto',
data: { clients: clientDataToSend }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.toastService.success('Petición de borrado de caché de imagen enviada correctamente');
}
});
}
hardwareInventory(): void {
if (this.clientData.length === 0) {
this.toastService.error('No hay clientes seleccionados');
return;
}
const clientId = this.clientData[0].uuid;
this.http.post(`${this.baseUrl}/clients/server/${clientId}/hardware-inventory`, {
this.http.post(`${this.baseUrl}/clients/server/login-client`, {
clients: this.clientData.map((client: any) => client['@id'])
}).subscribe(
response => {
this.toastService.success('Inventario de hardware actualizado correctamente');
this.toastService.success('Cliente actualizado correctamente');
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
this.toastService.error('Error de conexión con el cliente');
}
);
}
softwareInventory(): void {
if (this.clientData.length === 0) {
this.toastService.error('No hay clientes seleccionados');
return;
}
const clientDataToSend = {
clientId: this.clientData[0].uuid,
name: this.clientData[0].name,
mac: this.clientData[0].mac,
status: this.clientData[0].status,
partitions: this.clientData[0].partitions,
firmwareType: this.clientData[0].firmwareType,
ip: this.clientData[0].ip
}
const clientId = this.clientData[0].uuid;
const dialogRef = this.dialog.open(SoftwareProfilePartitionComponent, {
width: '70vw',
height: 'auto',
data: { client: clientDataToSend }
});
dialogRef.afterClosed().subscribe(result => {
});
}
powerOnClient(): void {
this.http.post(`${this.baseUrl}/image-repositories/wol`, {
clients: this.clientData.map((client: any) => client['@id'])
@ -293,7 +115,7 @@ export class ExecuteCommandComponent implements OnInit {
this.toastService.success('Petición de encendido enviada correctamente');
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
this.toastService.error('Error de conexión con el cliente');
}
);
}
@ -306,7 +128,7 @@ export class ExecuteCommandComponent implements OnInit {
this.toastService.success('Petición de apagado enviada correctamente');
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error de conexión con el cliente');
this.toastService.error('Error de conexión con el cliente');
}
);
}
@ -315,7 +137,7 @@ export class ExecuteCommandComponent implements OnInit {
const clientDataToSend = this.clientData.map(client => ({
name: client.name,
mac: client.mac,
uuid: '/clients/' + client.uuid,
uuid: '/clients/'+client.uuid,
status: client.status,
partitions: client.partitions,
firmwareType: client.firmwareType,
@ -323,10 +145,9 @@ export class ExecuteCommandComponent implements OnInit {
}));
this.router.navigate(['/clients/partition-assistant'], {
queryParams: {
clientData: JSON.stringify(clientDataToSend),
runScriptContext: JSON.stringify(this.runScriptContext)
}
queryParams: { clientData: JSON.stringify(clientDataToSend) }
}).then(r => {
console.log('Navigated to partition assistant with data:', this.clientData);
});
}
@ -340,17 +161,16 @@ export class ExecuteCommandComponent implements OnInit {
const clientDataToSend = this.clientData.map(client => ({
name: client.name,
mac: client.mac,
uuid: '/clients/' + client.uuid,
uuid: '/clients/'+client.uuid,
status: client.status,
partitions: client.partitions,
ip: client.ip
}));
this.router.navigate(['/clients/deploy-image'], {
queryParams: {
clientData: JSON.stringify(clientDataToSend),
runScriptContext: JSON.stringify(this.runScriptContext)
}
queryParams: { clientData: JSON.stringify(clientDataToSend) }
}).then(r => {
console.log('Navigated to deploy image with data:', this.clientData);
});
}
@ -358,17 +178,18 @@ export class ExecuteCommandComponent implements OnInit {
const clientDataToSend = this.clientData.map(client => ({
name: client.name,
mac: client.mac,
uuid: '/clients/' + client.uuid,
uuid: '/clients/'+client.uuid,
status: client.status,
partitions: client.partitions,
ip: client.ip
}));
this.router.navigate(['/clients/run-script'], {
queryParams: {
clientData: JSON.stringify(clientDataToSend),
runScriptContext: JSON.stringify(this.runScriptContext)
}
})
queryParams: { clientData: JSON.stringify(clientDataToSend) }
}).then(() => {
console.log('Navigated to run script with data:', clientDataToSend);
});
}
}

View File

@ -1,117 +0,0 @@
.dialog-content {
display: flex;
flex-direction: column;
padding: 40px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.select-container {
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.button-row {
display: flex;
padding-right: 1em;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.client-item {
position: relative;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.loading-spinner {
display: block;
margin: 0 auto;
align-items: center;
justify-content: center;
}
.client-details {
margin-top: 4px;
}
.client-name {
font-size: 0.9em;
font-weight: 600;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
display: block;
font-size: 0.9em;
color: #666;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
@media (max-width: 600px) {
.form-field {
width: 100%;
}
.dialog-actions {
flex-direction: column;
align-items: stretch;
}
button {
width: 100%;
margin-left: 0;
margin-bottom: 8px;
}
}

View File

@ -1,105 +0,0 @@
<h2 mat-dialog-title> Seleccionar imagen para eliminar de la cache</h2>
<mat-dialog-content class="dialog-content">
<mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<div *ngIf="!loading" class="select-container">
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title> Clientes </mat-panel-title>
<mat-panel-description>
Listado de clientes para arrancar un SO
<mat-icon>desktop_windows</mat-icon>
</mat-panel-description>
</mat-expansion-panel-header>
<div class="button-row">
<button class="action-button" (click)="toggleSelectAll()">
{{ allSelected ? 'Desmarcar todos' : 'Marcar todos' }}
</button>
</div>
<div class="clients-grid">
<div *ngFor="let client of data.clients" class="client-item">
<div class="client-card"
(click)="client.status === 'og-live' && toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected, 'disabled-client': client.status !== 'og-live'}" >
<img
[src]="'assets/images/computer_' + client.status + '.svg'"
alt="Client Icon"
class="client-image" />
<div class="client-details">
<span class="client-name">{{ client.name | slice:0:20 }}</span>
<span class="client-ip">{{ client.ip }}</span>
<span class="client-ip">{{ client.mac }}</span>
</div>
<mat-divider></mat-divider>
<mat-radio-group [(ngModel)]="selectedModelClient" (change)="loadPartitions(selectedModelClient)">
<mat-radio-button [value]="client"
color="primary"
[disabled]="!client.selected"
(click)="$event.stopPropagation()">
Modelo
</mat-radio-button>
</mat-radio-group>
</div>
</div>
</div>
</mat-expansion-panel>
</div>
<mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider>
<div *ngIf="!loading" class="partition-table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">Seleccionar imagen</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group
[(ngModel)]="selectedPartition"
[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 }} </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>
</mat-dialog-content>
<div mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">Cancelar</button>
<button class="submit-button" (click)="execute()" [disabled]="!selectedPartition">Ejecutar</button>
</div>

View File

@ -1,92 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RemoveCacheImageComponent } from './remove-cache-image.component';
import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from "@angular/material/dialog";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatCheckboxModule } from "@angular/material/checkbox";
import { MatButtonModule } from "@angular/material/button";
import { MatMenuModule } from "@angular/material/menu";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { MatTableModule } from "@angular/material/table";
import { MatSelectModule } from "@angular/material/select";
import { MatIconModule } from "@angular/material/icon";
import { ToastrModule, ToastrService } from "ngx-toastr";
import { TranslateModule } from "@ngx-translate/core";
import { DataService } from "../../data.service";
import { provideHttpClient } from "@angular/common/http";
import { provideHttpClientTesting } from "@angular/common/http/testing";
import { ConfigService } from "@services/config.service";
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDividerModule } from '@angular/material/divider';
import { MatRadioModule } from '@angular/material/radio';
describe('RemoveCacheImageComponent', () => {
let component: RemoveCacheImageComponent;
let fixture: ComponentFixture<RemoveCacheImageComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [RemoveCacheImageComponent],
imports: [
ReactiveFormsModule,
FormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
MatCheckboxModule,
MatButtonModule,
MatMenuModule,
MatExpansionModule,
BrowserAnimationsModule,
MatTableModule,
MatDividerModule,
MatSelectModule,
MatRadioModule,
MatIconModule,
ToastrModule.forRoot(),
TranslateModule.forRoot()
],
providers: [
FormBuilder,
ToastrService,
DataService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {
clients: [
{
'@id': '/clients/1',
uuid: 'client-uuid-1',
selected: false,
status: 'og-live',
state: 'og-live'
}
]
}
},
{ provide: ConfigService, useValue: mockConfigService }
]
})
.compileComponents();
fixture = TestBed.createComponent(RemoveCacheImageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,154 +0,0 @@
import {Component, Inject} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {ConfigService} from "@services/config.service";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
@Component({
selector: 'app-remove-cache-image',
templateUrl: './remove-cache-image.component.html',
styleUrl: './remove-cache-image.component.css'
})
export class RemoveCacheImageComponent {
baseUrl: string;
selectedPartition: any = null;
dataSource = new MatTableDataSource<any>();
clientId: string | null = null;
selectedClients: any[] = [];
selectedModelClient: any = null;
filteredPartitions: any[] = [];
allSelected: boolean = false;
clientData: any[] = [];
loading: boolean = false;
columns = [
{
columnDef: 'diskNumber',
header: 'Disco',
cell: (partition: any) => partition.diskNumber
},
{
columnDef: 'partitionNumber',
header: 'Particion',
cell: (partition: any) => partition.partitionNumber
},
{
columnDef: 'size',
header: 'Tamaño',
cell: (partition: any) => `${partition.size} MB`
},
{
columnDef: 'partitionCode',
header: 'Tipo de partición',
cell: (partition: any) => partition.partitionCode
},
{
columnDef: 'filesystem',
header: 'Sistema de ficheros',
cell: (partition: any) => partition.filesystem
},
{
columnDef: 'operativeSystem',
header: 'SO',
cell: (partition: any) => partition.operativeSystem?.name
}
];
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
constructor(
@Inject(MAT_DIALOG_DATA) public data: { clients: any },
private dialogRef: MatDialogRef<RemoveCacheImageComponent>,
private configService: ConfigService,
private http: HttpClient,
private toastService: ToastrService,
) {
this.baseUrl = this.configService.apiUrl;
this.clientId = this.data.clients?.length ? this.data.clients[0]['@id'] : null;
this.data.clients.forEach((client: { selected: boolean; status: string }) => {
if (client.status === 'og-live') {
client.selected = true;
}
});
this.selectedClients = this.data.clients.filter(
(client: { status: string }) => client.status === 'og-live'
);
this.selectedModelClient = this.data.clients.find(
(client: { status: string }) => client.status === 'og-live'
) || null;
if (this.selectedModelClient) {
this.loadPartitions(this.selectedModelClient);
}
}
ngOnInit() {
}
loadPartitions(client: any) {
const url = `${this.baseUrl}${client.uuid}`;
this.http.get(url).subscribe(
(response: any) => {
if (response.partitions) {
this.dataSource.data = response.partitions.filter((partition: any) => {
return partition.partitionNumber !== 0 && partition.image;
});
}
},
(error) => {
console.error('Error al cargar los datos del cliente:', error);
}
);
}
toggleClientSelection(client: any) {
client.selected = !client.selected;
this.updateSelectedClients();
}
updateSelectedClients() {
this.selectedClients = this.data.clients.filter(
(client: { selected: boolean; state: string }) => client.selected && client.state === "og-live"
);
if (!this.selectedClients.includes(this.selectedModelClient)) {
this.selectedModelClient = null;
this.filteredPartitions = [];
}
}
toggleSelectAll() {
this.allSelected = !this.allSelected;
this.data.clients.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected;
}
});
}
close() {
this.dialogRef.close();
}
execute(): void {
this.loading = true;
this.http.post(`${this.baseUrl}/clients/server/remove-cache-image`, {
clients: this.selectedClients.map((client: any) => client.uuid),
partition: this.selectedPartition['@id']
}).subscribe(
response => {
this.toastService.success('Cliente actualizado correctamente');
this.dialogRef.close();
this.loading = false;
},
error => {
this.toastService.error(error.error['hydra:description']);
this.loading = false;
}
);
}
}

View File

@ -1,117 +0,0 @@
.dialog-content {
display: flex;
flex-direction: column;
padding: 40px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
.select-container {
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.button-row {
display: flex;
padding-right: 1em;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.client-item {
position: relative;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.loading-spinner {
display: block;
margin: 0 auto;
align-items: center;
justify-content: center;
}
.client-details {
margin-top: 4px;
}
.client-name {
font-size: 0.9em;
font-weight: 600;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
display: block;
font-size: 0.9em;
color: #666;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
@media (max-width: 600px) {
.form-field {
width: 100%;
}
.dialog-actions {
flex-direction: column;
align-items: stretch;
}
button {
width: 100%;
margin-left: 0;
margin-bottom: 8px;
}
}

View File

@ -1,55 +0,0 @@
<h2 mat-dialog-title> Seleccionar partición para inventariar</h2>
<mat-dialog-content class="dialog-content">
<mat-spinner class="loading-spinner" *ngIf="loading"></mat-spinner>
<mat-divider *ngIf="!loading" style="margin-top: 20px;"></mat-divider>
<div *ngIf="!loading" class="partition-table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">Seleccionar imagen</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group
[(ngModel)]="selectedPartition"
>
<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 }} </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>
</mat-dialog-content>
<div mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">Cancelar</button>
<button class="submit-button" (click)="execute()" [disabled]="!selectedPartition">Ejecutar</button>
</div>

View File

@ -1,71 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SoftwareProfilePartitionComponent } from './software-profile-partition.component';
import {FormBuilder, ReactiveFormsModule} from "@angular/forms";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from "@angular/material/dialog";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatInputModule} from "@angular/material/input";
import {MatCheckboxModule} from "@angular/material/checkbox";
import {MatButtonModule} from "@angular/material/button";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {ToastrModule, ToastrService} from "ngx-toastr";
import {TranslateModule} from "@ngx-translate/core";
import {DataService} from "../../data.service";
import {provideHttpClient} from "@angular/common/http";
import {provideHttpClientTesting} from "@angular/common/http/testing";
import {ConfigService} from "@services/config.service";
import {MatDividerModule} from "@angular/material/divider";
import {MatTableModule} from "@angular/material/table";
describe('SoftwareProfilePartitionComponent', () => {
let component: SoftwareProfilePartitionComponent;
let fixture: ComponentFixture<SoftwareProfilePartitionComponent>;
beforeEach(async () => {
const mockConfigService = {
apiUrl: 'http://mock-api-url',
mercureUrl: 'http://mock-mercure-url'
};
await TestBed.configureTestingModule({
declarations: [SoftwareProfilePartitionComponent],
imports: [
ReactiveFormsModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
MatCheckboxModule,
MatButtonModule,
BrowserAnimationsModule,
MatDividerModule,
MatTableModule,
ToastrModule.forRoot(),
TranslateModule.forRoot()
],
providers: [
FormBuilder,
ToastrService,
DataService,
provideHttpClient(),
provideHttpClientTesting(),
{
provide: MatDialogRef,
useValue: {}
},
{
provide: MAT_DIALOG_DATA,
useValue: {}
},
{ provide: ConfigService, useValue: mockConfigService }
]
})
.compileComponents();
fixture = TestBed.createComponent(SoftwareProfilePartitionComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -1,107 +0,0 @@
import {Component, Inject, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {ConfigService} from "@services/config.service";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
@Component({
selector: 'app-software-profile-partition',
templateUrl: './software-profile-partition.component.html',
styleUrl: './software-profile-partition.component.css'
})
export class SoftwareProfilePartitionComponent implements OnInit{
baseUrl: string;
selectedPartition: any = null;
dataSource = new MatTableDataSource<any>();
clientId: string | null = null;
selectedClients: any[] = [];
selectedModelClient: any = null;
filteredPartitions: any[] = [];
allSelected: boolean = false;
clientData: any[] = [];
loading: boolean = false;
columns = [
{
columnDef: 'diskNumber',
header: 'Disco',
cell: (partition: any) => partition.diskNumber
},
{
columnDef: 'partitionNumber',
header: 'Particion',
cell: (partition: any) => partition.partitionNumber
},
{
columnDef: 'size',
header: 'Tamaño',
cell: (partition: any) => `${partition.size} MB`
},
{
columnDef: 'partitionCode',
header: 'Tipo de partición',
cell: (partition: any) => partition.partitionCode
},
{
columnDef: 'filesystem',
header: 'Sistema de ficheros',
cell: (partition: any) => partition.filesystem
},
{
columnDef: 'operativeSystem',
header: 'SO',
cell: (partition: any) => partition.operativeSystem?.name
}
];
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
constructor(
@Inject(MAT_DIALOG_DATA) public data: { client: any },
private dialogRef: MatDialogRef<SoftwareProfilePartitionComponent>,
private configService: ConfigService,
private http: HttpClient,
private toastService: ToastrService,
) {
this.baseUrl = this.configService.apiUrl;
this.clientId = this.data.client?.clientId
}
ngOnInit() {
this.loadPartitions();
}
loadPartitions() {
const url = `${this.baseUrl}/clients/${this.data.client?.clientId}`;
this.http.get(url).subscribe(
(response: any) => {
if (response.partitions) {
this.dataSource.data = response.partitions;
}
},
(error) => {
console.error('Error al cargar los datos del cliente:', error);
}
);
}
close() {
this.dialogRef.close();
}
execute(): void {
this.loading = true;
this.http.post(`${this.baseUrl}/clients/server/${this.data.client.clientId}/software-inventory`, {
partition: this.selectedPartition['@id'],
}).subscribe(
response => {
this.toastService.success('Inventario de software actualizado correctamente');
this.dialogRef.close(response);
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error al actualizar el inventario de software');
}
);
}
}

View File

@ -0,0 +1 @@
<p>dashboard works!</p>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DashboardComponent } from './dashboard.component';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [DashboardComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the component', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.css'
})
export class DashboardComponent {
}

View File

@ -1,557 +1,44 @@
/* ===== HEADER DE BIENVENIDA ===== */
.welcome-header {
background: #3f51b5;
color: white;
padding: 2rem 2rem 1.5rem 2rem;
display: flex;
justify-content: space-between;
align-items: flex-start;
position: relative;
overflow: hidden;
}
.welcome-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="10" cy="60" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="40" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
opacity: 0.2;
}
.welcome-content {
display: flex;
align-items: center;
gap: 1.5rem;
position: relative;
z-index: 1;
}
.welcome-icon {
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
width: 60px;
height: 60px;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.3);
}
.welcome-icon mat-icon {
font-size: 32px;
width: 32px;
height: 32px;
color: white;
}
.welcome-text {
flex: 1;
}
.welcome-title {
margin: 0 0 0.5rem 0;
font-size: 2rem;
font-weight: 700;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.welcome-subtitle {
margin: 0 0 0.25rem 0;
font-size: 1.1rem;
font-weight: 500;
opacity: 0.95;
}
.welcome-description {
margin: 0;
font-size: 0.9rem;
opacity: 0.8;
}
.welcome-actions {
display: flex;
gap: 0.5rem;
position: relative;
z-index: 1;
}
.help-button,
.refresh-button {
background: rgba(255, 255, 255, 0.2) !important;
color: white !important;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.3);
transition: all 0.3s ease;
}
.help-button:hover,
.refresh-button:hover {
background: rgba(255, 255, 255, 0.3) !important;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
/* ===== CONTENIDO PRINCIPAL ===== */
mat-dialog-content {
height: calc(100% - 200px);
overflow: auto;
padding: 0 !important;
background: #f8f9fa;
height: calc(100% - 64px);
overflow: auto;
padding-top: 0.5em !important;
}
.main-content {
padding: 2rem;
.content-container {
min-height: 100%;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
/* ===== SPINNER DE CARGA ===== */
.spinner-container {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
background: rgba(255, 255, 255, 0.95);
border-radius: 16px;
padding: 2rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(10px);
}
.loading-content {
text-align: center;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
}
.loading-spinner {
width: 60px !important;
height: 60px !important;
margin-bottom: 1rem;
}
.loading-text {
margin: 0;
color: #666;
font-weight: 500;
}
/* ===== RESUMEN DEL SISTEMA ===== */
.system-overview {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
.overview-card {
background: white;
border-radius: 16px;
padding: 1.5rem;
display: flex;
align-items: center;
gap: 1rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
transition: all 0.3s ease;
border: 1px solid rgba(0, 0, 0, 0.05);
position: relative;
overflow: hidden;
}
.overview-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #667eea, #764ba2);
opacity: 0;
transition: opacity 0.3s ease;
}
.overview-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.overview-card:hover::before {
opacity: 1;
}
.overview-icon {
background: linear-gradient(135deg, #667eea, #764ba2);
border-radius: 50%;
width: 50px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.overview-icon mat-icon {
color: white;
font-size: 24px;
width: 24px;
height: 24px;
}
.overview-content h3 {
margin: 0 0 0.5rem 0;
font-size: 1.1rem;
font-weight: 600;
color: #2c3e50;
}
.overview-content p {
margin: 0;
font-size: 0.9rem;
color: #6c757d;
}
/* ===== BADGES DE ESTADO ===== */
.status-badge {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-badge.online {
background: linear-gradient(135deg, #28a745, #20c997);
color: white;
}
.status-badge.offline {
background: linear-gradient(135deg, #dc3545, #c82333);
color: white;
}
.status-badge.info {
background: linear-gradient(135deg, #17a2b8, #138496);
color: white;
}
/* ===== TABS PRINCIPALES ===== */
.main-tabs {
background: white;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
overflow: hidden;
}
::ng-deep .main-tabs .mat-tab-header {
background: #f8f9fa;
border-bottom: 1px solid #e9ecef;
}
::ng-deep .main-tabs .mat-tab-label {
font-weight: 600;
color: #6c757d;
transition: all 0.3s ease;
}
::ng-deep .main-tabs .mat-tab-label-active {
color: #667eea;
}
::ng-deep .main-tabs .mat-ink-bar {
background: linear-gradient(90deg, #667eea, #764ba2);
height: 3px;
}
.tab-content {
padding: 2rem;
}
/* ===== CONTENEDOR DE ERRORES ===== */
.error-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 300px;
padding: 2rem;
width: 100px;
height: 100px;
}
.error-card {
background: white;
border-radius: 16px;
padding: 3rem 2rem;
text-align: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid #e9ecef;
max-width: 400px;
}
.error-icon {
font-size: 64px;
width: 64px;
height: 64px;
color: #dc3545;
margin-bottom: 1rem;
}
.error-card h3 {
margin: 0 0 1rem 0;
color: #2c3e50;
font-weight: 600;
margin: 20px auto;
max-width: 600px;
text-align: center;
background-color: rgb(243, 243, 243);
color: rgb(48, 48, 48);
}
.error-card p {
margin: 0 0 2rem 0;
color: #6c757d;
line-height: 1.5;
}
/* ===== REPOSITORIOS ===== */
.repositories-container {
padding: 1rem;
}
.repositories-selector-container {
display: flex;
flex-direction: column;
gap: 2rem;
}
.repository-selector {
display: flex;
justify-content: center;
padding: 1rem 0;
}
.repository-content {
padding: 1rem;
}
.repository-select-field {
min-width: 300px;
max-width: 500px;
width: 100%;
}
.selected-repository-content {
animation: fadeInUp 0.6s ease-out;
}
.no-repository-selected {
text-align: center;
padding: 3rem 2rem;
color: #6c757d;
}
.no-repository-selected .no-data-icon {
font-size: 4rem;
width: 4rem;
height: 4rem;
margin-bottom: 1rem;
opacity: 0.5;
}
.no-repository-selected h3 {
margin: 0 0 1rem 0;
color: #2c3e50;
font-weight: 600;
}
.no-repository-selected p {
margin: 0;
font-size: 1rem;
line-height: 1.5;
}
/* ===== FOOTER CON ACCIONES ===== */
.action-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.5rem 2rem;
background: white;
border-top: 1px solid #e9ecef;
border-radius: 0 0 12px 12px;
}
.action-info {
flex: 1;
}
.last-update {
margin: 0;
font-size: 0.85rem;
color: #6c757d;
}
.action-buttons {
display: flex;
gap: 1rem;
}
.secondary-button {
color: #6c757d !important;
border: 1px solid #dee2e6 !important;
transition: all 0.3s ease;
}
.secondary-button:hover {
background: #f8f9fa !important;
border-color: #667eea !important;
color: #667eea !important;
}
/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
.welcome-header {
padding: 1.5rem 1rem 1rem 1rem;
flex-direction: column;
gap: 1rem;
text-align: center;
}
.welcome-content {
flex-direction: column;
gap: 1rem;
}
.welcome-title {
font-size: 1.5rem;
}
.welcome-subtitle {
font-size: 1rem;
}
.main-content {
padding: 1rem;
}
.system-overview {
grid-template-columns: 1fr;
gap: 1rem;
}
.overview-card {
padding: 1rem;
}
.action-container {
flex-direction: column;
gap: 1rem;
text-align: center;
}
.action-buttons {
width: 100%;
justify-content: center;
}
}
@media (max-width: 480px) {
.welcome-header {
padding: 1rem;
}
.welcome-icon {
width: 50px;
height: 50px;
}
.welcome-icon mat-icon {
font-size: 28px;
width: 28px;
height: 28px;
}
.welcome-title {
font-size: 1.25rem;
}
.overview-card {
flex-direction: column;
text-align: center;
}
.tab-content {
padding: 1rem;
}
.repository-select-field {
min-width: 250px;
max-width: 100%;
}
}
/* ===== ANIMACIONES ===== */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.system-overview,
.main-tabs {
animation: fadeInUp 0.6s ease-out;
}
.overview-card {
animation: fadeInUp 0.6s ease-out;
}
.overview-card:nth-child(1) { animation-delay: 0.1s; }
.overview-card:nth-child(2) { animation-delay: 0.2s; }
.overview-card:nth-child(3) { animation-delay: 0.3s; }
/* ===== ESTILOS GLOBALES DEL DIALOG ===== */
::ng-deep .mat-dialog-container {
border-radius: 16px !important;
overflow: hidden !important;
padding: 0 !important;
}
::ng-deep .mat-dialog-content {
margin: 0 !important;
padding: 0 !important;
}
/* ===== LOADING INDIVIDUAL POR TAB ===== */
.loading-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 300px;
padding: 2rem;
}
.loading-container .loading-content {
text-align: center;
background: rgba(255, 255, 255, 0.95);
border-radius: 16px;
padding: 2rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(10px);
}
.loading-container .loading-spinner {
width: 60px !important;
height: 60px !important;
margin-bottom: 1rem;
}
.loading-container .loading-text {
margin: 0;
color: #666;
font-weight: 500;
margin-top: 0;
}

View File

@ -1,209 +1,94 @@
<!-- Header con bienvenida -->
<div class="welcome-header">
<div class="welcome-content">
<div class="welcome-icon">
<mat-icon>dashboard</mat-icon>
</div>
<div class="welcome-text">
<h1 class="welcome-title">{{ 'GlobalStatus' | translate }}</h1>
<p class="welcome-subtitle">Bienvenido a la consola de administración de OpenGnsys</p>
<p class="welcome-description">Estado general de todos los componentes de la plataforma</p>
</div>
</div>
<div class="welcome-actions">
<button mat-icon-button class="refresh-button" (click)="refreshAll()" matTooltip="Actualizar datos">
<mat-icon>refresh</mat-icon>
</button>
</div>
</div>
<!-- Contenido principal -->
<header>
<h1 mat-dialog-title>{{'GlobalStatus' | translate}}</h1>
</header>
<mat-dialog-content [ngClass]="{'loading': loading}">
<!-- Spinner de carga -->
<div class="spinner-container" *ngIf="loading">
<div class="loading-content">
<mat-spinner class="loading-spinner"></mat-spinner>
<p class="loading-text">Cargando estado del sistema...</p>
</div>
<mat-spinner class="loading-spinner"></mat-spinner>
</div>
<!-- Contenido principal cuando no está cargando -->
<div *ngIf="!loading" class="main-content">
<!-- Resumen rápido del sistema -->
<div class="system-overview">
<div class="overview-card">
<div class="overview-icon">
<mat-icon>cloud</mat-icon>
</div>
<div class="overview-content">
<h3>Repositorios</h3>
<p>Total: <span class="status-badge info">{{ repositories.length }}</span></p>
</div>
<mat-tab-group (selectedTabChange)="onTabChange($event)">
<mat-tab label="OgBoot">
<div *ngIf="!loading && !errorOgBoot" class="content-container">
<app-status-tab
[loading]="loading"
[diskUsage]="ogBootDiskUsage"
[servicesStatus]="ogBootServicesStatus"
[installedOgLives]="installedOgLives"
[diskUsageChartData]="ogBootDiskUsageChartData"
[view]="view"
[colorScheme]="colorScheme"
[isDoughnut]="isDoughnut"
[showLabels]="showLabels"
[isDhcp]="isDhcp"
[isRepository]="false">
</app-status-tab>
</div>
<div class="overview-card">
<div class="overview-icon">
<mat-icon>storage</mat-icon>
</div>
<div class="overview-content">
<h3>OgBoot Server</h3>
<p *ngIf="!errorOgBoot">Estado: <span class="status-badge online">Operativo</span></p>
<p *ngIf="errorOgBoot">Estado: <span class="status-badge offline">Error</span></p>
</div>
<mat-card *ngIf="!loading && errorOgBoot" class="error-card">
<mat-card-content>
<p>{{ 'errorLoadingData' | translate }}</p>
</mat-card-content>
</mat-card>
</mat-tab>
<mat-tab label="Dhcp">
<div *ngIf="!loading && !errorDhcp" class="content-container">
<app-status-tab
[loading]="loading"
[diskUsage]="dhcpDiskUsage"
[servicesStatus]="dhcpServicesStatus"
[subnets]="subnets"
[diskUsageChartData]="dhcpDiskUsageChartData"
[view]="view"
[colorScheme]="colorScheme"
[isDoughnut]="isDoughnut"
[showLabels]="showLabels"
[isDhcp]="isDhcp"
[isRepository]="false">
</app-status-tab>
</div>
<div class="overview-card">
<div class="overview-icon">
<mat-icon>router</mat-icon>
</div>
<div class="overview-content">
<h3>DHCP Server</h3>
<p *ngIf="!errorDhcp">Estado: <span class="status-badge online">Operativo</span></p>
<p *ngIf="errorDhcp">Estado: <span class="status-badge offline">Error</span></p>
</div>
</div>
</div>
<mat-card *ngIf="!loading && errorDhcp" class="error-card">
<mat-card-content>
<p>{{ 'errorLoadingData' | translate }}</p>
</mat-card-content>
</mat-card>
</mat-tab>
<!-- Tabs principales -->
<mat-tab-group (selectedTabChange)="onTabChange($event)" class="main-tabs">
<mat-tab label="{{ 'repositoryLabel' | translate }}">
<div class="repositories-container">
<div *ngIf="repositories.length === 0" class="no-repositories">
<mat-icon class="no-data-icon">cloud_off</mat-icon>
<h3>No hay repositorios disponibles</h3>
<p>No se encontraron repositorios configurados en el sistema.</p>
<mat-tab label="Repositorios">
<mat-tab-group>
<mat-tab *ngFor="let repository of repositories" [label]="repository.name">
<div *ngIf="!loading && !errorRepositories[repository.uuid] && repositoryStatuses[repository.uuid]">
<app-status-tab
[loading]="loading"
[diskUsage]="repositoryStatuses[repository.uuid].disk"
[servicesStatus]="repositoryStatuses[repository.uuid].services"
[processesStatus]="repositoryStatuses[repository.uuid].processes"
[ramUsage]="repositoryStatuses[repository.uuid].ram"
[cpuUsage]="repositoryStatuses[repository.uuid].cpu"
[diskUsageChartData]="[
{ name: 'Usado', value: repositoryStatuses[repository.uuid].disk.used },
{ name: 'Disponible', value: repositoryStatuses[repository.uuid].disk.available }
]"
[ramUsageChartData]="[
{ name: 'Usado', value: repositoryStatuses[repository.uuid].ram.used },
{ name: 'Disponible', value: repositoryStatuses[repository.uuid].ram.available }
]"
[view]="view"
[colorScheme]="colorScheme"
[isDoughnut]="isDoughnut"
[showLabels]="showLabels"
[isDhcp]="false"
[isRepository]="true">
</app-status-tab>
</div>
<div *ngIf="repositories.length > 0" class="repositories-selector-container">
<!-- Selector de repositorio -->
<div class="repository-selector">
<mat-form-field appearance="outline" class="repository-select-field">
<mat-label>Seleccionar repositorio</mat-label>
<mat-select [(ngModel)]="selectedRepositoryUuid" (selectionChange)="onRepositoryChange($event.value)">
<mat-option *ngFor="let repository of repositories" [value]="repository.uuid">
{{ repository.name }}
</mat-option>
</mat-select>
<mat-icon matSuffix>storage</mat-icon>
</mat-form-field>
</div>
<!-- Información del repositorio seleccionado -->
<div *ngIf="selectedRepositoryUuid && !errorRepositories[selectedRepositoryUuid] && repositoryStatuses[selectedRepositoryUuid]" class="selected-repository-content">
<div class="repository-item">
<div class="repository-header">
<h3>{{ getSelectedRepositoryName() }}</h3>
</div>
<div class="repository-content">
<app-status-tab [loading]="loading" [diskUsage]="repositoryStatuses[selectedRepositoryUuid].disk"
[servicesStatus]="repositoryStatuses[selectedRepositoryUuid].services"
[processesStatus]="repositoryStatuses[selectedRepositoryUuid].processes"
[ramUsage]="repositoryStatuses[selectedRepositoryUuid].ram" [cpuUsage]="repositoryStatuses[selectedRepositoryUuid].cpu"
[diskUsageChartData]="[
{ name: 'Usado', value: repositoryStatuses[selectedRepositoryUuid].disk.used },
{ name: 'Disponible', value: repositoryStatuses[selectedRepositoryUuid].disk.available }
]" [ramUsageChartData]="[
{ name: 'Usado', value: repositoryStatuses[selectedRepositoryUuid].ram.used },
{ name: 'Disponible', value: repositoryStatuses[selectedRepositoryUuid].ram.available }
]" [view]="view" [colorScheme]="colorScheme" [isDoughnut]="isDoughnut" [showLabels]="showLabels"
[isDhcp]="false" [isRepository]="true">
</app-status-tab>
</div>
</div>
</div>
<!-- Mensaje cuando no hay repositorio seleccionado -->
<div *ngIf="!selectedRepositoryUuid" class="no-repository-selected">
<mat-icon class="no-data-icon">storage</mat-icon>
<h3>Selecciona un repositorio</h3>
<p>Elige un repositorio de la lista para ver su estado detallado.</p>
</div>
<!-- Error al cargar repositorio -->
<div *ngIf="selectedRepositoryUuid && errorRepositories[selectedRepositoryUuid]" class="error-container">
<div class="error-card">
<mat-icon class="error-icon">error_outline</mat-icon>
<h3>Error de conexión</h3>
<p>No se pudo conectar con el repositorio seleccionado</p>
<button mat-raised-button color="primary" (click)="retryRepositoryStatus(selectedRepositoryUuid)">
<mat-icon>refresh</mat-icon>
Reintentar
</button>
</div>
</div>
</div>
</div>
</mat-tab>
<mat-tab label="OgBoot Server">
<div *ngIf="!errorOgBoot && !loadingOgBoot" class="tab-content">
<app-status-tab [loading]="loadingOgBoot" [diskUsage]="ogBootDiskUsage" [servicesStatus]="ogBootServicesStatus"
[installedOgLives]="installedOgLives" [diskUsageChartData]="ogBootDiskUsageChartData" [view]="view"
[colorScheme]="colorScheme" [isDoughnut]="isDoughnut" [showLabels]="showLabels" [isDhcp]="isDhcp"
[isRepository]="false">
</app-status-tab>
</div>
<div *ngIf="loadingOgBoot" class="loading-container">
<div class="loading-content">
<mat-spinner class="loading-spinner"></mat-spinner>
<p class="loading-text">Cargando estado de OgBoot...</p>
</div>
</div>
<div *ngIf="errorOgBoot" class="error-container">
<div class="error-card">
<mat-icon class="error-icon">error_outline</mat-icon>
<h3>Error de conexión</h3>
<p>No se pudo conectar con el servidor OgBoot</p>
<button mat-raised-button color="primary" (click)="loadOgBootStatus()">
<mat-icon>refresh</mat-icon>
Reintentar
</button>
</div>
</div>
</mat-tab>
<mat-tab label="DHCP Server">
<div *ngIf="!errorDhcp && !loadingDhcp" class="tab-content">
<app-status-tab [loading]="loadingDhcp" [diskUsage]="dhcpDiskUsage" [servicesStatus]="dhcpServicesStatus"
[subnets]="subnets" [diskUsageChartData]="dhcpDiskUsageChartData" [view]="view" [colorScheme]="colorScheme"
[isDoughnut]="isDoughnut" [showLabels]="showLabels" [isDhcp]="true" [isRepository]="false">
</app-status-tab>
</div>
<div *ngIf="loadingDhcp" class="loading-container">
<div class="loading-content">
<mat-spinner class="loading-spinner"></mat-spinner>
<p class="loading-text">Cargando estado de DHCP...</p>
</div>
</div>
<div *ngIf="errorDhcp" class="error-container">
<div class="error-card">
<mat-icon class="error-icon">error_outline</mat-icon>
<h3>Error de conexión</h3>
<p>No se pudo conectar con el servidor DHCP</p>
<button mat-raised-button color="primary" (click)="loadDhcpStatus()">
<mat-icon>refresh</mat-icon>
Reintentar
</button>
</div>
</div>
</mat-tab>
</mat-tab-group>
</div>
<mat-card *ngIf="!loading && errorRepositories[repository.uuid]" class="error-card">
<mat-card-content>
<p>{{ 'errorLoadingData' | translate }}</p>
</mat-card-content>
</mat-card>
</mat-tab>
</mat-tab-group>
</mat-tab>
</mat-tab-group>
</mat-dialog-content>
<!-- Footer con acciones -->
<mat-dialog-actions class="action-container">
<div class="action-info">
<p class="last-update">Última actualización: {{ lastUpdateTime }}</p>
</div>
<div class="action-buttons">
<button mat-button class="secondary-button" (click)="refreshAll()">
<mat-icon>refresh</mat-icon>
Actualizar
</button>
<button mat-raised-button color="primary" [mat-dialog-close]="true">
{{ 'closeButton' | translate }}
</button>
</div>
<button class="ordinary-button" [mat-dialog-close]="true">{{ 'closeButton' | translate }}</button>
</mat-dialog-actions>

View File

@ -2,7 +2,6 @@ import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ConfigService } from '@services/config.service';
import { MatTabChangeEvent } from '@angular/material/tabs';
import {ToastrService} from "ngx-toastr";
@Component({
selector: 'app-global-status',
@ -12,9 +11,6 @@ import {ToastrService} from "ngx-toastr";
export class GlobalStatusComponent implements OnInit {
baseUrl: string;
loading: boolean = false;
loadingOgBoot: boolean = false;
loadingDhcp: boolean = false;
loadingRepositories: boolean = false;
errorOgBoot: boolean = false;
errorDhcp: boolean = false;
errorRepositories: { [key: string]: boolean } = {};
@ -29,8 +25,6 @@ export class GlobalStatusComponent implements OnInit {
repositoriesUrl: string;
repositories: any[] = [];
repositoryStatuses: { [key: string]: any } = {};
lastUpdateTime: string = '';
selectedRepositoryUuid: string = '';
ogBootApiUrl: string;
ogBootDiskUsage: any = {};
@ -44,109 +38,27 @@ export class GlobalStatusComponent implements OnInit {
isDhcp: boolean = false;
isRepository: boolean = false;
// Loading específicos para cada sección
loadingOgBootOgLives: boolean = false;
loadingOgBootServices: boolean = false;
loadingOgBootDisk: boolean = false;
loadingDhcpSubnets: boolean = false;
loadingDhcpServices: boolean = false;
loadingDhcpDisk: boolean = false;
constructor(
private configService: ConfigService,
private toastService: ToastrService,
private http: HttpClient
) {
this.baseUrl = this.configService.apiUrl;
this.ogBootApiUrl = `${this.baseUrl}/og-boot/status`;
this.dhcpApiUrl = `${this.baseUrl}/og-dhcp/status`;
this.repositoriesUrl = `${this.baseUrl}/image-repositories`;
this.ogBootDiskUsageChartData = [];
this.dhcpDiskUsageChartData = [];
}
ngOnInit(): void {
this.updateLastUpdateTime();
this.loadOgBootStatus();
this.loadDhcpStatus();
this.loadRepositories(false);
this.syncSubnets();
this.syncTemplates();
this.syncOgLives();
}
syncSubnets() {
const timeoutId = setTimeout(() => {
this.toastService.error('Error al sincronizar las subredes: tiempo de espera agotado');
}, 3500);
this.http.post(`${this.baseUrl}/subnets/sync`, {}).subscribe({
next: (response) => {
clearTimeout(timeoutId);
this.toastService.success('Sincronización con componente DHCP exitosa');
},
error: (error) => {
clearTimeout(timeoutId);
this.toastService.error(error.error['hydra:description'] || 'Error al sincronizar las subredes');
}
});
}
syncTemplates() {
const timeoutId = setTimeout(() => {
this.toastService.error('Error al sincronizar las plantillas Pxe: tiempo de espera agotado');
}, 3500);
this.http.post(`${this.baseUrl}/pxe-templates/sync`, {})
.subscribe(response => {
clearTimeout(timeoutId);
this.toastService.success('Sincronización de las plantillas Pxe completada');
}, error => {
clearTimeout(timeoutId);
this.toastService.error(error.error['hydra:description'] || 'Error al sincronizar las plantillas Pxe');
});
}
syncOgLives(): void {
const timeoutId = setTimeout(() => {
this.toastService.error('Error al sincronizar las imagenes ogLive : tiempo de espera agotado');
}, 3500);
this.http.post(`${this.baseUrl}/og-lives/sync`, {})
.subscribe(response => {
clearTimeout(timeoutId);
this.toastService.success('Sincronización con los ogLives completada');
}, error => {
clearTimeout(timeoutId);
this.toastService.error(error.error['hydra:description'] || 'Error al sincronizar las imagenes ogLive');
});
}
[key: string]: any;
loadStatus(apiUrl: string, diskUsage: any, servicesStatus: any, diskUsageChartData: any[], installedOgLives: any[], isDhcp: boolean, errorState: string, showLoading: boolean = true): void {
if (isDhcp) {
this.loadingDhcp = true;
} else {
this.loadingOgBoot = true;
}
if (showLoading) {
this.loading = true;
}
loadStatus(apiUrl: string, diskUsage: any, servicesStatus: any, diskUsageChartData: any[], installedOgLives: any[], isDhcp: boolean, errorState: string): void {
this.loading = true;
this[errorState] = false;
const timeoutId = setTimeout(() => {
if (showLoading) {
this.loading = false;
}
if (isDhcp) {
this.loadingDhcp = false;
} else {
this.loadingOgBoot = false;
}
this.loading = false;
this[errorState] = true;
}, 3500);
this.http.get<any>(apiUrl).subscribe({
@ -168,7 +80,6 @@ export class GlobalStatusComponent implements OnInit {
if (data.message.installed_oglives) {
installedOgLives.push(...data.message.installed_oglives);
}
this.loadingOgBootOgLives = false;
}
diskUsageChartData.length = 0;
@ -177,41 +88,23 @@ export class GlobalStatusComponent implements OnInit {
{ name: 'Disponible', value: parseFloat(diskUsage.available) }
);
if (showLoading) {
this.loading = false;
}
if (isDhcp) {
this.loadingDhcp = false;
} else {
this.loadingOgBoot = false;
}
this.loading = false;
clearTimeout(timeoutId);
},
error: error => {
this.toastService.error(error.error['hydra:description'] || 'Error al cargar el estado de ogBoot');
if (showLoading) {
this.loading = false;
}
if (isDhcp) {
this.loadingDhcp = false;
} else {
this.loadingOgBoot = false;
}
console.log(error);
this.loading = false;
this[errorState] = true;
clearTimeout(timeoutId);
}
});
}
loadRepositories(showLoading: boolean = true): void {
if (showLoading) {
this.loading = true;
}
loadRepositories(): void {
this.loading = true;
this.errorRepositories = {};
const timeoutId = setTimeout(() => {
if (showLoading) {
this.loading = false;
}
this.loading = false;
this.repositories.forEach(repository => {
if (!(repository.uuid in this.errorRepositories)) {
this.errorRepositories[repository.uuid] = true;
@ -231,15 +124,14 @@ export class GlobalStatusComponent implements OnInit {
this.errorRepositories[repository.uuid] = errorOccurred;
if (remainingRepositories === 0) {
if (showLoading) {
this.loading = false;
}
this.loading = false;
clearTimeout(timeoutId);
}
});
});
},
error => {
console.error('Error fetching repositories', error);
this.loading = false;
this.repositories.forEach(repository => {
this.errorRepositories[repository.uuid] = true;
@ -273,7 +165,7 @@ export class GlobalStatusComponent implements OnInit {
callback(false);
},
error => {
this.toastService.error(error.error['hydra:description'] || 'Error al cargar el estado del repositorio');
console.error(`Error fetching status for repository ${repositoryUuid}`, error);
clearTimeout(timeoutId);
callback(true);
}
@ -282,86 +174,23 @@ export class GlobalStatusComponent implements OnInit {
loadOgBootStatus(): void {
this.isDhcp = false;
this.loadStatus(this.ogBootApiUrl, this.ogBootDiskUsage, this.ogBootServicesStatus, this.ogBootDiskUsageChartData, this.installedOgLives, this.isDhcp, 'errorOgBoot', false);
this.loadStatus(this.ogBootApiUrl, this.ogBootDiskUsage, this.ogBootServicesStatus, this.ogBootDiskUsageChartData, this.installedOgLives, this.isDhcp, 'errorOgBoot');
}
loadDhcpStatus(): void {
this.isDhcp = true;
this.loadStatus(this.dhcpApiUrl, this.dhcpDiskUsage, this.dhcpServicesStatus, this.dhcpDiskUsageChartData, this.installedOgLives, this.isDhcp, 'errorDhcp', false);
this.loadStatus(this.dhcpApiUrl, this.dhcpDiskUsage, this.dhcpServicesStatus, this.dhcpDiskUsageChartData, this.installedOgLives, this.isDhcp, 'errorDhcp');
}
onTabChange(event: MatTabChangeEvent): void {
switch (event.index) {
case 0:
if (this.repositories.length === 0) {
this.loadRepositories(false);
}
break;
case 1:
this.loadOgBootStatus();
break;
case 2:
this.loadDhcpStatus();
break;
default:
break;
}
}
onRepositoryChange(repositoryUuid: string): void {
this.selectedRepositoryUuid = repositoryUuid;
if (repositoryUuid && !this.repositoryStatuses[repositoryUuid]) {
this.loadRepositoryStatus(repositoryUuid, (errorOccurred: boolean) => {
if (errorOccurred) {
this.errorRepositories[repositoryUuid] = true;
}
});
}
}
getSelectedRepositoryName(): string {
const selectedRepo = this.repositories.find(repo => repo.uuid === this.selectedRepositoryUuid);
return selectedRepo ? selectedRepo.name : '';
}
refreshAll(): void {
this.loading = true;
this.updateLastUpdateTime();
this.loadStatus(this.ogBootApiUrl, this.ogBootDiskUsage, this.ogBootServicesStatus, this.ogBootDiskUsageChartData, this.installedOgLives, false, 'errorOgBoot', true);
this.loadStatus(this.dhcpApiUrl, this.dhcpDiskUsage, this.dhcpServicesStatus, this.dhcpDiskUsageChartData, this.installedOgLives, true, 'errorDhcp', true);
this.loadRepositories(true);
this.syncSubnets();
this.syncTemplates();
this.syncOgLives();
this.toastService.success('Datos actualizados correctamente');
}
updateLastUpdateTime(): void {
const now = new Date();
this.lastUpdateTime = now.toLocaleTimeString('es-ES', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
getCurrentTime(): string {
const now = new Date();
return now.toLocaleTimeString('es-ES', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
retryRepositoryStatus(repositoryUuid: string): void {
this.loadRepositoryStatus(repositoryUuid, (errorOccurred: boolean) => {
this.errorRepositories[repositoryUuid] = errorOccurred;
if (!errorOccurred) {
this.toastService.success('Estado del repositorio actualizado correctamente');
} else {
this.toastService.error('Error al cargar el estado del repositorio');
if (event.tab.textLabel === 'OgBoot') {
this.loadOgBootStatus();
} else if (event.tab.textLabel === 'Dhcp') {
this.loadDhcpStatus();
} else if (event.tab.textLabel === 'Repositorios') {
if (this.repositories.length === 0) {
this.loadRepositories();
}
});
}
}
}
}

View File

@ -1,533 +1,84 @@
/* ===== LAYOUT PRINCIPAL ===== */
.dashboard {
display: flex;
flex-direction: column;
gap: 2rem;
padding: 0;
}
/* ===== SECCIÓN DE RECURSOS ===== */
.resources-section {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
gap: 1.5rem;
}
/* Layout específico para repositorios - gráficas en una sola fila */
.resources-section.repository-layout {
grid-template-columns: 1fr !important;
gap: 1.5rem;
}
.resources-section.repository-layout .resource-card {
min-width: 0;
}
.resource-card {
background: white;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.resource-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #667eea, #764ba2);
opacity: 0;
transition: opacity 0.3s ease;
}
.resource-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.resource-card:hover::before {
opacity: 1;
}
.resource-header {
.disk-usage-container,
.ram-usage-container {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
flex-direction: column;
}
.resource-icon {
background: linear-gradient(135deg, #667eea, #764ba2);
border-radius: 50%;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.resource-icon mat-icon {
color: white;
font-size: 20px;
width: 20px;
height: 20px;
}
.resource-title {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
color: #2c3e50;
}
.resource-content {
display: flex;
gap: 1.5rem;
align-items: center;
}
.chart-container {
.disk-usage,
.ram-usage {
flex: 1;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.resource-info {
flex: 1;
.service-list,
.process-list {
margin-top: 0em;
margin-bottom: 0.5em;
}
.services-status,
.processes-status {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.info-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 0;
border-bottom: 1px solid #f1f3f4;
}
.info-item:last-child {
border-bottom: none;
}
.info-label {
font-size: 0.9rem;
color: #6c757d;
font-weight: 500;
}
.info-value {
font-size: 0.9rem;
color: #2c3e50;
font-weight: 600;
}
.usage-percentage {
color: #667eea;
font-weight: 700;
}
/* ===== CPU USAGE DISPLAY ===== */
.cpu-usage-display {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
.cpu-circle {
background: linear-gradient(135deg, #667eea, #764ba2);
border-radius: 50%;
width: 120px;
height: 120px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: white;
text-align: center;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}
.cpu-percentage {
font-size: 1.8rem;
font-weight: 700;
line-height: 1;
margin-bottom: 0.25rem;
}
.cpu-label {
font-size: 0.8rem;
opacity: 0.9;
}
/* ===== SECCIÓN DE SERVICIOS ===== */
.services-section {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
.service-card {
background: white;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.service-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}
.service-header {
.services-status li {
margin: 5px 0;
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
}
.service-icon {
background: linear-gradient(135deg, #28a745, #20c997);
border-radius: 50%;
width: 40px;
height: 40px;
.processes-status li {
margin: 5px 0;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.service-icon mat-icon {
color: white;
font-size: 20px;
width: 20px;
height: 20px;
}
.service-title {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
color: #2c3e50;
}
.service-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.service-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem;
background: #f8f9fa;
border-radius: 8px;
transition: all 0.3s ease;
}
.service-item:hover {
background: #e9ecef;
transform: translateX(4px);
}
.service-status {
display: flex;
align-items: center;
gap: 0.75rem;
}
.status-indicator {
width: 12px;
height: 12px;
.status-led {
width: 10px;
height: 10px;
border-radius: 50%;
display: inline-block;
transition: all 0.3s ease;
margin-right: 10px;
}
.status-indicator.active {
background: linear-gradient(135deg, #28a745, #20c997);
box-shadow: 0 0 8px rgba(40, 167, 69, 0.4);
.status-led.active {
background-color: green;
}
.status-indicator.inactive {
background: linear-gradient(135deg, #dc3545, #c82333);
box-shadow: 0 0 8px rgba(220, 53, 69, 0.4);
.status-led.inactive {
background-color: red;
}
.service-name {
font-size: 0.9rem;
font-weight: 500;
color: #2c3e50;
.disk-title,
.ram-title {
margin-bottom: 0px;
}
.service-state {
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
padding: 0.25rem 0.75rem;
border-radius: 12px;
transition: all 0.3s ease;
.service-title,
.process-title {
margin-top: 0px;
}
.service-state.active {
background: linear-gradient(135deg, #28a745, #20c997);
color: white;
}
.service-state.inactive {
background: linear-gradient(135deg, #dc3545, #c82333);
color: white;
}
/* ===== SECCIÓN DE DATOS ===== */
.data-section {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.data-card {
background: white;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
}
.data-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}
.data-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
}
.data-icon {
background: linear-gradient(135deg, #17a2b8, #138496);
border-radius: 50%;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.data-icon mat-icon {
color: white;
font-size: 20px;
width: 20px;
height: 20px;
}
.data-title {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
color: #2c3e50;
}
.table-container {
overflow-x: auto;
border-radius: 8px;
border: 1px solid #e9ecef;
}
.data-table {
table {
width: 100%;
border-collapse: collapse;
background: white;
}
.data-table th {
background: linear-gradient(135deg, #f8f9fa, #e9ecef);
color: #495057;
padding: 1rem;
font-weight: 600;
text-align: left;
border-bottom: 2px solid #dee2e6;
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.5px;
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
.data-table td {
padding: 0.75rem 1rem;
border-bottom: 1px solid #f1f3f4;
color: #2c3e50;
font-size: 0.9rem;
}
.data-table tr:hover {
background: #f8f9fa;
}
.data-table tr:last-child td {
border-bottom: none;
}
/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
.dashboard {
gap: 1rem;
}
.resources-section {
grid-template-columns: 1fr;
gap: 1rem;
}
.services-section {
grid-template-columns: 1fr;
gap: 1rem;
}
.resource-content {
flex-direction: column;
gap: 1rem;
}
.resource-card,
.service-card,
.data-card {
padding: 1rem;
}
.cpu-circle {
width: 100px;
height: 100px;
}
.cpu-percentage {
font-size: 1.5rem;
}
.service-item {
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
}
.service-item:hover {
transform: none;
}
}
@media (max-width: 480px) {
.resource-header,
.service-header,
.data-header {
flex-direction: column;
text-align: center;
gap: 0.5rem;
}
.resource-icon,
.service-icon,
.data-icon {
width: 35px;
height: 35px;
}
.resource-icon mat-icon,
.service-icon mat-icon,
.data-icon mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
.resource-title,
.service-title,
.data-title {
font-size: 1.1rem;
}
.info-item {
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
}
.data-table th,
.data-table td {
padding: 0.5rem;
font-size: 0.8rem;
}
}
/* ===== ANIMACIONES ===== */
@keyframes slideInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.resource-card,
.service-card,
.data-card {
animation: slideInUp 0.6s ease-out;
}
.resource-card:nth-child(1) { animation-delay: 0.1s; }
.resource-card:nth-child(2) { animation-delay: 0.2s; }
.resource-card:nth-child(3) { animation-delay: 0.3s; }
.service-card:nth-child(1) { animation-delay: 0.4s; }
.service-card:nth-child(2) { animation-delay: 0.5s; }
.data-card { animation-delay: 0.6s; }
/* ===== ESTILOS PARA LOS GRÁFICOS ===== */
::ng-deep .chart-container ngx-charts-pie-chart {
width: 100% !important;
height: auto !important;
}
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend {
position: relative !important;
top: auto !important;
left: auto !important;
right: auto !important;
bottom: auto !important;
display: block !important;
margin-top: 1rem !important;
}
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend .legend-labels {
display: flex !important;
flex-direction: column !important;
align-items: center !important;
justify-content: center !important;
}
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend .legend-label {
display: flex !important;
align-items: center !important;
margin: 0.25rem 0 !important;
th {
background-color: #f4f4f4;
}

View File

@ -1,206 +1,113 @@
<app-loading [isLoading]="loading"></app-loading>
<div *ngIf="!loading" class="dashboard">
<!-- Sección de uso de recursos -->
<div class="resources-section">
<!-- Disk Usage Section -->
<div class="resource-card disk-usage-container">
<div class="resource-header">
<div class="resource-icon">
<mat-icon>storage</mat-icon>
</div>
<h3 class="resource-title">{{ 'diskUsageTitle' | translate }}</h3>
</div>
<div class="resource-content">
<div class="chart-container" joyrideStep="diskUsageStep" text="{{ 'diskUsageDescription' | translate }}">
<ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="diskUsageChartData" [doughnut]="isDoughnut"
[labels]="showLabels">
</ngx-charts-pie-chart>
</div>
<div class="resource-info">
<div class="info-item">
<span class="info-label">{{ 'totalLabel' | translate }}:</span>
<span class="info-value">{{ isRepository ? diskUsage.total : formatBytes(diskUsage.total) }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'usedLabel' | translate }}:</span>
<span class="info-value">{{ isRepository ? diskUsage.used : formatBytes(diskUsage.used) }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'availableLabel' | translate }}:</span>
<span class="info-value">{{ isRepository ? diskUsage.available : formatBytes(diskUsage.available) }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'usedPercentageLabel' | translate }}:</span>
<span class="info-value usage-percentage">{{ isRepository ? diskUsage.used_percentage : diskUsage.percentage }}%</span>
</div>
</div>
</div>
</div>
<!-- RAM Usage Section -->
<div class="resource-card ram-usage-container" *ngIf="isRepository">
<div class="resource-header">
<div class="resource-icon">
<mat-icon>memory</mat-icon>
</div>
<h3 class="resource-title">{{ 'RamUsage' | translate }}</h3>
</div>
<div class="resource-content">
<div class="chart-container">
<ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="ramUsageChartData" [doughnut]="isDoughnut"
[labels]="showLabels">
</ngx-charts-pie-chart>
</div>
<div class="resource-info">
<div class="info-item">
<span class="info-label">{{ 'totalLabel' | translate }}:</span>
<span class="info-value">{{ ramUsage.total }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'usedLabel' | translate }}:</span>
<span class="info-value">{{ ramUsage.used }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'availableLabel' | translate }}:</span>
<span class="info-value">{{ ramUsage.available }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ 'usedPercentageLabel' | translate }}:</span>
<span class="info-value usage-percentage">{{ ramUsage.used_percentage }}%</span>
</div>
</div>
</div>
</div>
<!-- CPU Usage Section -->
<div class="resource-card cpu-usage-container" *ngIf="isRepository">
<div class="resource-header">
<div class="resource-icon">
<mat-icon>speed</mat-icon>
</div>
<h3 class="resource-title">{{ 'CpuUsage' | translate }}</h3>
</div>
<div class="resource-content">
<div class="cpu-usage-display">
<div class="cpu-circle">
<div class="cpu-percentage">{{ cpuUsage.used_percentage }}%</div>
<div class="cpu-label">Uso actual</div>
</div>
</div>
<!-- Disk Usage Section -->
<div class="disk-usage-container">
<h3 class="disk-title">{{ 'diskUsageTitle' | translate }}</h3>
<div class="disk-usage" joyrideStep="diskUsageStep" text="{{ 'diskUsageDescription' | translate }}">
<ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="diskUsageChartData" [doughnut]="isDoughnut"
[labels]="showLabels">
</ngx-charts-pie-chart>
<div class="disk-usage-info">
<p>{{ 'totalLabel' | translate }}: <strong>{{ isRepository ? diskUsage.total : formatBytes(diskUsage.total) }}</strong></p>
<p>{{ 'usedLabel' | translate }}: <strong>{{ isRepository ? diskUsage.used : formatBytes(diskUsage.used) }}</strong></p>
<p>{{ 'availableLabel' | translate }}: <strong>{{ isRepository ? diskUsage.available : formatBytes(diskUsage.available) }}</strong></p>
<p>{{ 'usedPercentageLabel' | translate }}: <strong>{{ isRepository ? diskUsage.used_percentage : diskUsage.percentage }}</strong></p>
</div>
</div>
</div>
<!-- Sección de servicios y procesos -->
<div class="services-section">
<!-- Services Status Section -->
<div class="service-card services-status" joyrideStep="servicesStatusStep" text="{{ 'servicesStatusDescription' | translate }}">
<div class="service-header">
<div class="service-icon">
<mat-icon>settings</mat-icon>
</div>
<h3 class="service-title">{{ 'servicesTitle' | translate }}</h3>
</div>
<div class="service-list">
<div class="service-item" *ngFor="let service of getServices()">
<div class="service-status">
<span class="status-indicator"
[ngClass]="{ 'active': service.status === 'active', 'inactive': service.status !== 'active' }"></span>
<span class="service-name">{{ service.name }}</span>
</div>
<span class="service-state" [ngClass]="{ 'active': service.status === 'active', 'inactive': service.status !== 'active' }">
{{ service.status | translate }}
</span>
</div>
</div>
</div>
<!-- Processes Status Section -->
<div class="service-card processes-status" *ngIf="isRepository">
<div class="service-header">
<div class="service-icon">
<mat-icon>list_alt</mat-icon>
</div>
<h3 class="service-title">{{ 'processes' | translate }}</h3>
</div>
<div class="service-list">
<div class="service-item" *ngFor="let process of getProcesses()">
<div class="service-status">
<span class="status-indicator"
[ngClass]="{ 'active': process.status === 'running', 'inactive': process.status !== 'running' }"></span>
<span class="service-name">{{ process.name }}</span>
</div>
<span class="service-state" [ngClass]="{ 'active': process.status === 'running', 'inactive': process.status !== 'running' }">
{{ process.status }}
</span>
</div>
<!-- RAM Usage Section -->
<div class="ram-usage-container" *ngIf="isRepository">
<h3 class="ram-title">{{ 'RamUsage' | translate }}</h3>
<div class="ram-usage">
<ngx-charts-pie-chart [view]="view" [scheme]="colorScheme" [results]="ramUsageChartData" [doughnut]="isDoughnut"
[labels]="showLabels">
</ngx-charts-pie-chart>
<div class="ram-usage-info">
<p>{{ 'totalLabel' | translate }}: <strong>{{ ramUsage.total }}</strong></p>
<p>{{ 'usedLabel' | translate }}: <strong>{{ ramUsage.used }}</strong></p>
<p>{{ 'availableLabel' | translate }}: <strong>{{ ramUsage.available }}</strong></p>
<p>{{ 'usedPercentageLabel' | translate }}: <strong>{{ ramUsage.used_percentage }}</strong></p>
</div>
</div>
</div>
<!-- Sección de datos específicos -->
<div class="data-section">
<!-- Installed OgLives Section -->
<div class="data-card" *ngIf="!isRepository && !isDhcp">
<div class="data-header">
<div class="data-icon">
<mat-icon>computer</mat-icon>
</div>
<h3 class="data-title">{{ 'InstalledOglivesTitle' | translate }}</h3>
</div>
<div class="table-container">
<table class="data-table">
<thead>
<tr>
<th>{{ 'idLabel' | translate }}</th>
<th>{{ 'kernelLabel' | translate }}</th>
<th>{{ 'architectureLabel' | translate }}</th>
<th>{{ 'revisionLabel' | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of installedOgLives">
<td>{{ item.id }}</td>
<td>{{ item.kernel }}</td>
<td>{{ item.architecture }}</td>
<td>{{ item.revision }}</td>
</tr>
</tbody>
</table>
</div>
<!-- CPU Usage Section -->
<div class="cpu-usage-container" *ngIf="isRepository">
<h3 class="cpu-title">{{ 'CpuUsage' | translate }}</h3>
<div class="cpu-usage">
<p>{{ 'usedLabel' | translate }}: <strong>{{ cpuUsage.used_percentage }}</strong></p>
</div>
</div>
<!-- Subnets Section -->
<div class="data-card" *ngIf="isDhcp">
<div class="data-header">
<div class="data-icon">
<mat-icon>router</mat-icon>
</div>
<h3 class="data-title">{{ 'subnets' | translate }}</h3>
</div>
<div class="table-container">
<table class="data-table">
<thead>
<tr>
<th>{{ 'idLabel' | translate }}</th>
<th>{{ 'bootFileNameLabel' | translate }}</th>
<th>{{ 'nextServerLabel' | translate }}</th>
<th>{{ 'ipLabel' | translate }}</th>
<th>{{ 'clientsLabel' | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of subnets">
<td>{{ item.id }}</td>
<td>{{ item['boot-file-name'] }}</td>
<td>{{ item['next-server'] }}</td>
<td>{{ item.subnet }}</td>
<td>{{ item.reservations.length }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Services Status Section -->
<div class="services-status" joyrideStep="servicesStatusStep" text="{{ 'servicesStatusDescription' | translate }}">
<h3 class="service-title">{{ 'servicesTitle' | translate }}</h3>
<ul class="service-list">
<li *ngFor="let service of getServices()">
<span class="status-led"
[ngClass]="{ 'active': service.status === 'active', 'inactive': service.status !== 'active' }"></span>
{{ service.name }}: {{ service.status | translate }}
</li>
</ul>
</div>
<!-- Processes Status Section -->
<div class="processes-status" *ngIf="isRepository">
<h3 class="process-title">{{ 'processes' | translate }}</h3>
<ul class="process-list">
<li *ngFor="let process of getProcesses()">
<span class="status-led"
[ngClass]="{ 'active': process.status === 'running', 'inactive': process.status !== 'running' }"></span>
{{ process.name }}: {{ process.status }}
</li>
</ul>
</div>
<!-- Installed OgLives / Subnets Section -->
<div *ngIf="!isRepository && !isDhcp">
<h3>{{ 'InstalledOglivesTitle' | translate }}</h3>
<table>
<thead>
<tr>
<th>{{ 'idLabel' | translate }}</th>
<th>{{ 'kernelLabel' | translate }}</th>
<th>{{ 'architectureLabel' | translate }}</th>
<th>{{ 'revisionLabel' | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of installedOgLives">
<td>{{ item.id }}</td>
<td>{{ item.kernel }}</td>
<td>{{ item.architecture }}</td>
<td>{{ item.revision }}</td>
</tr>
</tbody>
</table>
</div>
<div *ngIf="isDhcp">
<h3>{{ 'subnets' | translate }}</h3>
<table>
<thead>
<tr>
<th>{{ 'idLabel' | translate }}</th>
<th>{{ 'bootFileNameLabel' | translate }}</th>
<th>{{ 'nextServerLabel' | translate }}</th>
<th>{{ 'ipLabel' | translate }}</th>
<th>{{ 'clientsLabel' | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of subnets">
<td>{{ item.id }}</td>
<td>{{ item['boot-file-name'] }}</td>
<td>{{ item['next-server'] }}</td>
<td>{{ item.subnet }}</td>
<td>{{ item.reservations.length }}</td>
</tr>
</tbody>
</table>
</div>
</div>

View File

@ -5,13 +5,6 @@
padding: 10px;
}
.table-header-container {
display: flex;
align-items: center;
padding: 10px;
gap: 20px;
}
.client-container {
flex-grow: 1;
box-sizing: border-box;
@ -280,7 +273,7 @@
}
.table-container {
flex: 5;
flex: 3;
display: flex;
justify-content: center;
align-items: center;

View File

@ -29,12 +29,8 @@
</div>
</div>
</div>
<div class="table-header-container">
<div class="header-container">
<h2 class="title" i18n="@@adminImagesTitle">Discos/Particiones</h2>
<mat-chip *ngIf="clientData.firmwareType" class="firmware-chip">
<mat-icon>memory</mat-icon>
{{ clientData.firmwareType }}
</mat-chip>
</div>
<div class="disk-container">

View File

@ -1,5 +1,4 @@
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from "@angular/common";
import { MatTableDataSource } from "@angular/material/table";
@ -15,11 +14,11 @@ interface ClientInfo {
}
@Component({
selector: 'app-client-details',
templateUrl: './client-details.component.html',
styleUrl: './client-details.component.css'
selector: 'app-client-main-view',
templateUrl: './client-main-view.component.html',
styleUrl: './client-main-view.component.css'
})
export class ClientDetailsComponent {
export class ClientMainViewComponent implements OnInit {
baseUrl: string;
@ViewChild('assistantContainer') assistantContainer!: ElementRef;
clientUuid: string;
@ -35,30 +34,39 @@ export class ClientDetailsComponent {
partitions: any[] = [];
commands: any[] = [];
chartDisk: any[] = [];
view: [number, number] = [260, 160];
view: [number, number] = [300, 200];
showLegend: boolean = true;
arrayCommands: any[] = [
{ name: 'Enceder', slug: 'power-on' },
{ name: 'Apagar', slug: 'power-off' },
{ name: 'Reiniciar', slug: 'reboot' },
{ name: 'Iniciar Sesión', slug: 'login' },
{ name: 'Crear imagen', slug: 'create-image' },
{ name: 'Clonar/desplegar imagen', slug: 'deploy-image' },
{ name: 'Eliminar Imagen Cache', slug: 'delete-image-cache' },
{ name: 'Particionar y Formatear', slug: 'partition' },
{ name: 'Inventario Software', slug: 'software-inventory' },
{ name: 'Inventario Hardware', slug: 'hardware-inventory' },
{ name: 'Ejecutar comando', slug: 'run-script' },
];
datePipe: DatePipe = new DatePipe('es-ES');
columns = [
{
columnDef: 'diskNumber',
header: 'Disco',
cell: (partition: any) => partition.diskNumber,
cell: (partition: any) => `${partition.diskNumber}`,
},
{
columnDef: 'partitionNumber',
header: 'Particion',
cell: (partition: any) => partition.partitionNumber
},
{
columnDef: 'partitionCode',
header: 'Tipo de partición',
cell: (partition: any) => partition.partitionCode
cell: (partition: any) => `${partition.partitionNumber}`
},
{
columnDef: 'description',
header: 'Sistema de ficheros',
cell: (partition: any) => partition.filesystem
cell: (partition: any) => `${partition.filesystem}`
},
{
columnDef: 'size',
@ -68,13 +76,13 @@ export class ClientDetailsComponent {
{
columnDef: 'memoryUsage',
header: 'Uso',
cell: (partition: any) => `${partition.memoryUsage}%`
cell: (partition: any) => `${partition.memoryUsage} %`
},
{
columnDef: 'operativeSystem',
header: 'SO/Imagen',
cell: (partition: any) => partition.operativeSystem?.name
}
header: 'SO',
cell: (partition: any) => `${partition.operativeSystem?.name}`
},
];
displayedColumns = [...this.columns.map(column => column.columnDef)];
isDiskUsageEmpty: boolean = true;
@ -85,8 +93,7 @@ export class ClientDetailsComponent {
private dialog: MatDialog,
private configService: ConfigService,
private router: Router,
private toastService: ToastrService,
@Inject(MAT_DIALOG_DATA) public data: { clientData: any }
private toastService: ToastrService
) {
this.baseUrl = this.configService.apiUrl;
const url = window.location.href;
@ -95,16 +102,31 @@ export class ClientDetailsComponent {
}
ngOnInit() {
if (this.data && this.data.clientData) {
this.clientData = this.data.clientData;
this.updateGeneralData();
this.updateNetworkData();
this.calculateDiskUsage();
this.loadPartitions();
this.loading = false;
} else {
console.error('No se recibieron datos del cliente.');
}
this.clientData = history.state.clientData['@id'];
this.loadClient(this.clientData)
this.loadCommands()
this.calculateDiskUsage();
this.loading = false;
}
loadClient = (uuid: string) => {
this.http.get<any>(`${this.baseUrl}${uuid}`).subscribe({
next: data => {
this.clientData = data;
this.updateGeneralData();
this.updateNetworkData();
this.loadPartitions()
this.loading = false;
},
error: error => {
console.error('Error al obtener el cliente:', error);
}
});
}
navigateToGroups() {
this.router.navigate(['/groups']);
}
updateGeneralData() {
@ -121,7 +143,7 @@ export class ClientDetailsComponent {
updateNetworkData() {
this.networkData = [
{ property: 'Padre', value: this.clientData?.organizationalUnit?.name || '' },
{ property: 'Pxe', value: this.clientData?.pxeTemplate?.name || '' },
{ property: 'Pxe', value: this.clientData?.template?.name || '' },
{ property: 'Remote Pc', value: this.clientData.remotePc || '' },
{ property: 'Subred', value: this.clientData?.subnet || '' },
{ property: 'OGlive', value: this.clientData?.ogLive?.name || '' },
@ -176,14 +198,16 @@ export class ClientDetailsComponent {
this.isDiskUsageEmpty = this.diskUsageData.length === 0;
}
loadPartitions(): void {
if (!this.clientData?.id) {
return;
}
onEditClick(event: MouseEvent, uuid: string): void {
event.stopPropagation();
const dialogRef = this.dialog.open(ManageClientComponent, { data: { uuid }, width: '900px' });
dialogRef.afterClosed().subscribe();
}
this.http.get<any>(`${this.baseUrl}/partitions?client.id=${this.clientData.id}&order[diskNumber, partitionNumber]=ASC`).subscribe({
loadPartitions(): void {
this.http.get<any>(`${this.baseUrl}/partitions?client.id=${this.clientData?.id}&order[diskNumber, partitionNumber]=ASC`).subscribe({
next: data => {
const filteredPartitions = data['hydra:member'];
const filteredPartitions = data['hydra:member'].filter((partition: any) => partition.partitionNumber !== 0);
this.dataSource = filteredPartitions;
this.partitions = filteredPartitions;
this.calculateDiskUsage();
@ -194,7 +218,96 @@ export class ClientDetailsComponent {
});
}
onNoClick(): void {
this.dialog.closeAll();
loadCommands(): void {
this.http.get<any>(`${this.baseUrl}/commands?`).subscribe({
next: data => {
this.commands = data['hydra:member'];
},
error: error => {
console.error('Error al obtener las particiones:', error);
}
});
}
onCommandSelect(action: any): void {
if (action === 'partition') {
this.openPartitionAssistant();
}
if (action === 'create-image') {
this.openCreateImageAssistant();
}
if (action === 'deploy-image') {
this.openDeployImageAssistant();
}
if (action === 'reboot') {
this.rebootClient();
}
if (action === 'power-off') {
this.powerOffClient();
}
if (action === 'power-on') {
this.powerOnClient();
}
}
rebootClient(): void {
this.http.post(`${this.baseUrl}/clients/server/${this.clientData.uuid}/reboot`, {}).subscribe(
response => {
this.toastService.success('Cliente actualizado correctamente');
},
error => {
this.toastService.error('Error de conexión con el cliente');
}
);
}
powerOnClient(): void {
const payload = {
client: this.clientData['@id']
}
this.http.post(`${this.baseUrl}${this.clientData.repository['@id']}/wol`, payload).subscribe(
response => {
this.toastService.success('Cliente actualizado correctamente');
},
error => {
this.toastService.error('Error de conexión con el cliente');
}
);
}
powerOffClient(): void {
this.http.post(`${this.baseUrl}/clients/server/${this.clientData.uuid}/power-off`, {}).subscribe(
response => {
this.toastService.success('Cliente actualizado correctamente');
},
error => {
this.toastService.error('Error de conexión con el cliente');
}
);
}
openPartitionAssistant(): void {
this.router.navigate([`/clients/${this.clientData.uuid}/partition-assistant`]).then(r => {
console.log('navigated', r);
});
}
openCreateImageAssistant(): void {
this.router.navigate([`/clients/${this.clientData.uuid}/create-image`]).then(r => {
console.log('navigated', r);
});
}
openDeployImageAssistant(): void {
this.router.navigate([`/clients/deploy-image`]).then(r => {
console.log('navigated', r);
});
}
}

View File

@ -1,677 +1,105 @@
/* Contenedor principal modernizado */
.title {
font-size: 24px;
}
.calendar-button-row {
display: flex;
justify-content: flex-start;
margin-top: 16px;
}
.divider {
margin: 20px 0;
}
.lists-container {
padding: 16px;
}
.card.unidad-card {
height: 100%;
box-sizing: border-box;
}
table {
width: 100%;
margin-top: 50px;
background-color: #eaeff6;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 5px;
box-sizing: border-box;
}
.select-container {
gap: 24px;
gap: 16px;
width: 100%;
box-sizing: border-box;
padding: 32px;
background: white !important;
border-radius: 4px;
margin: 20px 0;
align-items: center;
}
/* Secciones del formulario */
.form-section {
background: white !important;
border-radius: 8px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
border: 1px solid #bbdefb;
}
.form-section-title {
font-size: 18px;
font-weight: 600;
color: #333;
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 8px;
}
.form-section-title mat-icon {
color: #2196f3;
padding: 20px;
}
.selector {
display: flex;
gap: 20px;
gap: 16px;
width: 100%;
margin-top: 16px;
margin-top: 30px;
box-sizing: border-box;
align-items: start;
}
.half-width {
flex: 1;
max-width: calc(50% - 10px);
max-width: 50%;
}
.full-width {
.search-string {
flex: 2;
padding: 5px;
}
.search-boolean {
flex: 1;
width: 100%;
padding: 5px;
}
/* Header modernizado */
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
.header-container-title {
flex-grow: 1;
text-align: left;
}
.header-container-title h2 {
margin: 0 0 8px 0;
color: #333;
font-weight: 600;
}
/* Estilos modernos para el badge de destino */
.destination-info {
margin-top: 12px;
}
.destination-badge {
display: inline-flex;
align-items: center;
background: #e3f2fd;
color: #1565c0;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #bbdefb;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
}
.destination-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #1976d2;
}
.destination-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.destination-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #1976d2;
line-height: 1;
}
.destination-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #0d47a1;
padding-left: 1em;
}
.button-row {
display: flex;
gap: 12px;
padding-right: 0;
padding-right: 1em;
}
/* Tabla de particiones modernizada */
.partition-table-container {
background: white;
padding: 24px;
background-color: #eaeff6;
padding: 20px;
border-radius: 12px;
margin-top: 24px;
}
.partition-table-container h3 {
margin: 0 0 20px 0;
color: #333;
font-weight: 600;
font-size: 18px;
}
.repository-label {
font-weight: 500;
margin-right: 8px;
}
mat-chip {
margin-top: 8px !important;
border-radius: 20px !important;
}
mat-icon {
margin-right: 4px;
}
/* Botón de crear repositorio modernizado */
.create-repository-button {
color: white;
border: none;
padding: 12px 20px;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
}
.create-repository-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}
.create-repository-button mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
/* Botones modernizados */
.action-button {
border-radius: 8px;
font-weight: 500;
padding: 12px 24px;
transition: all 0.3s ease;
}
.action-button:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
/* Campos de formulario modernizados */
mat-form-field {
margin-bottom: 8px;
}
::ng-deep .mat-form-field-appearance-fill .mat-form-field-flex {
border-radius: 8px;
background-color: white !important;
border: 1px solid #e9ecef;
transition: all 0.3s ease;
}
::ng-deep .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex {
background-color: white;
border-color: #2196f3;
box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}
/* Overlay de carga para creación de repositorio */
.creating-repository-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9999;
color: white;
backdrop-filter: blur(4px);
}
.creating-repository-overlay p {
margin-top: 16px;
font-size: 16px;
font-weight: 500;
}
/* Estilo para hacer el backdrop no clickeable */
::ng-deep .non-clickable-backdrop {
pointer-events: none !important;
}
/* Responsive design */
@media (max-width: 768px) {
.select-container {
padding: 16px;
}
.header-container {
padding: 16px;
flex-direction: column;
gap: 16px;
align-items: stretch;
}
.selector {
flex-direction: column;
gap: 16px;
}
.half-width {
max-width: 100%;
}
.create-repository-button {
min-width: 100%;
margin-left: 0;
}
.button-row {
justify-content: center;
}
.destination-badge {
padding: 10px 14px;
border-radius: 10px;
}
.destination-icon {
font-size: 18px;
width: 18px;
height: 18px;
margin-right: 10px;
}
.destination-value {
max-width: 150px;
font-size: 13px;
}
.destination-label {
font-size: 10px;
}
}
/* Estilos para elementos específicos */
.unit-name {
font-weight: 500;
color: #2c3e50;
}
/* Estilos para las opciones de acción Git */
.git-action-selector {
margin: 24px 0;
padding: 20px;
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border-radius: 12px;
border: 1px solid #dee2e6;
}
.action-chips-container {
margin-bottom: 16px;
}
::ng-deep .action-chip {
margin: 8px !important;
padding: 12px 20px !important;
border-radius: px !important;
font-weight: 500 !important;
font-size: 14px !important;
transition: all 0.3s ease !important;
border: 2px solid transparent !important;
background: white !important;
color: #6c757d !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
cursor: pointer !important;
display: flex !important;
align-items: center !important;
gap: 8px !important;
min-height: 48px !important;
}
::ng-deep .action-chip:hover {
transform: translateY(-2px) !important;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15) !important;
}
::ng-deep .action-chip.mat-mdc-chip-selected {
border-color: #667eea !important;
box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2) !important;
}
::ng-deep .create-chip.mat-mdc-chip-selected {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
color: white !important;
}
::ng-deep .update-chip.mat-mdc-chip-selected {
background: linear-gradient(135deg, #007bff 0%, #0056b3 100%) !important;
color: white !important;
}
::ng-deep .action-chip mat-icon {
font-size: 18px !important;
width: 18px !important;
height: 18px !important;
}
.action-hint {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
background: rgba(102, 126, 234, 0.1);
border-radius: 8px;
border-left: 4px solid #667eea;
color: #495057;
font-size: 14px;
}
.action-hint mat-icon {
color: #667eea;
font-size: 16px;
width: 16px;
height: 16px;
}
.git-action-section {
background: white !important;
border-radius: 8px;
padding: 16px;
margin-top: 16px;
border-left: 4px solid #667eea;
}
/* Eliminar sombra de la tabla */
.mat-elevation-z8 {
box-shadow: none !important;
}
/* Animaciones para transiciones de formulario */
.form-transition {
transition: all 0.3s ease-in-out;
opacity: 1;
transform: translateY(0);
}
.form-transition.ng-enter {
opacity: 0;
transform: translateY(10px);
}
.form-transition.ng-enter-active {
opacity: 1;
transform: translateY(0);
}
.form-transition.ng-leave {
opacity: 1;
transform: translateY(0);
}
.form-transition.ng-leave-active {
opacity: 0;
transform: translateY(-10px);
}
/* Estilos para los formularios específicos */
.git-form-section {
background: white;
border-radius: 4px;
padding: 20px;
margin-top: 16px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
border: 1px solid #e9ecef;
transition: all 0.3s ease;
}
.git-form-section:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}
/* Estilos para la sección de repositorio Git */
.git-repository-section {
background: white !important;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #e9ecef;
}
.repository-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
padding-bottom: 12px;
}
.repository-header h4 {
margin: 0;
color: #2c3e50;
font-weight: 600;
font-size: 16px;
display: flex;
align-items: center;
gap: 8px;
}
.repository-selector {
display: flex;
gap: 20px;
align-items: flex-start;
}
.repository-field {
flex: 0 0 300px;
min-width: 250px;
}
.repository-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.info-item {
display: flex;
align-items: flex-start;
gap: 8px;
color: #6c757d;
font-size: 13px;
line-height: 1.4;
}
.info-item mat-icon {
color: #667eea;
font-size: 16px;
width: 16px;
height: 16px;
margin-top: 2px;
flex-shrink: 0;
}
.create-repository-button {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
color: white;
border: none;
padding: 10px 16px;
border-radius: 6px;
font-weight: 500;
font-size: 14px;
transition: all 0.3s ease;
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
box-shadow: 0 2px 8px rgba(40, 167, 69, 0.2);
}
.create-repository-button:hover:not(:disabled) {
background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}
.create-repository-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.create-repository-button mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
.no-repositories-hint {
display: flex;
align-items: flex-start;
gap: 8px;
color: #dc3545;
font-weight: 500;
font-size: 13px;
padding: 4px 4px 4px 12px;
background: rgba(220, 53, 69, 0.1);
border-radius: 6px;
border-left: 3px solid #dc3545;
line-height: 1.4;
}
.no-repositories-hint mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
margin-top: 2px;
flex-shrink: 0;
}
/* Estilos para el hint del formulario */
::ng-deep .mat-form-field-hint {
display: flex !important;
align-items: center !important;
gap: 6px !important;
color: #6c757d !important;
font-size: 12px !important;
}
::ng-deep .mat-form-field-hint mat-icon {
font-size: 14px !important;
width: 14px !important;
height: 14px !important;
color: #667eea !important;
}
/* Responsive */
@media (max-width: 768px) {
.header-container {
flex-direction: column;
gap: 20px;
text-align: center;
}
.button-row {
flex-wrap: wrap;
justify-content: center;
}
.selector {
flex-direction: column;
}
.half-width {
min-width: auto;
}
.clients-grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
.input-group {
grid-template-columns: 1fr;
}
.select-container {
padding: 0 16px;
}
.form-section {
padding: 20px;
}
/* Responsive para repositorio Git */
.repository-header {
flex-direction: column;
gap: 12px;
align-items: flex-start;
}
.repository-selector {
flex-direction: column;
gap: 16px;
}
.repository-field {
flex: none;
width: 100%;
min-width: auto;
}
.repository-info {
flex: none;
}
.create-repository-button {
width: 100%;
justify-content: center;
}
}
/* Botón flotante para scroll hacia arriba */
.scroll-to-top-button {
position: fixed;
bottom: 30px;
left: 30px;
z-index: 1000;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.scroll-to-top-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}
/* Animación de entrada/salida */
.scroll-to-top-button {
animation: fadeInUp 0.3s ease;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Responsive para el botón */
@media (max-width: 768px) {
.scroll-to-top-button {
bottom: 20px;
left: 20px;
}
margin-top: 20px;
}

View File

@ -1,205 +1,59 @@
<!-- Overlay de carga para creación de repositorio -->
<app-modal-overlay
[isVisible]="creatingRepository"
message="Creando repositorio...">
</app-modal-overlay>
<app-loading [isLoading]="loading"></app-loading>
<div class="header-container">
<div class="header-container-title">
<h2>
<h2 >
Crear imagen desde {{ clientName }}
</h2>
<div class="destination-info">
<div class="destination-badge">
<mat-icon class="destination-icon">cloud_upload</mat-icon>
<div class="destination-content">
<span class="destination-label">Destino</span>
<span class="destination-value">{{ selectedRepository?.name || 'No hay repositorio asociado' }}</span>
</div>
</div>
</div>
</div>
<div class="button-row">
<button class="action-button" id="execute-button" [disabled]="!selectedPartition" (click)="save()">Ejecutar</button>
<button class="action-button" [disabled]="!selectedPartition" (click)="save()">Ejecutar</button>
</div>
</div>
<mat-divider></mat-divider>
<div class="select-container">
<!-- Sección: Configuración de tipo de imagen -->
<div class="form-section">
<div class="form-section-title">
<mat-icon>settings</mat-icon>
Configuración de tipo de imagen
</div>
<div class="selector">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Tipo de imagen</mat-label>
<mat-select [(ngModel)]="imageType" class="full-width" (selectionChange)="onImageTypeSelected($event.value)">
<mat-option [value]="'monolithic'">Monolítica</mat-option>
<mat-option [value]="'git'">Git</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="selector">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Nombre canónico</mat-label>
<input matInput [disabled]="selectedImage" [(ngModel)]="name" placeholder="Nombre canónico. En minúscula y sin espacios" required>
</mat-form-field>
<mat-form-field appearance="fill" class="half-width">
<mat-label>Seleccione imagen</mat-label>
<mat-select [(ngModel)]="selectedImage" name="selectedImage" (selectionChange)="resetCanonicalName()" required>
<mat-option *ngFor="let image of images" [value]="image">{{ image?.name }}</mat-option>
</mat-select>
<mat-hint>Seleccione la imagen para sobreescribir si se requiere. </mat-hint>
</mat-form-field>
</div>
<!-- Sección: Configuración Git (solo para tipo git) -->
<div class="form-section" *ngIf="imageType === 'git'">
<div class="form-section-title">
<mat-icon>code</mat-icon>
Configuración Git
</div>
<div class="git-repository-section">
<div class="repository-header">
<button *ngIf="imageType === 'git'"
class="create-repository-button"
(click)="openCreateRepositoryModal()"
[disabled]="creatingRepository">
<mat-icon>add</mat-icon>
<span>Crear nuevo repositorio / SO</span>
</button>
</div>
<div class="selector">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccionar repositorio Git</mat-label>
<mat-select [(ngModel)]="selectedGitRepository" (selectionChange)="onGitRepositorySelected($event.value)" required>
<mat-option [value]="null">Seleccionar repositorio git / SO</mat-option>
<mat-option *ngFor="let repo of gitRepositories" [value]="repo">{{ repo.name }}</mat-option>
</mat-select>
<mat-spinner *ngIf="loadingGitRepositories" matSuffix diameter="20"></mat-spinner>
<mat-hint>
<mat-icon>info</mat-icon>
Selecciona el repositorio git para obtener las imágenes disponibles.
<span *ngIf="gitRepositories.length === 0" class="no-repositories-hint">
No hay repositorios disponibles. Crea uno nuevo para continuar.
</span>
</mat-hint>
</mat-form-field>
</div>
</div>
<!-- Opciones de acción Git -->
<div class="git-action-selector">
<div class="action-chips-container">
<mat-chip-listbox [(ngModel)]="gitAction" required class="action-chip-listbox">
<mat-chip-option value="create" class="action-chip create-chip firmware-chip" (click)="onGitActionSelected({value: 'create'})">
<span>Crear imagen</span>
</mat-chip-option>
<mat-chip-option value="update" class="action-chip update-chip firmware-chip" (click)="onGitActionSelected({value: 'update'})">
<span>Actualizar imagen</span>
</mat-chip-option>
</mat-chip-listbox>
</div>
<div class="action-hint">
<mat-icon>info</mat-icon>
<span *ngIf="gitAction === 'create'">Crea una nueva imagen con el nombre especificado</span>
<span *ngIf="gitAction === 'update'">Actualiza una imagen existente seleccionada</span>
</div>
</div>
<div class="partition-table-container">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">Seleccionar partición</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group
[(ngModel)]="selectedPartition"
[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 }} </th>
<td mat-cell *matCellDef="let image">
{{ column.cell(image) }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<!-- Sección: Configuración general -->
<div class="form-section" *ngIf="imageType !== 'git'">
<div class="form-section-title">
<mat-icon>image</mat-icon>
Configuración de imagen
</div>
<!-- Opciones de acción para imágenes monolíticas -->
<div class="action-chips-container">
<mat-chip-listbox [(ngModel)]="monolithicAction" required class="action-chip-listbox">
<mat-chip-option value="create" class="action-chip create-chip firmware-chip" (click)="onMonolithicActionSelected({value: 'create'})">
<span>Crear imagen</span>
</mat-chip-option>
<mat-chip-option value="update" class="action-chip update-chip firmware-chip" (click)="onMonolithicActionSelected({value: 'update'})">
<span>Actualizar imagen</span>
</mat-chip-option>
</mat-chip-listbox>
</div>
<div class="action-hint">
<mat-icon>info</mat-icon>
<span *ngIf="monolithicAction === 'create'">Crea una nueva imagen con el nombre especificado</span>
<span *ngIf="monolithicAction === 'update'">Actualiza una imagen existente seleccionada</span>
</div>
<div class="selector" *ngIf="monolithicAction === 'create'">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Nombre canónico</mat-label>
<input matInput [(ngModel)]="name" placeholder="Nombre canónico. En minúscula y sin espacios" required>
<mat-hint>Introduce el nombre para la nueva imagen que se creará.</mat-hint>
</mat-form-field>
</div>
<div class="selector" *ngIf="monolithicAction === 'update'">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Seleccione imagen</mat-label>
<mat-select [(ngModel)]="selectedImage" name="selectedImage" (selectionChange)="resetCanonicalName()" required>
<mat-option [value]="null">Seleccionar imagen para actualizar</mat-option>
<mat-option *ngFor="let image of images" [value]="image">{{ image?.name }}</mat-option>
</mat-select>
<button *ngIf="selectedImage" mat-icon-button matSuffix aria-label="Clear client search"
(click)="selectedImage = null; resetCanonicalName()">
<mat-icon>close</mat-icon>
</button>
<mat-hint>Selecciona la imagen existente que quieres actualizar.</mat-hint>
</mat-form-field>
</div>
</div>
<!-- Sección: Selección de partición -->
<div class="form-section" #partitionSection id="partition-selection">
<div class="form-section-title">
<mat-icon>storage</mat-icon>
Selección de partición
</div>
<div class="partition-table-container">
<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef i18n="@@columnActions" style="text-align: start">Seleccionar partición</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group
[(ngModel)]="selectedPartition"
[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 }} </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>
</div>
<app-scroll-to-top
[threshold]="200"
targetElement=".header-container"
position="bottom-right"
[showTooltip]="true"
tooltipText="Volver arriba"
tooltipPosition="left">
</app-scroll-to-top>

View File

@ -1,13 +1,10 @@
import {Component, EventEmitter, OnInit, Output, ViewChild, ElementRef} from '@angular/core';
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ActivatedRoute, Router } from "@angular/router";
import { MatTableDataSource } from "@angular/material/table";
import { SelectionModel } from "@angular/cdk/collections";
import { ConfigService } from '@services/config.service';
import {MatDialog} from "@angular/material/dialog";
import {QueueConfirmationModalComponent} from "../../../../../shared/queue-confirmation-modal/queue-confirmation-modal.component";
import {CreateRepositoryModalComponent} from "./create-repository-modal/create-repository-modal.component";
@Component({
selector: 'app-create-image',
@ -17,63 +14,43 @@ import {CreateRepositoryModalComponent} from "./create-repository-modal/create-r
export class CreateClientImageComponent implements OnInit{
baseUrl: string;
@Output() dataChange = new EventEmitter<any>();
@ViewChild('partitionSection', { static: false }) partitionSection!: ElementRef;
errorMessage = '';
clientId: string | null = null;
partitions: any[] = [];
images: any[] = [];
clientName: string = '';
private _selectedPartition: any = null;
selectedPartition: any = null;
name: string = '';
client: any = null;
loading: boolean = false;
selectedImage: any = null;
private _imageType: string = 'monolithic';
selectedRepository: any = null;
gitRepositories: any[] = [];
selectedGitRepository: any = null;
gitImageRepositories: any[] = [];
gitImageName: string = '';
loadingGitRepositories: boolean = false;
loadingGitImageRepositories: boolean = false;
creatingRepository: boolean = false;
gitAction: string = 'create';
monolithicAction: string = 'create';
existingImages: any[] = [];
selectedExistingImage: any = null;
loadingExistingImages: boolean = false;
dataSource = new MatTableDataSource<any>();
columns = [
{
columnDef: 'diskNumber',
header: 'Disco',
cell: (partition: any) => partition.diskNumber
cell: (partition: any) => `${partition.diskNumber}`
},
{
columnDef: 'partitionNumber',
header: 'Particion',
cell: (partition: any) => partition.partitionNumber
cell: (partition: any) => `${partition.partitionNumber}`
},
{
columnDef: 'size',
header: 'Tamaño',
cell: (partition: any) => `${partition.size} MB`
},
{
columnDef: 'partitionCode',
header: 'Tipo de partición',
cell: (partition: any) => partition.partitionCode
},
{
columnDef: 'filesystem',
header: 'Sistema de ficheros',
cell: (partition: any) => partition.filesystem
cell: (partition: any) => `${partition.filesystem}`
},
{
columnDef: 'operativeSystem',
header: 'SO',
cell: (partition: any) => partition.operativeSystem?.name
cell: (partition: any) => `${partition.operativeSystem?.name}`
}
];
@ -86,13 +63,11 @@ export class CreateClientImageComponent implements OnInit{
private configService: ConfigService,
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog
) {
this.baseUrl = this.configService.apiUrl;
}
ngOnInit() {
console.log('CreateImageComponent ngOnInit ejecutado');
this.clientId = this.route.snapshot.paramMap.get('id');
this.loadPartitions();
this.loadImages();
@ -105,7 +80,6 @@ export class CreateClientImageComponent implements OnInit{
if (response.partitions) {
this.client = response;
this.clientName = response.name;
this.selectedRepository = response.repository;
this.dataSource.data = response.partitions.filter((partition: any) => {
return partition.partitionNumber !== 0;
@ -118,12 +92,8 @@ export class CreateClientImageComponent implements OnInit{
);
}
onImageTypeSelected(event: any) {
this.imageType = event;
}
loadImages() {
const url = `${this.baseUrl}/images?created=false&type=${this.imageType}&page=1&itemsPerPage=100`;
const url = `${this.baseUrl}/images?created=false&page=1&itemsPerPage=1000`;
this.http.get(url).subscribe(
(response: any) => {
this.images = response['hydra:member'];
@ -134,285 +104,44 @@ export class CreateClientImageComponent implements OnInit{
);
}
loadGitRepositories() {
this.loadingGitRepositories = true;
const url = `${this.baseUrl}/git-repositories?repository=${this.selectedRepository.id}&page=1&itemsPerPage=100`;
return this.http.get(url).subscribe(
(response: any) => {
this.gitRepositories = response['hydra:member'];
this.loadingGitRepositories = false;
},
(error) => {
console.error('Error al cargar los repositorios git:', error);
this.loadingGitRepositories = false;
}
);
}
loadGitImageRepositories(gitRepository: any) {
this.loadingGitImageRepositories = true;
const url = `${this.baseUrl}/git-image-repositories?gitRepository.id=${gitRepository.id}&page=1&itemsPerPage=100`;
this.http.get(url).subscribe(
(response: any) => {
this.gitImageRepositories = response['hydra:member'];
this.loadingGitImageRepositories = false;
},
(error) => {
console.error('Error al cargar las imágenes de repositorio git:', error);
this.loadingGitImageRepositories = false;
}
);
}
onGitRepositorySelected(gitRepository: any) {
this.selectedGitRepository = gitRepository;
this.selectedExistingImage = null;
this.existingImages = [];
if (gitRepository) {
this.loadGitImageRepositories(gitRepository);
} else {
this.gitImageRepositories = [];
}
}
onGitActionSelected(event: any) {
console.log('onGitActionSelected llamado con:', event);
this.gitAction = event.value;
this.selectedExistingImage = null;
this.gitImageName = '';
// Si se selecciona 'update' y ya hay un repositorio Git seleccionado, cargar los repositorios de imágenes
if (event.value === 'update' && this.selectedGitRepository) {
this.loadGitImageRepositories(this.selectedGitRepository);
}
console.log('Antes del setTimeout');
// Hacer scroll hacia la sección de partición después de un delay más largo
setTimeout(() => {
console.log('Dentro del setTimeout, llamando a scrollToPartitionSection');
this.scrollToPartitionSection();
}, 300);
}
onMonolithicActionSelected(event: any) {
console.log('onMonolithicActionSelected llamado con:', event);
this.monolithicAction = event.value;
this.selectedImage = null;
this.name = '';
// Si se selecciona 'update', cargar las imágenes existentes
if (event.value === 'update') {
this.loadImages();
}
console.log('Antes del setTimeout (monolithic)');
// Hacer scroll hacia la sección de partición después de un delay más largo
setTimeout(() => {
console.log('Dentro del setTimeout (monolithic), llamando a scrollToPartitionSection');
this.scrollToPartitionSection();
}, 300);
}
loadExistingImages() {
if (!this.selectedExistingImage) return;
this.loadingExistingImages = true;
// Aquí deberías hacer el GET al endpoint externo
// Por ahora uso un endpoint de ejemplo, ajusta según tu API
const url = `${this.baseUrl}/images?gitImageRepository.id=${this.selectedExistingImage.id}&page=1&itemsPerPage=100`;
this.http.get(url).subscribe(
(response: any) => {
this.existingImages = response['hydra:member'] || [];
this.loadingExistingImages = false;
},
(error) => {
console.error('Error al cargar las imágenes existentes:', error);
this.loadingExistingImages = false;
this.toastService.error('Error al cargar las imágenes existentes');
}
);
}
resetGitSelections() {
this.selectedGitRepository = null;
this.selectedExistingImage = null;
this.gitImageName = '';
this.gitAction = 'create';
this.existingImages = [];
this.gitRepositories = [];
this.gitImageRepositories = [];
this.selectedImage = null;
this.name = '';
this.monolithicAction = 'create';
}
resetCanonicalName() {
this.name = this.selectedImage ? this.selectedImage.name : '';
}
save(): void {
this.loading = true;
if (!this.selectedPartition) {
this.toastService.error('Debes seleccionar una partición');
this.loading = false;
return;
}
if (this.imageType === 'git') {
if (!this.selectedGitRepository) {
this.toastService.error('Debes seleccionar un repositorio Git');
return;
}
if (this.gitAction === 'update' && !this.selectedExistingImage) {
this.toastService.error('Debes seleccionar un repositorio de imágenes Git');
return;
}
}
if (this.imageType === 'monolithic') {
if (this.monolithicAction === 'create' && !this.name) {
this.toastService.error('Debes introducir un nombre canónico para la imagen');
return;
}
if (this.monolithicAction === 'update' && !this.selectedImage) {
this.toastService.error('Debes seleccionar una imagen para actualizar');
return;
}
}
if (this.selectedImage) {
this.toastService.warning('Aviso: Está seleccionando una imagen previamente creada. Se procede a crear un backup de la misma. ');
}
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop'
});
const payload = {
client: `/clients/${this.clientId}`,
name: this.name,
partition: this.selectedPartition['@id'],
source: 'assistant',
selectedImage: this.selectedImage?.['@id']
};
dialogRef.afterClosed().subscribe(result => {
if (result !== undefined) {
this.loading = true;
let payload: any = {
client: `/clients/${this.clientId}`,
partition: this.selectedPartition['@id'],
source: 'assistant',
type: this.imageType,
queue: result
};
if (this.imageType === 'git') {
payload.gitRepository = this.selectedGitRepository.name
payload.name = this.selectedGitRepository.name;
if (this.gitAction === 'create') {
payload.action = 'create';
} else {
payload.action = 'update';
}
} else {
if (this.monolithicAction === 'create') {
payload.name = this.name;
payload.action = 'create';
} else {
payload.selectedImage = this.selectedImage['@id'];
payload.action = 'update';
}
this.http.post(`${this.baseUrl}/images`, payload)
.subscribe({
next: (response) => {
this.toastService.success('Petición de creación de imagen enviada');
this.loading = false;
this.router.navigate(['/commands-logs']);
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
this.loading = false;
}
this.http.post(`${this.baseUrl}/images`, payload)
.subscribe({
next: (response) => {
let actionText = 'creación';
if (this.imageType === 'git' && this.gitAction === 'update') {
actionText = 'actualización';
} else if (this.imageType === 'monolithic' && this.monolithicAction === 'update') {
actionText = 'actualización';
}
this.toastService.success(`Petición de ${actionText} de imagen enviada`);
this.loading = false;
this.router.navigate(['/commands-logs']);
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
this.loading = false;
}
});
}
});
}
openCreateRepositoryModal(): void {
this.creatingRepository = true;
const dialogRef = this.dialog.open(CreateRepositoryModalComponent, {
width: '600px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
data: {
clientRepository: this.selectedRepository
}
});
dialogRef.afterClosed().subscribe(result => {
this.creatingRepository = false;
if (result) {
this.loadGitRepositories();
setTimeout(() => {
const newRepository = this.gitRepositories.find(repo => repo['@id'] === result['@id']);
if (newRepository) {
this.selectedGitRepository = newRepository;
this.onGitRepositorySelected(newRepository);
}
}, 200);
}
});
}
get imageType(): string {
return this._imageType;
}
set imageType(value: string) {
this._imageType = value;
this.loadImages();
if (value === 'git') {
this.loadGitRepositories();
this.selectedImage = null;
this.name = '';
this.monolithicAction = 'create';
} else {
this.resetGitSelections();
}
}
onGitImageRepositorySelected(gitImageRepository: any) {
this.selectedExistingImage = gitImageRepository;
this.existingImages = [];
if (gitImageRepository) {
this.loadExistingImages();
}
}
scrollToPartitionSection() {
const partitionSection = document.getElementById('partition-selection');
if (partitionSection) {
partitionSection.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
}
get selectedPartition(): any {
return this._selectedPartition;
}
set selectedPartition(value: any) {
this._selectedPartition = value;
);
}
}

View File

@ -1,40 +0,0 @@
.dialog-content {
display: flex;
flex-direction: column;
padding: 40px;
}
.repository-form {
width: 100%;
display: flex;
flex-direction: column;
}
.form-field {
width: 100%;
margin-top: 16px;
}
.action-container {
display: flex;
justify-content: flex-end;
gap: 1em;
padding: 1.5em;
}
@media (max-width: 600px) {
.form-field {
width: 100%;
}
.dialog-actions {
flex-direction: column;
align-items: stretch;
}
button {
width: 100%;
margin-left: 0;
margin-bottom: 8px;
}
}

View File

@ -1,17 +0,0 @@
<app-loading [isLoading]="loading"></app-loading>
<h2 mat-dialog-title>Crear nuevo repositorio de imágenes git</h2>
<mat-dialog-content class="dialog-content">
<form [formGroup]="repositoryForm" (ngSubmit)="save()" class="repository-form">
<mat-form-field appearance="fill" class="form-field">
<mat-label>Nombre del repositorio</mat-label>
<input matInput formControlName="name" required>
</mat-form-field>
</form>
</mat-dialog-content>
<div mat-dialog-actions class="action-container">
<button class="ordinary-button" (click)="close()">Cancelar</button>
<button class="submit-button" (click)="save()">Guardar</button>
</div>

View File

@ -1,64 +0,0 @@
import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';
@Component({
selector: 'app-create-repository-modal',
templateUrl: './create-repository-modal.component.html',
styleUrl: './create-repository-modal.component.css'
})
export class CreateRepositoryModalComponent implements OnInit {
baseUrl: string;
repositoryForm: FormGroup<any>;
loading: boolean = false;
clientRepository: any = null;
constructor(
private fb: FormBuilder,
private http: HttpClient,
public dialogRef: MatDialogRef<CreateRepositoryModalComponent>,
private toastService: ToastrService,
private configService: ConfigService,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.baseUrl = this.configService.apiUrl;
this.clientRepository = this.data?.clientRepository || null;
this.repositoryForm = this.fb.group({
name: [null, Validators.required],
});
}
ngOnInit() {
// El componente se inicializa
}
save(): void {
if (this.repositoryForm.valid) {
this.loading = true;
const payload = {
name: this.repositoryForm.value.name,
repository: this.clientRepository ? this.clientRepository.id : null
};
this.http.post(`${this.baseUrl}/git-repositories`, payload).subscribe({
next: (response) => {
this.toastService.success('Repositorio creado correctamente');
this.dialogRef.close(response);
},
error: (error) => {
this.toastService.error(error.error?.['hydra:description'] || 'Error al crear el repositorio');
this.loading = false;
}
});
} else {
this.toastService.error('Por favor, complete todos los campos requeridos');
}
}
close(): void {
this.dialogRef.close();
}
}

View File

@ -1,140 +1,101 @@
.header-container {
.divider {
margin: 20px 0;
}
table {
width: 100%;
margin-top: 50px;
background-color: #eaeff6;
}
.search-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
background: white;
border-radius: 12px;
margin-bottom: 20px;
width: 100%;
padding: 0 5px;
box-sizing: border-box;
}
.header-container-title {
flex-grow: 1;
text-align: left;
.option-container {
margin: 20px 0;
width: 100%;
}
.header-container-title h2 {
margin: 0 0 8px 0;
color: #333;
font-weight: 600;
}
.header-container-title h4 {
margin: 0;
font-size: 16px;
opacity: 0.9;
font-weight: 400;
}
.button-row {
.deploy-container {
display: flex;
padding-right: 1em;
gap: 12px;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 5px;
gap: 10px;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
cursor: pointer;
.options-container {
padding: 10px;
}
.action-button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.action-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Contenedor principal */
.select-container {
background: white !important;
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
/* Secciones del formulario */
.form-section {
background: white !important;
border-radius: 16px;
padding: 32px;
margin-bottom: 24px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid #bbdefb;
}
.form-section-title {
.input-group {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 24px;
font-size: 20px;
font-weight: 600;
color: #2c3e50;
padding-bottom: 16px;
border-bottom: 2px solid #f8f9fa;
}
.form-section-title mat-icon {
color: #667eea;
font-size: 24px;
width: 24px;
height: 24px;
}
/* Selectores */
.selector {
display: flex;
gap: 20px;
margin-bottom: 20px;
flex-wrap: wrap;
gap: 16px;
margin-top: 20px;
}
.half-width {
flex: 1;
mat-option .unit-name {
display: block;
}
.input-field {
flex: 1 1 calc(33.33% - 16px);
min-width: 250px;
}
.full-width {
width: 100%;
margin-bottom: 16px;
}
/* Campos de formulario */
mat-form-field {
width: 100%;
margin-bottom: 8px;
.search-string {
flex: 2;
padding: 5px;
}
::ng-deep .mat-form-field-appearance-fill .mat-form-field-flex {
background-color: #f8f9fa;
border-radius: 8px;
border: 1px solid #e9ecef;
transition: all 0.3s ease;
.search-boolean {
flex: 1;
padding: 5px;
}
::ng-deep .mat-form-field-appearance-fill.mat-focused .mat-form-field-flex {
background-color: white;
border-color: #2196f3;
box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
.paginator-container {
display: flex;
justify-content: end;
margin-bottom: 30px;
}
/* Grid de clientes */
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
margin-top: 20px;
gap: 8px;
}
.client-item {
@ -142,277 +103,74 @@ mat-form-field {
}
.client-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 12px;
padding: 8px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.client-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
border-color: #667eea;
::ng-deep .custom-tooltip {
white-space: pre-line !important;
max-width: 200px;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px;
border-radius: 4px;
}
.selected-client {
background: linear-gradient(135deg, #8fa1f0 0%, #9b7bc8 100%);
color: white;
border-color: #667eea;
}
.selected-client .client-name,
.selected-client .client-ip {
color: white;
}
.client-image {
width: 32px;
height: 32px;
margin-bottom: 8px;
background-color: #a0c2e5 !important; /* Azul */
color: white !important;
}
.client-details {
margin-bottom: 12px;
margin-top: 4px;
}
.client-name {
font-size: 12px;
font-size: 0.9em;
font-weight: 600;
color: #2c3e50;
margin-bottom: 2px;
display: block;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
font-size: 10px;
color: #6c757d;
display: block;
margin-bottom: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: 0.9em;
color: #666;
}
.header-container-title {
flex-grow: 1;
text-align: left;
padding-left: 1em;
}
.button-row {
display: flex;
padding-right: 1em;
}
/* Tabla de particiones */
.partition-table-container {
background: white !important;
border-radius: 12px;
padding: 24px;
margin-top: 20px;
}
table {
width: 100%;
background: white;
border-radius: 8px;
overflow: hidden;
}
::ng-deep .mat-table {
background: white;
}
::ng-deep .mat-header-cell {
background: white !important;
color: #2c3e50;
font-weight: 600;
padding: 16px;
}
::ng-deep .mat-cell {
padding: 16px;
color: #495057;
}
/* Opciones avanzadas */
.input-group {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-top: 20px;
}
.input-field {
width: 100%;
}
/* Mensajes de error */
.error-message {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
color: white;
padding: 16px 20px;
border-radius: 8px;
margin-top: 16px;
font-weight: 500;
box-shadow: 0 4px 16px rgba(255, 107, 107, 0.3);
}
/* Instrucciones */
.instructions-box {
margin-bottom: 20px;
}
.instructions-card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
::ng-deep .instructions-card .mat-card-title {
color: #2c3e50;
font-weight: 600;
padding: 20px 20px 0 20px;
}
::ng-deep .instructions-card .mat-card-content {
background-color: #eaeff6;
padding: 20px;
}
.instructions-card pre {
background: white !important;
padding: 16px;
border-radius: 8px;
border: 1px solid #e9ecef;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.5;
}
/* Tooltip personalizado */
::ng-deep .custom-tooltip {
background: rgba(0, 0, 0, 0.9) !important;
color: white !important;
padding: 12px !important;
border-radius: 8px !important;
font-size: 12px !important;
max-width: 250px !important;
white-space: pre-line !important;
}
/* Responsive */
@media (max-width: 768px) {
.header-container {
flex-direction: column;
gap: 16px;
align-items: stretch;
}
.button-row {
justify-content: center;
}
.selector {
flex-direction: column;
}
.half-width {
min-width: auto;
}
.clients-grid {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 8px;
}
.client-card {
padding: 8px;
}
.client-image {
width: 24px;
height: 24px;
margin-bottom: 6px;
}
.client-name {
font-size: 11px;
}
.client-ip {
font-size: 9px;
}
.input-group {
grid-template-columns: 1fr;
}
.select-container {
padding: 0 16px;
}
.form-section {
padding: 20px;
}
.destination-badge {
padding: 10px 14px;
border-radius: 10px;
}
.destination-icon {
font-size: 18px;
width: 18px;
height: 18px;
margin-right: 10px;
}
.destination-value {
max-width: 150px;
font-size: 13px;
}
.destination-label {
font-size: 10px;
}
}
/* Estilos para elementos específicos */
.unit-name {
font-weight: 500;
color: #2c3e50;
}
/* Eliminar sombra de la tabla */
.mat-elevation-z8 {
box-shadow: none !important;
}
/* Estilos para el expansion panel */
::ng-deep .mat-expansion-panel {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
border-radius: 12px !important;
margin-bottom: 20px;
background: #f7fbff !important;
border: 1px solid #bbdefb !important;
}
::ng-deep .mat-expansion-panel-header {
padding: 20px 24px !important;
border-radius: 12px !important;
}
::ng-deep .mat-expansion-panel-header-title {
font-weight: 600 !important;
color: #2c3e50 !important;
}
::ng-deep .mat-expansion-panel-header-description {
color: #6c757d !important;
}
/* Otros estilos */
.divider {
margin: 20px 0;
border-radius: 12px;
margin-top: 20px;
}
.disabled-client {
@ -420,103 +178,21 @@ table {
opacity: 0.5;
}
.error-message {
background-color: #de2323;
padding: 20px;
border-radius: 12px;
margin-top: 20px;
color: white;
font-weight: bold;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.instructions-textarea textarea {
font-family: monospace;
white-space: pre;
}
/* Estilo para hacer el backdrop no clickeable */
::ng-deep .non-clickable-backdrop {
pointer-events: none;
}
/* Estilos modernos para el badge de destino */
.destination-info {
margin-top: 12px;
}
.destination-badge {
display: inline-flex;
align-items: center;
background: #e3f2fd;
color: #1565c0;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #bbdefb;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
}
.destination-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #1976d2;
}
.destination-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.destination-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #1976d2;
line-height: 1;
}
.destination-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #0d47a1;
}
.filters-row {
display: flex;
gap: 20px;
align-items: flex-end;
margin-bottom: 20px;
}
.git-gap {
gap: 40px;
}
.monolithic-row {
display: flex;
gap: 24px;
align-items: flex-end;
margin-bottom: 20px;
}
.monolithic-row .half-width {
flex: 1 1 200px;
min-width: 200px;
}
.monolithic-row .full-width {
flex: 2;
}
@media (max-width: 768px) {
.monolithic-row .full-width {
flex: 2;
}
}

View File

@ -5,36 +5,12 @@
<h2>
{{ 'deployImage' | translate }}
</h2>
<div class="destination-info">
<div class="destination-badge">
<mat-icon class="destination-icon">cloud_download</mat-icon>
<div class="destination-content">
<span class="destination-label">Destino</span>
<span class="destination-value">{{ runScriptTitle }}</span>
</div>
</div>
</div>
</div>
<div class="button-row">
<button class="action-button" id="execute-button"
[disabled]="!isFormValid()"
(click)="save()">Ejecutar</button>
</div>
<div class="button-row">
<button class="action-button" (click)="generateOgInstructions()">
Generar instrucciones
</button>
</div>
<div class="button-row">
<button class="action-button" color="accent"
[disabled]="!isFormValid()"
(click)="openScheduleModal()">
Opciones de programación
</button>
<button class="action-button" [disabled]="!allSelected || !selectedModelClient || !selectedImage || !selectedMethod || !selectedPartition" (click)="save()">Ejecutar</button>
</div>
</div>
<mat-divider></mat-divider>
<div class="select-container">
<mat-expansion-panel>
@ -56,7 +32,7 @@
<div *ngFor="let client of clientData" class="client-item">
<div class="client-card"
(click)="client.status === 'og-live' && toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}"
[ngClass]="{'selected-client': client.selected, 'disabled-client': client.status !== 'og-live'}"
[matTooltip]="getPartitionsTooltip(client)"
matTooltipPosition="above"
matTooltipClass="custom-tooltip">
@ -91,183 +67,72 @@
<mat-divider style="margin-top: 20px;"></mat-divider>
<div class="select-container">
<!-- Sección: Configuración de imagen -->
<div class="form-section">
<div class="form-section-title">
<mat-icon>image</mat-icon>
Configuración de imagen
</div>
<div class="selector">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Tipo de imagen</mat-label>
<mat-select [(ngModel)]="imageType" (selectionChange)="onImageTypeSelected($event.value)">
<mat-option [value]="'monolithic'">Monolítica</mat-option>
<mat-option [value]="'git'">Git</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="deploy-container">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccione imagen</mat-label>
<mat-select [(ngModel)]="selectedImage" name="selectedImage">
<mat-option *ngFor="let image of images" [value]="image">
<div class="unit-name"> {{ image.name }}</div>
<div style="font-size: smaller; color: gray;">{{ image.description }}</div>
</mat-option>
</mat-select>
</mat-form-field>
<!-- Selectores Git (solo si imageType === 'git') -->
<div *ngIf="imageType === 'git'" class="filters-row git-gap">
<mat-form-field appearance="fill" style="width: 300px;">
<mat-label>Seleccionar Repositorio</mat-label>
<mat-select [(ngModel)]="selectedGitRepository" (selectionChange)="onGitRepositoryChange($event.value)" [disabled]="loadingRepositories">
<mat-option *ngFor="let repo of repositories" [value]="repo">
{{ repo }}
</mat-option>
</mat-select>
<mat-icon matSuffix *ngIf="loadingRepositories">hourglass_empty</mat-icon>
</mat-form-field>
<mat-form-field appearance="fill" style="width: 300px;">
<mat-label>Seleccionar Rama</mat-label>
<mat-select [(ngModel)]="selectedBranch" (selectionChange)="onGitBranchChange()" [disabled]="loadingBranches || !selectedRepository">
<mat-option *ngFor="let branch of branches" [value]="branch">
{{ branch }}
</mat-option>
</mat-select>
<mat-icon matSuffix *ngIf="loadingBranches">hourglass_empty</mat-icon>
</mat-form-field>
</div>
<!-- Tabla de commits (solo si imageType === 'git') -->
<div *ngIf="imageType === 'git' && commits.length > 0" class="commits-table-container">
<table mat-table [dataSource]="commits" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>Seleccionar</th>
<td mat-cell *matCellDef="let commit">
<mat-radio-group [(ngModel)]="selectedCommit" name="selectedCommit">
<mat-radio-button [value]="commit"></mat-radio-button>
</mat-radio-group>
</td>
</ng-container>
<ng-container matColumnDef="hexsha">
<th mat-header-cell *matHeaderCellDef>Commit ID</th>
<td mat-cell *matCellDef="let commit">
<code style="background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px; font-family: monospace;">
{{ commit.hexsha }}
</code>
</td>
</ng-container>
<ng-container matColumnDef="message">
<th mat-header-cell *matHeaderCellDef>Mensaje</th>
<td mat-cell *matCellDef="let commit">{{ commit.message }}</td>
</ng-container>
<ng-container matColumnDef="committed_date">
<th mat-header-cell *matHeaderCellDef>Fecha</th>
<td mat-cell *matCellDef="let commit">{{ commit.committed_date * 1000 | date:'dd/MM/yyyy HH:mm:ss' }}</td>
</ng-container>
<ng-container matColumnDef="tags">
<th mat-header-cell *matHeaderCellDef>Tags</th>
<td mat-cell *matCellDef="let commit">
<mat-chip-list>
<mat-chip *ngFor="let tag of commit.tags" color="primary" selected>{{ tag }}</mat-chip>
<span *ngIf="!commit.tags || commit.tags.length === 0" style="color: #999; font-style: italic;">Sin tags</span>
</mat-chip-list>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['select','hexsha','message','committed_date','tags']"></tr>
<tr mat-row *matRowDef="let row; columns: ['select','hexsha','message','committed_date','tags'];"></tr>
</table>
</div>
<!-- Selector de método y de imagen solo si imageType === 'monolithic' -->
<div class="monolithic-row" *ngIf="imageType === 'monolithic'">
<mat-form-field appearance="fill" class="half-width">
<mat-label>Seleccione método de deploy</mat-label>
<mat-select [(ngModel)]="selectedMethod" name="selectedMethod" (selectionChange)="validateImageSize()">
<mat-option *ngFor="let method of allMethods" [value]="method.value">{{ method.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccione imagen</mat-label>
<mat-select [(ngModel)]="selectedImage" name="selectedImage" [disabled] = "!imageType" >
<mat-option *ngFor="let image of images" [value]="image">
<div class="unit-name"> {{ image.name }}</div>
<div style="font-size: smaller; color: gray;">{{ image.description }}</div>
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div *ngIf="errorMessage" class="error-message">
{{ errorMessage }}
</div>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccione método de deploy</mat-label>
<mat-select [(ngModel)]="selectedMethod" name="selectedMethod" (selectionChange)="validateImageSize()">
<mat-option *ngFor="let method of allMethods" [value]="method.value">{{ method.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<!-- Sección: Selección de partición -->
<div class="form-section" id="partition-selection">
<div class="form-section-title">
<mat-icon>storage</mat-icon>
Selección de partición
</div>
<div class="partition-table-container">
<div *ngIf="showInstructions" class="instructions-box">
<mat-card class="instructions-card">
<mat-card-title>
Instrucciones generadas
<button mat-icon-button (click)="showInstructions = false" style="float: right;">
<mat-icon>close</mat-icon>
</button>
</mat-card-title>
<mat-card-content>
<pre>{{ ogInstructions }}</pre>
</mat-card-content>
</mat-card>
</div>
<table mat-table [dataSource]="filteredPartitions">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef style="text-align: start">Seleccionar partición</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group [(ngModel)]="selectedPartition" name="selectedPartition">
<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 }} </th>
<td mat-cell *matCellDef="let image">
{{ column.cell(image) }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<div *ngIf="errorMessage" class="error-message">
{{ errorMessage }}
</div>
<!-- Sección: Opciones avanzadas -->
<div class="form-section" id="advanced-options" *ngIf="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct') || isMethod('p2p')">
<div class="form-section-title">
<mat-icon>settings</mat-icon>
<span *ngIf="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">Opciones multicast</span>
<span *ngIf="isMethod('p2p')">Opciones torrent</span>
</div>
<div class="input-group" *ngIf="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<div class="partition-table-container">
<table mat-table [dataSource]="filteredPartitions" class="mat-elevation-z8">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef style="text-align: start">Seleccionar partición</th>
<td mat-cell *matCellDef="let row">
<mat-radio-group [(ngModel)]="selectedPartition" name="selectedPartition" (change)="validateImageSize()">
<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 }} </th>
<td mat-cell *matCellDef="let image">
{{ column.cell(image) }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<mat-divider></mat-divider>
<div class="options-container">
<h3 *ngIf="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')" class="input-group">Opciones multicast</h3>
<h3 *ngIf="isMethod('p2p')" class="input-group">Opciones torrent</h3>
<div *ngIf="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')" class="input-group">
<mat-form-field appearance="fill" class="input-field">
<mat-label>Puerto</mat-label>
<input matInput [(ngModel)]="mcastPort" name="mcastPort" type="number"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<input matInput [(ngModel)]="mcastPort" name="mcastPort" type="number">
</mat-form-field>
<mat-form-field appearance="fill" class="input-field">
<mat-label>Dirección</mat-label>
<input matInput [(ngModel)]="mcastIp" name="mcastIp"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<input matInput [(ngModel)]="mcastIp" name="mcastIp">
</mat-form-field>
<mat-form-field appearance="fill" class="input-field">
<mat-label i18n="@@mcastModeLabel">Modo Multicast</mat-label>
<mat-select [(ngModel)]="mcastMode" name="mcastMode"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<mat-option *ngFor="let option of multicastModeOptions" [value]="option.value">
<mat-select [(ngModel)]="mcastMode" name="mcastMode">
<mat-option *ngFor="let option of multicastModeOptions" [value]="option.value">
{{ option.name }}
</mat-option>
</mat-select>
@ -275,50 +140,37 @@
<mat-form-field appearance="fill" class="input-field">
<mat-label>Velocidad</mat-label>
<input matInput [(ngModel)]="mcastSpeed" name="mcastSpeed" type="number"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<input matInput [(ngModel)]="mcastSpeed" name="mcastSpeed" type="number">
</mat-form-field>
<mat-form-field appearance="fill" class="input-field">
<mat-label>Máximo Clientes</mat-label>
<input matInput [(ngModel)]="mcastMaxClients" name="mcastMaxClients" type="number"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<input matInput [(ngModel)]="mcastMaxClients" name="mcastMaxClients" type="number">
</mat-form-field>
<mat-form-field appearance="fill" class="input-field">
<mat-label>Tiempo Máximo de Espera</mat-label>
<input matInput [(ngModel)]="mcastMaxTime" name="mcastMaxTime" type="number"
[required]="isMethod('udpcast') || isMethod('uftp') || isMethod('udpcast-direct')">
<input matInput [(ngModel)]="mcastMaxTime" name="mcastMaxTime" type="number">
</mat-form-field>
</div>
<div class="input-group" *ngIf="isMethod('p2p')">
<div *ngIf="isMethod('p2p')" class="input-group">
<mat-form-field appearance="fill" class="input-field">
<mat-label i18n="@@p2pModeLabel">Modo P2P</mat-label>
<mat-select [(ngModel)]="p2pMode" name="p2pMode"
[required]="isMethod('p2p')">
<mat-option *ngFor="let option of p2pModeOptions" [value]="option.value">
<mat-select [(ngModel)]="p2pMode" name="p2pMode">
<mat-option *ngFor="let option of p2pModeOptions" [value]="option.value">
{{ option.name }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill" class="input-field" *ngIf="p2pMode === 'seeder'">
<mat-label>Semilla (minutos)</mat-label>
<input matInput [(ngModel)]="p2pTime" name="p2pTime" type="number"
[required]="isMethod('p2p') && p2pMode === 'seeder'">
<mat-form-field appearance="fill" class="input-field">
<mat-label>Semilla</mat-label>
<input matInput [(ngModel)]="p2pTime" name="p2pTime" type="number">
</mat-form-field>
</div>
</div>
</div>
<app-scroll-to-top
[threshold]="100"
targetElement=".header-container"
position="bottom-right"
[showTooltip]="true"
tooltipText="Volver arriba"
tooltipPosition="left">
</app-scroll-to-top>

View File

@ -15,12 +15,10 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateModule } from '@ngx-translate/core';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import { ActivatedRoute, provideRouter } from '@angular/router';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { MatSelectModule } from '@angular/material/select';
import { MatExpansionModule } from "@angular/material/expansion";
import { MatIconModule } from "@angular/material/icon";
import { MatTooltipModule } from "@angular/material/tooltip";
import { LoadingComponent } from "../../../../../shared/loading/loading.component";
import { ScrollToTopComponent } from "../../../../../shared/scroll-to-top/scroll-to-top.component";
import { ConfigService } from '@services/config.service';
describe('DeployImageComponent', () => {
@ -34,7 +32,7 @@ describe('DeployImageComponent', () => {
};
await TestBed.configureTestingModule({
declarations: [DeployImageComponent, LoadingComponent, ScrollToTopComponent],
declarations: [DeployImageComponent, LoadingComponent],
imports: [
ReactiveFormsModule,
FormsModule,
@ -48,8 +46,6 @@ describe('DeployImageComponent', () => {
MatDividerModule,
MatRadioModule,
MatSelectModule,
MatIconModule,
MatTooltipModule,
BrowserAnimationsModule,
ToastrModule.forRoot(),
TranslateModule.forRoot()
@ -77,7 +73,8 @@ describe('DeployImageComponent', () => {
}
},
{ provide: ConfigService, useValue: mockConfigService }
]
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();

View File

@ -1,20 +1,17 @@
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import { Component, EventEmitter, Output } from '@angular/core';
import { MatTableDataSource } from "@angular/material/table";
import { SelectionModel } from "@angular/cdk/collections";
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ActivatedRoute, Router } from "@angular/router";
import { ConfigService } from '@services/config.service';
import {CreateTaskComponent} from "../../../../commands/commands-task/create-task/create-task.component";
import {MatDialog} from "@angular/material/dialog";
import {QueueConfirmationModalComponent} from "../../../../../shared/queue-confirmation-modal/queue-confirmation-modal.component";
@Component({
selector: 'app-deploy-image',
templateUrl: './deploy-image.component.html',
styleUrl: './deploy-image.component.css'
})
export class DeployImageComponent implements OnInit{
export class DeployImageComponent {
baseUrl: string;
@Output() dataChange = new EventEmitter<any>();
@ -24,7 +21,7 @@ export class DeployImageComponent implements OnInit{
images: any[] = [];
selectedImage: any = null;
selectedMethod: string | null = null;
private _selectedPartition: any = null;
selectedPartition: any = null;
mcastIp: string = '';
mcastPort: Number = 0;
mcastMode: string = '';
@ -37,12 +34,6 @@ export class DeployImageComponent implements OnInit{
clientData: any = [];
loading: boolean = false;
allSelected = true;
runScriptContext: any = null;
ogInstructions: string = '';
deployImage: boolean = true;
showInstructions: boolean = false;
loadingCommits: boolean = false;
selectedGitRepository: string = '';
protected p2pModeOptions = [
{ name: 'Leecher', value: 'leecher' },
@ -58,7 +49,6 @@ export class DeployImageComponent implements OnInit{
selectedModelClient: any = null;
filteredPartitions: any[] = [];
selectedRepository: any = null;
imageType: string = 'monolithic';
allMethods = [
{ name: 'Multicast', value: 'udpcast' },
@ -100,77 +90,38 @@ export class DeployImageComponent implements OnInit{
displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
selection = new SelectionModel(true, []);
repositories: string[] = [];
loadingRepositories: boolean = false;
branches: string[] = [];
selectedBranch: string = '';
loadingBranches: boolean = false;
commits: any[] = [];
selectedCommit: any = null;
private initialGitLoad = true;
constructor(
private http: HttpClient,
private toastService: ToastrService,
private configService: ConfigService,
private router: Router,
private route: ActivatedRoute,
private dialog: MatDialog,
private route: ActivatedRoute
) {
this.baseUrl = this.configService.apiUrl;
this.route.queryParams.subscribe(params => {
if (params['clientData']) {
this.clientData = JSON.parse(params['clientData']);
}
if (params['runScriptContext']) {
this.runScriptContext = params['runScriptContext'];
}
});
this.clientId = this.clientData?.length ? this.clientData[0]['@id'] : null;
this.clientData.forEach((client: { selected: boolean; status: string}) => { client.selected = true; });
this.clientData.forEach((client: { selected: boolean; status: string}) => {
if (client.status === 'og-live') {
client.selected = true;
}
});
this.selectedClients = this.clientData.filter(
(client: { status: string }) => client.status === 'og-live'
);
this.selectedClients = this.clientData.filter((client: { selected: boolean; status: string}) => client.selected);
this.selectedModelClient = this.clientData.find((client: { selected: boolean; status: string}) => client.selected) || null;
this.selectedModelClient = this.clientData.find(
(client: { status: string }) => client.status === 'og-live'
) || null;
if (this.selectedModelClient) {
this.loadPartitions(this.selectedModelClient);
}
}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.runScriptContext = params['runScriptContext'] ? JSON.parse(params['runScriptContext']) : null;
});
}
onImageTypeSelected(event: any) {
this.imageType = event;
if (event === 'git') {
this.selectedMethod = null;
this.loadGitRepositories();
}
this.loadImages();
setTimeout(() => {
this.scrollToPartitionSection();
}, 200);
}
get runScriptTitle(): string {
const ctx = this.runScriptContext;
if (!ctx) {
return '';
}
if (Array.isArray(ctx)) {
return ctx.map(c => c.name).join(', ');
}
if (typeof ctx === 'object' && 'name' in ctx) {
return ctx.name;
}
return String(ctx);
}
isMethod(method: string): boolean {
return this.selectedMethod === method;
}
@ -223,7 +174,7 @@ export class DeployImageComponent implements OnInit{
this.loadImages();
},
(error) => {
console.error('Error al cargar las particiones:', error);
console.error('Error al cargar los datos completos del cliente:', error);
}
);
} else {
@ -235,7 +186,11 @@ export class DeployImageComponent implements OnInit{
toggleSelectAll() {
this.allSelected = !this.allSelected;
this.clientData.forEach((client: { selected: boolean; status: string }) => { client.selected = this.allSelected; });
this.clientData.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected;
}
});
}
loadImages() {
@ -246,13 +201,7 @@ export class DeployImageComponent implements OnInit{
return;
}
let url = ''
if (this.imageType === 'monolithic') {
url = `${this.baseUrl}/image-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;
} else {
url = `${this.baseUrl}/git-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;
}
const url = `${this.baseUrl}/image-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;
this.http.get(url).subscribe(
(response: any) => {
@ -273,296 +222,73 @@ export class DeployImageComponent implements OnInit{
}
}
this.errorMessage = "";
if (this.selectedMethod) {
setTimeout(() => {
this.scrollToPartitionSection();
}, 300);
}
return true;
}
save(): void {
this.loading = true;
if (!this.selectedClients.length) {
this.toastService.error('Debe seleccionar al menos un cliente');
this.loading = false;
return;
}
if (!this.selectedImage && this.imageType !== 'git') {
if (!this.selectedImage) {
this.toastService.error('Debe seleccionar una imagen');
this.loading = false;
return;
}
if (!this.selectedMethod && this.imageType !== 'git') {
if (!this.selectedMethod) {
this.toastService.error('Debe seleccionar un método');
this.loading = false;
return;
}
if (!this.selectedPartition) {
this.toastService.error('Debe seleccionar una partición');
this.loading = false;
return;
}
if (this.imageType === 'git' && !this.selectedCommit) {
this.toastService.error('Debe seleccionar un commit');
return;
}
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop'
});
this.toastService.info('Preparando petición de despliegue');
dialogRef.afterClosed().subscribe(result => {
if (result !== undefined) {
this.loading = true;
let payload: any;
let url: string;
const payload = {
clients: this.selectedClients.map((client: any) => client.uuid),
method: this.selectedMethod,
// partition: this.selectedPartition['@id'],
diskNumber: this.selectedPartition.diskNumber,
partitionNumber: this.selectedPartition.partitionNumber,
p2pMode: this.p2pMode,
p2pTime: this.p2pTime,
mcastIp: this.mcastIp,
mcastPort: this.mcastPort,
mcastMode: this.mcastMode,
mcastSpeed: this.mcastSpeed,
maxTime: this.mcastMaxTime,
maxClients: this.mcastMaxClients,
};
if (this.imageType === 'git') {
payload = {
type: 'git',
clients: this.selectedClients.map((client: any) => client.uuid),
diskNumber: this.selectedPartition.diskNumber,
partitionNumber: this.selectedPartition.partitionNumber,
repositoryName: this.selectedGitRepository,
branch: this.selectedBranch,
hexsha: this.selectedCommit.hexsha,
queue: result
};
url = `${this.baseUrl}/git-repositories/deploy-image`;
} else {
payload = {
clients: this.selectedClients.map((client: any) => client.uuid),
method: this.selectedMethod,
diskNumber: this.selectedPartition.diskNumber,
partitionNumber: this.selectedPartition.partitionNumber,
p2pMode: this.p2pMode,
p2pTime: this.p2pMode === 'seeder' ? this.p2pTime : 0,
mcastIp: this.mcastIp,
mcastPort: this.mcastPort,
mcastMode: this.mcastMode,
mcastSpeed: this.mcastSpeed,
maxTime: this.mcastMaxTime,
maxClients: this.mcastMaxClients,
type: this.imageType,
queue: result
};
url = `${this.baseUrl}/image-image-repositories/${this.selectedImage.uuid}/deploy-image`;
}
this.http.post(url, payload)
.subscribe({
next: (response) => {
this.toastService.success('Petición de despliegue enviada correctamente');
this.loading = false;
this.router.navigate(['/commands-logs']);
},
error: (error) => {
this.toastService.error(error.error['hydra:description'], 'Se ha detectado un error en el despliegue de imágenes.', {
"closeButton": true,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-bottom-right",
"timeOut": 0,
"extendedTimeOut": 0,
"tapToDismiss": false
});
this.loading = false;
}
this.http.post(`${this.baseUrl}/image-image-repositories/${this.selectedImage.uuid}/deploy-image`, payload)
.subscribe({
next: (response) => {
this.toastService.success('Petición de despliegue enviada correctamente');
this.loading = false;
this.router.navigate(['/commands-logs']);
},
error: (error) => {
this.toastService.error(error.error['hydra:description'], 'Se ha detectado un error en el despliegue de imágenes.', {
"closeButton": true,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-bottom-right",
"timeOut": 0,
"extendedTimeOut": 0,
"tapToDismiss": false
});
}
});
}
isFormValid(): boolean {
if (!this.allSelected || !this.selectedModelClient || !this.selectedPartition) {
return false;
}
if (this.imageType === 'git') {
if (!this.selectedCommit) {
return false;
}
}
if (this.imageType !== 'git' && !this.selectedMethod) {
return false;
}
if (this.imageType !== 'git') {
if (this.isMethod('udpcast') || this.isMethod('uftp') || this.isMethod('udpcast-direct')) {
if (!this.mcastPort || !this.mcastIp || !this.mcastMode || !this.mcastSpeed || !this.mcastMaxClients || !this.mcastMaxTime) {
return false;
this.loading = false;
}
}
if (this.isMethod('p2p')) {
if (!this.p2pMode) {
return false;
}
if (this.p2pMode === 'seeder' && !this.p2pTime) {
return false;
}
}
}
return true;
}
openScheduleModal(): void {
const dialogRef = this.dialog.open(CreateTaskComponent, {
width: '800px',
data: {
scope: this.runScriptContext.type,
organizationalUnit: this.runScriptContext['@id'],
source: 'assistant'
}
});
dialogRef.afterClosed().subscribe((result: { [x: string]: any; }) => {
if (result) {
const payload = {
method: this.selectedMethod,
diskNumber: this.selectedPartition.diskNumber,
partitionNumber: this.selectedPartition.partitionNumber,
p2pMode: this.selectedMethod === 'p2p' ? this.p2pMode : null,
p2pTime: this.selectedMethod === 'p2p' && this.p2pMode === 'seeder' ? this.p2pTime : null,
mcastIp: this.selectedMethod === 'udpcast' ? this.mcastIp : null,
mcastPort: this.selectedMethod === 'udpcast' ? this.mcastPort : null,
mcastMode: this.selectedMethod === 'udpcast' ? this.mcastMode : null,
mcastSpeed: this.selectedMethod === 'udpcast' ? this.mcastSpeed : null,
maxTime: this.selectedMethod === 'udpcast' ? this.mcastMaxTime : null,
maxClients: this.selectedMethod === 'udpcast' ? this.mcastMaxClients : null,
};
this.http.post(`${this.baseUrl}/command-task-scripts`, {
commandTask: result['taskId'] ? result['taskId']['@id'] : result['@id'],
parameters: payload,
order: result['executionOrder'] || 1,
type: 'deploy-image',
}).subscribe({
next: () => {
this.toastService.success('Script añadido con éxito a la tarea');
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
}
})
}
});
}
generateOgInstructions() {
this.showInstructions = true;
this.ogInstructions = `og-deploy-image --image ${this.selectedImage.name} --partition ${this.selectedPartition.partitionNumber} --method ${this.selectedMethod}`;
}
scrollToPartitionSection() {
const partitionSection = document.getElementById('partition-selection');
if (partitionSection) {
partitionSection.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
console.log('Scroll ejecutado');
}
}
scrollToAdvancedOptions() {
const advancedOptions = document.getElementById('advanced-options');
if (advancedOptions) {
advancedOptions.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
console.log('Scroll hacia opciones avanzadas ejecutado');
}
}
get selectedPartition(): any {
return this._selectedPartition;
}
set selectedPartition(value: any) {
this._selectedPartition = value;
}
loadGitRepositories() {
this.loadingRepositories = true;
this.http.get<any>(`${this.baseUrl}/image-repositories/server/git/${this.selectedRepository?.uuid}/get-collection`).subscribe(
data => {
this.repositories = data.repositories || [];
this.loadingRepositories = false;
if (this.repositories.length > 0) {
this.selectedGitRepository = this.repositories[0];
this.loadGitBranches();
}
},
error => {
this.toastService.error('Error al cargar los repositorios git');
this.loadingRepositories = false;
}
);
}
onGitRepositoryChange(event: any) {
this.selectedGitRepository = event;
this.selectedBranch = '';
this.branches = [];
this.commits = [];
this.selectedCommit = null;
this.loadGitBranches();
}
loadGitBranches() {
if (!this.selectedGitRepository) return;
this.loadingBranches = true;
this.http.post<any>(`${this.baseUrl}/image-repositories/server/git/${this.selectedRepository?.uuid}/branches`, { repositoryName: this.selectedGitRepository }).subscribe(
data => {
this.branches = data.branches || [];
this.loadingBranches = false;
if (this.branches.length > 0) {
this.selectedBranch = this.branches[0];
this.loadGitCommits();
}
},
error => {
this.toastService.error('Error al cargar las ramas');
this.loadingBranches = false;
}
);
}
onGitBranchChange() {
this.selectedCommit = null;
this.commits = [];
this.loadGitCommits();
}
loadGitCommits() {
if (!this.selectedGitRepository || !this.selectedBranch) return;
this.loadingCommits = true;
this.http.post<any>(`${this.baseUrl}/image-repositories/server/git/${this.selectedRepository?.uuid}/commits`, {
repositoryName: this.selectedGitRepository,
branch: this.selectedBranch
}).subscribe(
data => {
this.commits = data.commits || [];
this.loadingCommits = false;
},
error => {
this.toastService.error('Error al cargar los commits');
this.loadingCommits = false;
}
);
}
}

View File

@ -1,420 +1,147 @@
/* ===== ESTILOS PRINCIPALES ===== */
.partition-assistant {
padding: 32px;
padding: 40px;
margin: 20px;
background: white !important;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid #bbdefb;
background-color: #eaeff6;
border-radius: 12px;
}
/* ===== HEADER ===== */
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
background: white;
border-radius: 12px;
margin-bottom: 20px;
}
.header-container-title {
flex-grow: 1;
text-align: left;
}
.header-container-title h2 {
margin: 0 0 8px 0;
color: #333;
font-weight: 600;
}
.header-container-title h4 {
margin: 0;
font-size: 16px;
opacity: 0.9;
font-weight: 400;
}
/* ===== DESTINATION BADGE ===== */
.destination-info {
margin-top: 12px;
}
.destination-badge {
display: inline-flex;
align-items: center;
background: #e3f2fd;
color: #1565c0;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #bbdefb;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
}
.destination-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #1976d2;
}
.destination-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.destination-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #1976d2;
line-height: 1;
}
.destination-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #0d47a1;
}
/* ===== BOTONES ===== */
.button-row {
display: flex;
gap: 12px;
align-items: center;
}
.action-button {
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
cursor: pointer;
margin-top: 10px;
margin-bottom: 10px;
margin-right: 16px;
}
.action-button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.action-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.row-button {
display: flex;
align-items: center;
gap: 30px;
}
/* ===== SELECTOR DE DISCO ===== */
.disk-selector-card {
padding: 32px;
margin: 20px;
background: white !important;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid #bbdefb;
overflow: hidden;
}
.card-header {
display: flex;
align-items: center;
padding: 24px 32px;
background: transparent;
color: #1976d2;
border-bottom: 1.5px solid #1976d2;
}
.card-icon {
font-size: 28px;
width: 28px;
height: 28px;
margin-right: 16px;
color: #1976d2;
}
.card-title h3 {
margin: 0 0 4px 0;
font-size: 20px;
font-weight: 600;
color: #1976d2;
}
.card-title p {
margin: 0;
font-size: 14px;
opacity: 0.9;
color: #1976d2;
}
.card-content {
padding: 24px 32px;
}
.disk-select-field {
width: 100%;
margin-bottom: 20px;
}
/* Opciones del select */
::ng-deep .disk-option {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 8px 0;
}
.disk-info {
display: flex;
flex-direction: column;
gap: 4px;
}
.disk-name {
font-weight: 600;
font-size: 16px;
color: #2c3e50;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.disk-size {
font-size: 14px;
color: #6c757d;
font-weight: 500;
}
.disk-details {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
}
.partitions-count {
font-size: 12px;
color: #667eea;
font-weight: 500;
background: rgba(102, 126, 234, 0.1);
padding: 2px 8px;
border-radius: 12px;
}
.usage-percent {
font-size: 12px;
color: #6c757d;
font-weight: 500;
}
/* Información de selección */
.selection-info {
display: flex;
align-items: center;
padding: 16px 20px;
background: #e8f5e8;
border: 1px solid #c8e6c9;
border-radius: 12px;
margin-top: 16px;
}
.info-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #388e3c;
}
.info-text {
display: flex;
flex-direction: column;
gap: 2px;
}
.info-title {
font-size: 14px;
font-size: 1rem;
font-weight: 600;
color: #2e7d32;
color: #555;
}
.info-subtitle {
font-size: 12px;
color: #388e3c;
}
/* Mensaje cuando no hay discos */
.no-disks-message {
display: flex;
align-items: center;
padding: 16px 20px;
background: #fff3e0;
border: 1px solid #ffcc02;
border-radius: 12px;
margin-top: 16px;
}
.warning-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #f57c00;
}
.message-text {
display: flex;
flex-direction: column;
gap: 2px;
}
.message-title {
font-size: 14px;
font-weight: 600;
color: #e65100;
}
.message-subtitle {
font-size: 12px;
color: #f57c00;
}
/* ===== INFO BADGES ===== */
.info-badge {
display: inline-flex;
align-items: center;
background: #e8f5e8;
color: #2e7d32;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #c8e6c9;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
margin: 0 8px;
}
.info-badge:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.info-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.info-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #388e3c;
line-height: 1;
}
.info-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #1b5e20;
}
/* Badge específico para firmware */
.info-badge:first-of-type {
background: #e3f2fd;
border-color: #bbdefb;
}
.info-badge:first-of-type .info-icon {
color: #1976d2;
}
.info-badge:first-of-type .info-label {
color: #1976d2;
}
.info-badge:first-of-type .info-value {
color: #0d47a1;
}
/* Badge específico para tabla de particiones */
.info-badge:last-of-type {
background: #fff3e0;
border-color: #ffcc02;
}
.info-badge:last-of-type .info-icon {
color: #f57c00;
}
.info-badge:last-of-type .info-label {
color: #f57c00;
}
.info-badge:last-of-type .info-value {
color: #e65100;
}
/* ===== SELECTOR DE CLIENTES ===== */
.select-container {
margin-top: 20px;
align-items: center;
.partition-table {
width: 100%;
box-sizing: border-box;
padding: 20px;
}
/* Expansion panel */
::ng-deep .mat-expansion-panel {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
border-radius: 12px !important;
border-collapse: collapse;
overflow: hidden;
margin-bottom: 20px;
background: #f7fbff !important;
border: 1px solid #bbdefb !important;
}
::ng-deep .mat-expansion-panel-header {
padding: 20px 24px !important;
border-radius: 12px !important;
.partition-table th {
color: #333;
padding: 12px;
font-weight: 600;
}
::ng-deep .mat-expansion-panel-header-title {
font-weight: 600 !important;
color: #2c3e50 !important;
.partition-table td {
padding: 10px;
text-align: center;
}
::ng-deep .mat-expansion-panel-header-description {
color: #6c757d !important;
.partition-table select,
.partition-table input[type="number"],
.partition-table input[type="checkbox"] {
padding: 5px;
width: 100%;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
.actions {
display: flex;
justify-content: flex-end;
padding-top: 10px;
}
button {
border: none;
padding: 10px 20px;
border-radius: 4px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s ease;
}
button.mat-button {
background-color: #007bff;
color: white;
}
button.mat-button:hover {
background-color: #0056b3;
}
button.mat-flat-button {
background-color: #28a745;
color: white;
}
button.mat-flat-button:hover {
background-color: #218838;
}
button.remove-btn {
background-color: #dc3545;
color: white;
border-radius: 4px;
}
button.remove-btn:hover {
background-color: #c82333;
}
.error-message {
color: #dc3545;
font-size: 0.9rem;
padding: 10px;
background-color: #f8d7da;
border-radius: 4px;
margin-top: 10px;
}
.partition-assistant .row {
display: flex;
flex-wrap: wrap;
margin-bottom: 20px;
}
.form-container {
flex: 0 0 65%;
max-width: 65%;
padding-right: 20px;
box-sizing: border-box;
}
.chart-container {
flex: 0 0 35%;
max-width: 35%;
}
.partition-bar {
display: flex;
height: 40px;
margin: 20px 0;
}
.partition-segment {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
font-size: 10px;
color: white;
height: 100%;
}
.chart-container ngx-charts-pie-chart {
display: block;
align-content: center;
justify-self: center;
}
.disk-select {
padding: 20px;
margin: 10px auto;
}
/* Grid de clientes */
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
@ -425,40 +152,6 @@
position: relative;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
}
.client-card:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
.selected-client {
background: linear-gradient(135deg, #8fa1f0 0%, #9b7bc8 100%);
color: white;
border-color: #667eea;
}
.selected-client .client-name,
.selected-client .client-ip {
color: white;
}
.client-image {
width: 40px;
height: 40px;
margin: 0 auto 8px;
}
.client-details {
margin-top: 4px;
}
@ -481,7 +174,37 @@
color: #666;
}
/* Tooltip personalizado */
.header-container-title {
flex-grow: 1;
text-align: left;
padding-left: 1em;
}
.select-container {
margin-top: 20px;
align-items: center;
width: 100%;
box-sizing: border-box;
padding-left: 1em;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
::ng-deep .custom-tooltip {
white-space: pre-line !important;
max-width: 200px;
@ -491,357 +214,36 @@
border-radius: 4px;
}
/* ===== LAYOUT PRINCIPAL ===== */
.row {
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.button-row {
display: flex;
flex-wrap: wrap;
margin-bottom: 20px;
padding-right: 1em;
}
.form-container {
flex: 0 0 65%;
max-width: 65%;
padding-right: 20px;
box-sizing: border-box;
background: white;
border-radius: 16px;
border: none;
.disabled-client {
pointer-events: none;
opacity: 0.5;
}
/* ===== INFORMACIÓN DEL DISCO ===== */
.disk-space-info-container {
margin: 24px 0;
background: none;
border-radius: 0;
border: none;
padding: 0;
}
.disk-space-card {
display: flex;
gap: 24px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.space-info-item {
.row-button {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
background: #f8f9fa;
border-radius: 12px;
border: 1px solid #e9ecef;
min-width: 180px;
gap: 30px;
}
.space-icon {
font-size: 24px;
width: 24px;
height: 24px;
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.used-icon {
color: #dc3545;
}
.free-icon {
color: #28a745;
}
.total-icon {
color: #007bff;
}
.space-details {
display: flex;
flex-direction: column;
gap: 4px;
}
.space-label {
font-size: 12px;
font-weight: 500;
color: #6c757d;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.space-value {
font-size: 16px;
font-weight: 600;
color: #212529;
}
/* Barra de uso del disco */
.disk-usage-bar {
margin-top: 16px;
}
.usage-bar-container {
width: 100%;
height: 12px;
background: #e9ecef;
border-radius: 6px;
overflow: hidden;
margin-bottom: 8px;
}
.usage-bar-fill {
height: 100%;
background: linear-gradient(90deg, #28a745, #20c997);
border-radius: 6px;
transition: width 0.3s ease;
}
.usage-percentage {
font-size: 14px;
font-weight: 600;
color: #666;
margin-top: 8px;
text-align: center;
}
/* ===== TABLA DE PARTICIONES ===== */
.partition-table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
.partition-table th {
background: white !important;
color: #495057;
padding: 16px 12px;
font-weight: 600;
text-align: left;
border-bottom: 2px solid #e9ecef;
font-size: 14px;
}
.partition-table th:nth-child(1), .partition-table td:nth-child(1) { width: 5%; }
.partition-table th:nth-child(2), .partition-table td:nth-child(2) { width: 20%; }
.partition-table th:nth-child(3), .partition-table td:nth-child(3) { width: 20%; }
.partition-table th:nth-child(4), .partition-table td:nth-child(4) { width: 15%; }
.partition-table th:nth-child(5), .partition-table td:nth-child(5) { width: 15%; }
.partition-table th:nth-child(6), .partition-table td:nth-child(6) { width: 5%; }
.partition-table th:nth-child(7), .partition-table td:nth-child(7) { width: 5%; }
.partition-table td {
padding: 6px 8px;
border-bottom: 1px solid #f1f3f4;
vertical-align: middle;
}
.partition-table select,
.partition-table input[type="number"],
.partition-table input[type="checkbox"] {
padding: 5px;
width: 100%;
}
.remove-btn {
background-color: #dc3545;
color: white !important;
border-radius: 4px !important;
border: none !important;
cursor: pointer !important;
border-radius: 4px !important;
padding: 7px 10px !important;
}
.remove-btn:hover {
background-color: #c82333;
}
/* ===== GRÁFICA ===== */
.chart-container {
flex: 0 0 35%;
max-width: 35%;
align-self: center;
justify-self: center;
}
.chart-header {
text-align: center;
margin-bottom: 20px;
}
.chart-header h3 {
margin: 0 0 8px 0;
color: #2c3e50;
font-weight: 600;
font-size: 18px;
}
.chart-header p {
margin: 0;
color: #6c757d;
font-size: 14px;
}
.chart-container ngx-charts-pie-chart {
width: 100% !important;
min-width: 0;
}
/* Forzar la leyenda debajo del gráfico */
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend {
position: relative !important;
top: auto !important;
left: auto !important;
right: auto !important;
bottom: auto !important;
display: block !important;
margin-top: 20px !important;
}
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend .legend-labels {
display: flex !important;
flex-direction: column !important;
align-items: center !important;
justify-content: center !important;
}
::ng-deep .chart-container ngx-charts-pie-chart .chart-legend .legend-label {
display: flex !important;
align-items: center !important;
margin: 5px 0 !important;
}
/* ===== ESTADOS DE ADVERTENCIA ===== */
/* Advertencia (90% a 99% usado) */
.warning {
color: #ff9800 !important;
}
.usage-bar-fill.warning {
background: linear-gradient(90deg, #ff9800, #ffb74d) !important;
}
.free-icon.warning {
color: #ff9800 !important;
}
/* Peligro (100% o más usado) */
.danger {
color: #f44336 !important;
font-weight: bold !important;
}
.usage-bar-fill.danger {
background: linear-gradient(90deg, #f44336, #ef5350) !important;
animation: pulse 2s infinite;
}
.free-icon.danger {
color: #f44336 !important;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.7;
}
100% {
opacity: 1;
}
}
/* ===== INSTRUCCIONES ===== */
.instructions-box {
margin-top: 15px;
background-color: #f5f5f5;
border: 1px solid #ccc;
padding: 15px;
border-radius: 6px;
}
.instructions-card {
background: #f5f5f5;
box-shadow: none !important;
margin-top: 20px;
border-radius: 16px;
border: none;
}
.instructions-card pre {
font-family: monospace;
white-space: pre;
background: #f8f9fa;
padding: 16px;
border-radius: 8px;
border: 1px solid #e9ecef;
overflow-x: auto;
font-size: 14px;
line-height: 1.5;
}
/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
.header-container {
flex-direction: column;
gap: 16px;
text-align: center;
}
.button-row {
flex-direction: column;
gap: 8px;
}
.destination-badge {
flex-direction: column;
text-align: center;
}
.destination-icon {
margin-right: 0;
margin-bottom: 8px;
}
.destination-value {
max-width: none;
}
.destination-label {
text-align: center;
}
.form-section {
padding: 20px;
}
.disk-space-card {
flex-direction: column;
gap: 12px;
}
.space-info-item {
min-width: auto;
}
.row {
flex-direction: column;
}
.chart-container {
flex: none;
width: 100%;
margin-top: 20px;
}
.partition-table {
font-size: 12px;
}
.partition-table th,
.partition-table td {
padding: 8px 4px;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}

View File

@ -2,33 +2,12 @@
<div class="header-container">
<div class="header-container-title">
<h2>
{{ 'partitionTitle' | translate }}
<h2 joyrideStep="groupsTitleStepText" text="{{ 'groupsTitleStepText' | translate }}">
Asistente de particionado
</h2>
<div class="destination-info">
<div class="destination-badge">
<mat-icon class="destination-icon">cloud_download</mat-icon>
<div class="destination-content">
<span class="destination-label">Destino</span>
<span class="destination-value">{{ runScriptTitle }}</span>
</div>
</div>
</div>
</div>
<div class="button-row">
<button class="action-button" [disabled]="data.status === 'busy' || !selectedModelClient || !allSelected || !selectedDisk || (selectedDisk.totalDiskSize - selectedDisk.used) <= 0" (click)="save()">Ejecutar</button>
</div>
<div class="button-row">
<button class="action-button" (click)="generateInstructions()">
Generar instrucciones
</button>
</div>
<div class="button-row">
<button class="action-button" color="accent" [disabled]="data.status === 'busy' || !selectedModelClient || !allSelected || !selectedDisk || (selectedDisk.totalDiskSize - selectedDisk.used) <= 0" (click)="openScheduleModal()">
Opciones de programación
</button>
<div class="subnets-button-row">
<button class="action-button" [disabled]="data.status === 'busy' || !selectedModelClient || !allSelected" (click)="save()">Ejecutar</button>
</div>
</div>
@ -52,7 +31,7 @@
<div *ngFor="let client of clientData" class="client-item">
<div class="client-card"
(click)="client.status === 'og-live' && toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}"
[ngClass]="{'selected-client': client.selected, 'disabled-client': client.status !== 'og-live'}"
[matTooltip]="getPartitionsTooltip(client)"
matTooltipPosition="above"
matTooltipClass="custom-tooltip">
@ -83,131 +62,31 @@
</mat-expansion-panel>
</div>
<mat-divider style="margin-top: 20px;"></mat-divider>
<mat-dialog-content>
<div class="disk-selector-card">
<div class="card-header">
<mat-icon class="card-icon">storage</mat-icon>
<div class="card-title">
<h3>Selección de Disco</h3>
<p>Elige el disco donde se realizarán las operaciones de particionado</p>
</div>
</div>
<div class="card-content">
<mat-form-field appearance="fill" class="disk-select-field">
<mat-label>Seleccionar disco</mat-label>
<mat-select [(ngModel)]="selectedDiskNumber" (selectionChange)="onDiskSelectionChange()">
<mat-option *ngFor="let disk of disks" [value]="disk.diskNumber">
<div class="disk-option">
<div class="disk-info">
<span class="disk-name">Disco {{ disk.diskNumber }}</span>
<span class="disk-size"> {{ (disk.totalDiskSize / 1024).toFixed(2) }} GB</span>
</div>
<div class="disk-details">
<span class="usage-percent"> {{ (disk.percentage || 0).toFixed(1) }}% usado</span>
</div>
</div>
</mat-option>
</mat-select>
<mat-hint>Selecciona el disco que deseas particionar</mat-hint>
</mat-form-field>
<div class="selection-info" *ngIf="selectedDisk">
<mat-icon class="info-icon">info</mat-icon>
<div class="info-text">
<span class="info-title">Disco seleccionado: {{ selectedDisk.diskNumber }}</span>
<span class="info-subtitle">Tamaño total: {{ (selectedDisk.totalDiskSize / 1024).toFixed(2) }} GB</span>
</div>
</div>
<div class="no-disks-message" *ngIf="!disks || disks.length === 0">
<mat-icon class="warning-icon">warning</mat-icon>
<div class="message-text">
<span class="message-title">No hay discos disponibles</span>
<span class="message-subtitle">Asegúrate de que el cliente modelo tenga discos configurados</span>
</div>
</div>
</div>
<div class="disk-select">
<mat-form-field appearance="fill">
<mat-label>Seleccionar disco</mat-label>
<mat-select [(ngModel)]="selectedDiskNumber">
<mat-option *ngFor="let disk of disks" [value]="disk.diskNumber">
Disco {{ disk.diskNumber }} ({{ (disk.totalDiskSize / 1024).toFixed(2) }} GB)
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="partition-assistant" *ngIf="selectedDisk">
<div *ngIf="showInstructions" class="instructions-box">
<mat-card class="instructions-card">
<mat-card-title>
Instrucciones generadas
<button mat-icon-button (click)="showInstructions = false" style="float: right;">
<mat-icon>close</mat-icon>
</button>
</mat-card-title>
<mat-card-content>
<pre>{{ generatedInstructions }}</pre>
</mat-card-content>
</mat-card>
</div>
<div class="row-button">
<button class="action-button" [disabled]="partitionCode === 'MSDOS'" (click)="addPartition(selectedDisk.diskNumber)">Añadir partición</button>
<div class="info-badge" *ngIf="selectedModelClient.firmwareType">
<mat-icon class="info-icon">memory</mat-icon>
<div class="info-content">
<span class="info-label">Firmware</span>
<span class="info-value">{{ selectedModelClient.firmwareType }}</span>
</div>
</div>
<div class="info-badge" *ngIf="partitionCode">
<mat-icon class="info-icon">storage</mat-icon>
<div class="info-content">
<span class="info-label">Tabla de particiones</span>
<span class="info-value">{{ partitionCode }}</span>
</div>
</div>
<button class="action-button" (click)="addPartition(selectedDisk.diskNumber)">Añadir partición</button>
<mat-chip *ngIf="selectedModelClient.firmwareType">
Tabla de particiones: {{ selectedModelClient.firmwareType }}
</mat-chip>
</div>
<mat-divider style="padding: 10px;"></mat-divider>
<div class="row">
<div class="form-container">
<div class="disk-space-info-container" id="disk-info">
<div class="disk-space-card">
<div class="space-info-item">
<mat-icon class="space-icon used-icon">storage</mat-icon>
<div class="space-details">
<span class="space-label">Espacio usado</span>
<span class="space-value">{{ selectedDisk.used | number:'1.2-2' }} MB</span>
</div>
</div>
<div class="space-info-item">
<mat-icon class="space-icon free-icon" [ngClass]="{'warning': (selectedDisk.used / selectedDisk.totalDiskSize) >= 0.9 && (selectedDisk.used / selectedDisk.totalDiskSize) < 1, 'danger': (selectedDisk.used / selectedDisk.totalDiskSize) >= 1}">cloud_done</mat-icon>
<div class="space-details">
<span class="space-label">Espacio libre</span>
<span class="space-value" [ngClass]="{'warning': (selectedDisk.used / selectedDisk.totalDiskSize) >= 0.9 && (selectedDisk.used / selectedDisk.totalDiskSize) < 1, 'danger': (selectedDisk.used / selectedDisk.totalDiskSize) >= 1}">{{ (selectedDisk.totalDiskSize - selectedDisk.used) | number:'1.2-2' }} MB</span>
</div>
</div>
<div class="space-info-item">
<mat-icon class="space-icon total-icon">dns</mat-icon>
<div class="space-details">
<span class="space-label">Espacio total</span>
<span class="space-value">{{ selectedDisk.totalDiskSize | number:'1.2-2' }} MB</span>
</div>
</div>
</div>
<div class="disk-usage-bar">
<div class="usage-bar-container">
<div class="usage-bar-fill"
[style.width.%]="(selectedDisk.used / selectedDisk.totalDiskSize) * 100"
[ngClass]="{'warning': (selectedDisk.used / selectedDisk.totalDiskSize) >= 0.9 && (selectedDisk.used / selectedDisk.totalDiskSize) < 1, 'danger': (selectedDisk.used / selectedDisk.totalDiskSize) >= 1}"></div>
</div>
<span class="usage-percentage" [ngClass]="{'warning': (selectedDisk.used / selectedDisk.totalDiskSize) >= 0.9 && (selectedDisk.used / selectedDisk.totalDiskSize) < 1, 'danger': (selectedDisk.used / selectedDisk.totalDiskSize) >= 1}">{{ ((selectedDisk.used / selectedDisk.totalDiskSize) * 100) | number:'1.1-1' }}% usado</span>
</div>
</div>
<table class="partition-table" id="partition-table">
<table class="partition-table">
<thead>
<tr>
<th>Partición</th>
@ -216,6 +95,7 @@
<th>Tamaño (MB)</th>
<th>Tamaño (%)</th>
<th>Formatear</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
@ -223,61 +103,43 @@
<tr *ngIf="!partition.removed">
<td>{{ partition.partitionNumber }}</td>
<td>
<select [(ngModel)]="partition.partitionCode" required [disabled]="partition.partitionNumber === 1 && partitionCode === 'GPT'">
<select [(ngModel)]="partition.partitionCode" required>
<option *ngFor="let type of partitionTypes" [value]="type.name">
{{ type.name }}
</option>
</select>
</td>
<td>
<select [(ngModel)]="partition.filesystem" required [disabled]="partition.partitionNumber === 1 && partitionCode === 'GPT'">
<select [(ngModel)]="partition.filesystem" required>
<option *ngFor="let type of filesystemTypes" [value]="type.name">
{{ type.name }}
</option>
</select>
</td>
<td>
<input [disabled]="partition.partitionNumber === 1 && partitionCode === 'GPT'" type="number" [(ngModel)]="partition.size" required
<input type="number" [(ngModel)]="partition.size" required
(input)="updatePartitionSize(selectedDisk.diskNumber, j, partition.size)" />
</td>
<td>
<input [disabled]="partition.partitionNumber === 1 && partitionCode === 'GPT'" type="number" [(ngModel)]="partition.percentage"
<input type="number" [(ngModel)]="partition.percentage"
(input)="updatePartitionSizeFromPercentage(selectedDisk.diskNumber, j, partition.percentage)" />
</td>
<td>
<mat-checkbox type="checkbox" [(ngModel)]="partition.format" />
<input type="checkbox" [(ngModel)]="partition.format" />
</td>
<td>
<button mat-button *ngIf="partitionCode !== 'MSDOS'" (click)="removePartition(selectedDisk.diskNumber, partition)" class="remove-btn">X</button>
<button (click)="removePartition(selectedDisk.diskNumber, partition)" class="remove-btn">X</button>
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<div class="chart-container" *ngIf="selectedDisk">
<div class="chart-header">
<h3>Distribución de Particiones</h3>
</div>
<ngx-charts-pie-chart
[results]="selectedDisk.chartData"
[doughnut]="true"
[gradient]="true"
[labels]="true"
[tooltipDisabled]="false"
[animations]="true">
<div class="chart-container">
<ngx-charts-pie-chart [view]="view" [results]="selectedDisk.chartData" [doughnut]="true">
</ngx-charts-pie-chart>
</div>
</div>
</div>
</mat-dialog-content>
<app-scroll-to-top
[threshold]="200"
targetElement=".header-container"
position="bottom-right"
[showTooltip]="true"
tooltipText="Volver arriba"
tooltipPosition="left">
</app-scroll-to-top>

View File

@ -5,9 +5,6 @@ import {ActivatedRoute, Router} from "@angular/router";
import { PARTITION_TYPES } from '../../../../../shared/constants/partition-types';
import { FILESYSTEM_TYPES } from '../../../../../shared/constants/filesystem-types';
import { ConfigService } from '@services/config.service';
import {CreateTaskComponent} from "../../../../commands/commands-task/create-task/create-task.component";
import {MatDialog} from "@angular/material/dialog";
import {QueueConfirmationModalComponent} from "../../../../../shared/queue-confirmation-modal/queue-confirmation-modal.component";
interface Partition {
uuid?: string;
@ -28,7 +25,7 @@ interface Partition {
templateUrl: './partition-assistant.component.html',
styleUrls: ['./partition-assistant.component.css']
})
export class PartitionAssistantComponent implements OnInit{
export class PartitionAssistantComponent {
baseUrl: string;
private apiUrl: string;
@Output() dataChange = new EventEmitter<any>();
@ -44,17 +41,13 @@ export class PartitionAssistantComponent implements OnInit{
disks: { diskNumber: number; totalDiskSize: number; partitions: Partition[]; chartData: any[]; used: number; percentage: number }[] = [];
clientData: any = [];
loading: boolean = false;
runScriptContext: any = null;
showInstructions = false;
view: [number, number] = [300, 200];
view: [number, number] = [400, 300];
showLegend = true;
showLabels = true;
allSelected = true;
selectedClients: any[] = [];
selectedModelClient: any = null;
partitionCode: string = '';
generatedInstructions: string = '';
constructor(
private http: HttpClient,
@ -62,7 +55,6 @@ export class PartitionAssistantComponent implements OnInit{
private route: ActivatedRoute,
private router: Router,
private configService: ConfigService,
private dialog: MatDialog,
) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = this.baseUrl + '/partitions';
@ -70,28 +62,27 @@ export class PartitionAssistantComponent implements OnInit{
if (params['clientData']) {
this.clientData = JSON.parse(params['clientData']);
}
if (params['runScriptContext']) {
this.runScriptContext = params['runScriptContext'];
});
this.clientId = this.clientData?.[0]['@id'];
this.clientData.forEach((client: { selected: boolean; status: string}) => {
if (client.status === 'og-live') {
client.selected = true;
}
});
this.clientId = this.clientData?.length ? this.clientData[0]['@id'] : null;
this.clientData.forEach((client: { selected: boolean; status: string}) => { client.selected = true; });
this.selectedClients = this.clientData.filter((client: { selected: boolean; status: string}) => client.selected);
this.selectedClients = this.clientData.filter(
(client: { status: string }) => client.status === 'og-live'
);
this.selectedModelClient = this.clientData.find((client: { selected: boolean; status: string}) => client.selected) || null;
this.selectedModelClient = this.clientData.find(
(client: { status: string }) => client.status === 'og-live'
) || null;
if (this.selectedModelClient) {
this.loadPartitions(this.selectedModelClient);
}
}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.runScriptContext = params['runScriptContext'] ? JSON.parse(params['runScriptContext']) : null;
});
}
get selectedDisk():any {
return this.disks.find(disk => disk.diskNumber === this.selectedDiskNumber) || null;
}
@ -104,7 +95,6 @@ export class PartitionAssistantComponent implements OnInit{
this.http.get(url).subscribe(
(response) => {
this.data = response;
this.partitionCode = this.data.partitions[0].partitionCode;
this.initializeDisks();
},
(error) => {
@ -113,34 +103,17 @@ export class PartitionAssistantComponent implements OnInit{
);
}
get runScriptTitle(): string {
const ctx = this.runScriptContext;
if (!ctx) {
return '';
}
if (Array.isArray(ctx)) {
return ctx.map(c => c.name).join(', ');
}
if (typeof ctx === 'object' && 'name' in ctx) {
return ctx.name;
}
return String(ctx);
}
toggleSelectAll() {
this.allSelected = !this.allSelected;
this.clientData.forEach((client: { selected: boolean; status: string }) => { client.selected = this.allSelected; });
this.clientData.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected;
}
});
}
initializeDisks() {
this.disks = [];
// Verificar que hay datos válidos
if (!this.data || !this.data.partitions || !Array.isArray(this.data.partitions)) {
console.warn('No hay datos de particiones válidos');
return;
}
const partitionsFromData = this.data.partitions;
this.originalPartitions = JSON.parse(JSON.stringify(partitionsFromData));
@ -158,11 +131,11 @@ export class PartitionAssistantComponent implements OnInit{
disk!.partitions.push({
uuid: partition.uuid,
partitionNumber: partition.partitionNumber,
size: this.convertBytesToGB(partition.partitionNumber === 1 && this.partitionCode === 'GPT' ? 512 : partition.size),
size: this.convertBytesToGB(partition.size),
memoryUsage: partition.memoryUsage,
partitionCode: partition.partitionNumber === 1 && this.partitionCode === 'GPT' ? 'EFI' : partition.partitionCode,
partitionCode: partition.partitionCode,
filesystem: partition.filesystem,
sizeBytes: partition.partitionNumber === 1 && this.partitionCode === 'GPT' ? 512 : partition.size,
sizeBytes: partition.size,
format: false,
color: '#1f1b91',
percentage: 0,
@ -259,6 +232,7 @@ export class PartitionAssistantComponent implements OnInit{
removedPartitions.length > 0 ? Math.max(...removedPartitions.map((p) => p.partitionNumber)) : 0;
const newPartitionNumber = maxPartitionNumber + 1;
disk.partitions.push({
partitionNumber: newPartitionNumber,
size: 0,
@ -302,77 +276,64 @@ export class PartitionAssistantComponent implements OnInit{
}
getRemainingGB(partitions: Partition[], totalDiskSize: number): number {
const totalUsedGB = partitions
.filter(partition => !partition.removed)
.reduce((acc, partition) => acc + partition.size, 0);
const totalUsedGB = partitions.reduce((acc, partition) => acc + partition.size, 0);
return Math.max(0, totalDiskSize - totalUsedGB);
}
save() {
if (!this.selectedDisk) {
this.toastService.error('No se ha seleccionado un disco.');
return;
}
const totalPartitionSize = this.selectedDisk.partitions
.filter((partition: any) => !partition.removed)
.reduce((sum: any, partition: any) => sum + partition.size, 0);
this.loading = true;
const totalPartitionSize = this.selectedDisk.partitions.reduce((sum: any, partition: { size: any; }) => sum + partition.size, 0);
if (totalPartitionSize > this.selectedDisk.totalDiskSize) {
this.toastService.error('El tamaño total de las particiones en el disco seleccionado excede el tamaño total del disco.');
this.loading = false;
return;
}
const modifiedPartitions = this.selectedDisk.partitions.filter((partition: { removed: any; format: any; }) => !partition.removed || partition.format);
if (modifiedPartitions.length === 0) {
this.loading = false;
this.toastService.info('No hay cambios para guardar en el disco seleccionado.');
return;
}
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop'
});
const newPartitions = modifiedPartitions.map((partition: { partitionNumber: any; memoryUsage: any; size: any; partitionCode: any; filesystem: any; uuid: any; removed: any; format: any; }) => ({
diskNumber: this.selectedDisk.diskNumber,
partitionNumber: partition.partitionNumber,
memoryUsage: partition.memoryUsage,
size: partition.size,
partitionCode: partition.partitionCode,
filesystem: partition.filesystem,
uuid: partition.uuid,
removed: partition.removed || false,
format: partition.format || false,
}));
dialogRef.afterClosed().subscribe(result => {
if (result !== undefined) {
this.loading = true;
const newPartitions = modifiedPartitions.map((partition: { partitionNumber: any; memoryUsage: any; size: any; partitionCode: any; filesystem: any; uuid: any; removed: any; format: any; }) => ({
diskNumber: this.selectedDisk.diskNumber,
partitionNumber: partition.partitionNumber,
memoryUsage: partition.memoryUsage,
size: partition.size,
partitionCode: partition.partitionCode,
filesystem: partition.filesystem,
uuid: partition.uuid,
removed: partition.removed || false,
format: partition.format || false,
}));
if (newPartitions.length > 0) {
const bulkPayload = {
partitions: newPartitions,
clients: this.selectedClients.map((client: any) => client.uuid),
};
const bulkPayload = {
partitions: newPartitions,
clients: this.selectedClients.map((client: any) => client.uuid),
queue: result
};
this.http.post(this.apiUrl, bulkPayload).subscribe(
(response) => {
this.toastService.success('Particiones creadas exitosamente para el disco seleccionado.');
this.loading = false;
this.router.navigate(['/commands-logs']);
},
(error) => {
this.loading = false;
this.toastService.error('Error al crear las particiones.');
}
);
}
});
this.http.post(this.apiUrl, bulkPayload).subscribe(
(response) => {
this.toastService.success('Particiones creadas exitosamente para el disco seleccionado.');
this.loading = false;
this.router.navigate(['/commands-logs']);
},
(error) => {
this.loading = false;
this.toastService.error('Error al crear las particiones.');
}
);
}
}
@ -383,10 +344,6 @@ export class PartitionAssistantComponent implements OnInit{
if (partitionToRemove) {
partitionToRemove.removed = true;
}
disk.used = this.calculateUsedSpace(disk.partitions);
disk.percentage = (disk.used / disk.totalDiskSize) * 100;
this.updateDiskChart(disk);
this.updatePartitionPercentages(disk.partitions, disk.totalDiskSize);
}
@ -405,135 +362,20 @@ export class PartitionAssistantComponent implements OnInit{
}
calculateUsedSpace(partitions: Partition[]): number {
return partitions
.filter(partition => !partition.removed)
.reduce((acc, partition) => acc + partition.size, 0);
return partitions.reduce((acc, partition) => acc + partition.size, 0);
}
generateChartData(partitions: Partition[]): any[] {
const colors = [
'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
'#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
'#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#D7BDE2'
];
return partitions
.filter(partition => !partition.removed)
.map((partition, index) => ({
name: `Partición ${partition.partitionNumber}`,
value: partition.size,
color: colors[index % colors.length],
partition: partition
}));
return partitions.map((partition) => ({
name: `Partición ${partition.partitionNumber}`,
value: partition.percentage,
color: partition.color
}));
}
updateDiskChart(disk: any) {
console.log('disk', disk);
disk.chartData = this.generateChartData(disk.partitions);
disk.used = this.calculateUsedSpace(disk.partitions);
disk.percentage = (disk.used / disk.totalDiskSize) * 100;
}
openScheduleModal(): void {
const dialogRef = this.dialog.open(CreateTaskComponent, {
width: '800px',
data: {
scope: this.runScriptContext.type,
organizationalUnit: this.runScriptContext['@id'],
source: 'assistant'
}
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
const modifiedPartitions = this.selectedDisk.partitions.filter((partition: { removed: any; format: any; }) => !partition.removed || partition.format);
if (modifiedPartitions.length === 0) {
this.loading = false;
this.toastService.info('No hay cambios para guardar en el disco seleccionado.');
return;
}
const newPartitions = modifiedPartitions.map((partition: { partitionNumber: any; memoryUsage: any; size: any; partitionCode: any; filesystem: any; uuid: any; removed: any; format: any; }) => ({
diskNumber: this.selectedDisk.diskNumber,
partitionNumber: partition.partitionNumber,
memoryUsage: partition.memoryUsage,
size: partition.size,
partitionCode: partition.partitionCode,
filesystem: partition.filesystem,
uuid: partition.uuid,
removed: partition.removed || false,
format: partition.format || false,
}));
const bulkPayload = {
partitions: newPartitions,
clients: this.selectedClients.map((client: any) => client.uuid),
};
this.http.post(`${this.baseUrl}/command-task-scripts`, {
commandTask: result['@id'],
parameters: bulkPayload.partitions,
order: 1,
type: 'partition-assistant',
}).subscribe({
next: () => {
this.toastService.success('Script añadido con éxito a la tarea');
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
}
})
}
});
}
generateInstructions(): void {
this.showInstructions = true;
this.generatedInstructions = `og-partition --disk ${this.selectedDiskNumber} --partitions ${this.selectedDisk.partitions.map((p: Partition) => `${p.partitionNumber}:${p.size}:${p.partitionCode}:${p.filesystem}:${p.format}`).join(',')}`;
}
onDiskSelected(diskNumber: number) {
this.selectedDiskNumber = diskNumber;
this.scrollToPartitionTable();
}
onDiskSelectionChange() {
if (this.selectedDiskNumber) {
this.scrollToPartitionTable();
}
}
scrollToPartitionTable() {
// Pequeño delay para asegurar que el contenido se haya renderizado
setTimeout(() => {
const diskInfo = document.getElementById('disk-info');
if (diskInfo) {
diskInfo.scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'nearest'
});
}
}, 100);
}
scrollToExecuteButton() {
console.log('scrollToExecuteButton llamado');
const executeButton = document.getElementById('execute-button');
console.log('Botón ejecutar encontrado:', executeButton);
if (executeButton) {
executeButton.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
console.log('Scroll hacia botón ejecutar completado');
} else {
console.error('No se encontró el botón execute-button');
}
}
}

View File

@ -1,3 +1,4 @@
.divider {
margin: 20px 0;
}
@ -101,287 +102,10 @@ table {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
background: white;
border-radius: 12px;
margin-bottom: 20px;
padding: 10px 10px;
border-bottom: 1px solid #ddd;
}
.header-container-title {
flex-grow: 1;
text-align: left;
}
.header-container-title h2 {
margin: 0 0 8px 0;
color: #333;
font-weight: 600;
}
.header-container-title h4 {
margin: 0;
font-size: 16px;
opacity: 0.9;
font-weight: 400;
}
.button-row {
display: flex;
padding-right: 1em;
gap: 12px;
align-items: center;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
cursor: pointer;
}
.action-button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.action-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.select-container {
background: white !important;
margin-top: 20px;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.form-section {
background: white !important;
border-radius: 16px;
padding: 20px !important;
margin-bottom: 24px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
border: 1px solid #bbdefb;
}
.form-section-title {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 24px;
font-size: 20px;
font-weight: 600;
color: #2c3e50;
padding-bottom: 16px;
border-bottom: 2px solid #f8f9fa;
}
.form-section-title mat-icon {
color: #667eea;
font-size: 24px;
width: 24px;
height: 24px;
}
/* Badges y chips */
.destination-badge {
display: inline-flex;
align-items: center;
background: #e3f2fd;
color: #1565c0;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #bbdefb;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
}
.destination-icon {
font-size: 20px;
width: 20px;
height: 20px;
margin-right: 12px;
color: #1976d2;
}
.destination-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.destination-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #1976d2;
line-height: 1;
}
.destination-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #0d47a1;
}
.info-badge {
display: inline-flex;
align-items: center;
background: #e8f5e8;
color: #2e7d32;
padding: 12px 16px;
border-radius: 12px;
border: 1px solid #c8e6c9;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
transition: all 0.2s ease;
margin: 0 8px;
}
.info-badge:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.info-content {
display: flex;
flex-direction: column;
gap: 2px;
}
.info-label {
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #388e3c;
line-height: 1;
}
.info-value {
font-size: 14px;
font-weight: 600;
line-height: 1.2;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #1b5e20;
}
/* Clientes y tarjetas */
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
margin-top: 20px;
}
.client-item {
position: relative;
}
.client-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
overflow: hidden;
position: relative;
padding: 12px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.client-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.client-image {
width: 32px;
height: 32px;
margin-bottom: 8px;
}
.client-details {
margin-bottom: 12px;
}
.client-name {
font-size: 12px;
font-weight: 600;
color: #2c3e50;
margin-bottom: 2px;
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.client-ip {
font-size: 10px;
color: #6c757d;
display: block;
margin-bottom: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.selected-client {
background: linear-gradient(135deg, #8fa1f0 0%, #9b7bc8 100%);
color: white;
border-color: #667eea;
}
.selected-client .client-name,
.selected-client .client-ip {
color: white;
}
::ng-deep .mat-expansion-panel {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
border-radius: 12px !important;
margin-bottom: 20px;
background: #f7fbff !important;
border: 1px solid #bbdefb !important;
}
::ng-deep .mat-expansion-panel-header {
padding: 20px 24px !important;
border-radius: 12px !important;
}
::ng-deep .mat-expansion-panel-header-title {
font-weight: 600 !important;
color: #2c3e50 !important;
}
::ng-deep .mat-expansion-panel-header-description {
color: #6c757d !important;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.mat-elevation-z8 {
box-shadow: 0px 0px 0px rgba(0,0,0,0.2);
}
@ -392,11 +116,117 @@ table {
margin-bottom: 30px;
}
.clients-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
}
.client-item {
position: relative;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
.client-details {
margin-top: 4px;
}
.client-name {
font-size: 0.9em;
font-weight: 600;
color: #333;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 150px;
display: inline-block;
}
.client-ip {
display: block;
font-size: 0.9em;
color: #666;
}
.header-container-title {
flex-grow: 1;
text-align: left;
padding-left: 1em;
}
.button-row {
display: flex;
padding-right: 1em;
}
.client-card {
background: #ffffff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
padding: 8px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
&:hover {
background-color: #f0f0f0;
transform: scale(1.02);
}
}
::ng-deep .custom-tooltip {
white-space: pre-line !important;
max-width: 200px;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px;
border-radius: 4px;
}
.selected-client {
background-color: #a0c2e5 !important;
color: white !important;
}
.button-row {
display: flex;
padding-right: 1em;
}
.disabled-client {
pointer-events: none;
opacity: 0.5;
}
.action-button {
margin-top: 10px;
margin-bottom: 10px;
}
.mat-expansion-panel-header-description {
justify-content: space-between;
align-items: center;
}
.new-command-container {
display: flex;
flex-direction: column;
@ -431,85 +261,4 @@ table {
width: 100%;
}
/* Secciones del formulario */
.form-section {
background: white !important;
border-radius: 8px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
border: 1px solid #bbdefb;
padding: 20px;
}
.form-section-title {
font-size: 18px;
font-weight: 600;
color: #333;
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 8px;
}
.form-section-title mat-icon {
color: #2196f3;
}
.toggle-options {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.selected-toggle {
background: linear-gradient(135deg, #8fa1f0 0%, #9b7bc8 100%) !important;
color: white !important;
}
mat-spinner {
margin: 20px auto;
display: block;
}
/* Estilo para hacer el backdrop no clickeable */
::ng-deep .non-clickable-backdrop {
pointer-events: none !important;
}
::ng-deep .action-chip {
margin: 8px !important;
padding: 12px 20px !important;
border-radius: px !important;
font-weight: 500 !important;
font-size: 14px !important;
transition: all 0.3s ease !important;
border: 2px solid transparent !important;
background: white !important;
color: #6c757d !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
cursor: pointer !important;
display: flex !important;
align-items: center !important;
gap: 8px !important;
min-height: 48px !important;
}
::ng-deep .action-chip:hover {
transform: translateY(-2px) !important;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15) !important;
}
::ng-deep .action-chip.mat-mdc-chip-selected {
border-color: #667eea !important;
box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2) !important;
}
::ng-deep .create-chip.mat-mdc-chip-selected {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
color: white !important;
}
::ng-deep .update-chip.mat-mdc-chip-selected {
background: linear-gradient(135deg, #007bff 0%, #0056b3 100%) !important;
color: white !important;
}

View File

@ -5,18 +5,9 @@
<h2>
{{ 'runScript' | translate }}
</h2>
<h4>
{{ runScriptTitle }}
</h4>
</div>
<div class="button-row">
<button class="action-button" [disabled]="selectedClients.length < 1 || (commandType === 'existing' && !selectedScript) || loading" (click)="save()">Ejecutar</button>
</div>
<div class="button-row">
<button color="accent" class="action-button" [disabled]="selectedClients.length < 1 || (commandType === 'existing' && !selectedScript) || loading" (click)="openScheduleModal()">
Opciones de programación
</button>
<button class="action-button" [disabled]="selectedClients.length < 1 || (commandType === 'existing' && !selectedScript)" (click)="save()">Ejecutar</button>
</div>
</div>
<mat-divider></mat-divider>
@ -40,8 +31,8 @@
<div class="clients-grid">
<div *ngFor="let client of clientData" class="client-item">
<div class="client-card"
(click)="toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected}"
(click)="client.status === 'og-live' && toggleClientSelection(client)"
[ngClass]="{'selected-client': client.selected, 'disabled-client': client.status !== 'og-live'}"
[matTooltip]="getPartitionsTooltip(client)"
matTooltipPosition="above"
matTooltipClass="custom-tooltip">
@ -62,69 +53,51 @@
</mat-expansion-panel>
</div>
<mat-divider style="margin-top: 20px;"></mat-divider>
<div class="select-container">
<div class="command-toggle">
<mat-radio-group [(ngModel)]="commandType">
<mat-radio-button value="new">Comando nuevo</mat-radio-button>
<mat-radio-button value="existing">Comando existente</mat-radio-button>
</mat-radio-group>
</div>
<div class="form-section">
<div class="form-section-title">
<mat-icon>code</mat-icon>
Configuración de script
<div *ngIf="commandType === 'new'" class="new-command-container">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Ingrese el script</mat-label>
<textarea matInput [(ngModel)]="newScript" rows="6" placeholder="Escriba su script aquí"></textarea>
</mat-form-field>
<button class="action-button" (click)="saveNewScript()">Guardar Comando</button>
</div>
<div *ngIf="commandType === 'existing'" class="select-container">
<mat-form-field appearance="fill" class="custom-width">
<mat-label>Seleccione script a ejecutar</mat-label>
<mat-select [(ngModel)]="selectedScript" (selectionChange)="onScriptChange()">
<mat-option *ngFor="let script of scripts" [value]="script">{{ script.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div *ngIf="selectedScript && commandType === 'existing'" class="script-container">
<div class="script-content">
<h3> Script:</h3>
<div class="script-preview" [innerHTML]="scriptContent"></div>
</div>
<div class="action-chips-container">
<mat-chip-listbox [(ngModel)]="commandType" required class="action-chip-listbox">
<mat-chip-option value="new" class="action-chip create-chip firmware-chip" (click)="commandType = 'new'">
<span>Nuevo Script</span>
</mat-chip-option>
<mat-chip-option value="existing" class="action-chip update-chip firmware-chip" (click)="commandType = 'existing'">
<span>Script Guardado</span>
</mat-chip-option>
</mat-chip-listbox>
</div>
<div *ngIf="commandType === 'new'" class="new-command-container">
<mat-form-field appearance="fill" class="full-width">
<mat-label>Ingrese el script</mat-label>
<textarea matInput [(ngModel)]="newScript" rows="6" placeholder="Escriba su script aquí"></textarea>
</mat-form-field>
<button mat-flat-button color="primary" (click)="saveNewScript()">Guardar Script</button>
</div>
<div *ngIf="commandType === 'existing'">
<mat-form-field appearance="fill" class="custom-width">
<mat-label>Seleccione script a ejecutar</mat-label>
<mat-select [(ngModel)]="selectedScript" (selectionChange)="onScriptChange()">
<mat-option *ngFor="let script of scripts" [value]="script">{{ script.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div *ngIf="selectedScript && commandType === 'existing'" class="script-container">
<div class="script-content">
<h3>Script:</h3>
<div class="script-preview" [innerHTML]="scriptContent"></div>
</div>
<div class="script-params" *ngIf="parameterNames.length > 0 && selectedScript.parameters">
<h3>Ingrese los parámetros:</h3>
<div *ngFor="let paramName of parameterNames">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ paramName }}</mat-label>
<input matInput [ngModel]="parameters[paramName]" (ngModelChange)="onParamChange(paramName, $event)" placeholder="Valor para {{ paramName }}">
</mat-form-field>
</div>
<div class="script-params" *ngIf="parameterNames.length > 0">
<h3>Ingrese los valores de los parámetros detectados:</h3>
<div *ngFor="let paramName of parameterNames">
<mat-form-field appearance="fill" class="full-width">
<mat-label>{{ paramName }}</mat-label>
<input matInput
[ngModel]="parameters[paramName]"
(ngModelChange)="onParamChange(paramName, $event)"
placeholder="Ingrese el valor">
</mat-form-field>
</div>
</div>
</div>
</div>
<app-scroll-to-top
[threshold]="200"
targetElement=".header-container"
position="bottom-right"
[showTooltip]="true"
tooltipText="Volver arriba"
tooltipPosition="left">
</app-scroll-to-top>

View File

@ -2,7 +2,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RunScriptAssistantComponent } from './run-script-assistant.component';
import { DeployImageComponent } from "../deploy-image/deploy-image.component";
import { LoadingComponent } from "../../../../../shared/loading/loading.component";
import { ScrollToTopComponent } from "../../../../../shared/scroll-to-top/scroll-to-top.component";
import { FormBuilder, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from "@angular/material/dialog";
import { MatFormFieldModule } from "@angular/material/form-field";
@ -27,10 +26,6 @@ import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import {MatIconModule} from "@angular/material/icon";
import {MatCardModule} from "@angular/material/card";
import {MatButtonToggleModule} from "@angular/material/button-toggle";
import { MatChipsModule } from "@angular/material/chips";
import { MatTooltipModule } from "@angular/material/tooltip";
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
@ -47,7 +42,7 @@ describe('RunScriptAssistantComponent', () => {
};
await TestBed.configureTestingModule({
declarations: [RunScriptAssistantComponent, DeployImageComponent, LoadingComponent, ScrollToTopComponent],
declarations: [RunScriptAssistantComponent, DeployImageComponent, LoadingComponent],
imports: [
ReactiveFormsModule,
FormsModule,
@ -64,10 +59,6 @@ describe('RunScriptAssistantComponent', () => {
MatSelectModule,
BrowserAnimationsModule,
MatIconModule,
MatCardModule,
MatButtonToggleModule,
MatChipsModule,
MatTooltipModule,
ToastrModule.forRoot(),
HttpClientTestingModule,
TranslateModule.forRoot({

View File

@ -1,20 +1,18 @@
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import { SelectionModel } from "@angular/cdk/collections";
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ConfigService } from "@services/config.service";
import { ActivatedRoute, Router } from "@angular/router";
import { SaveScriptComponent } from "./save-script/save-script.component";
import { MatDialog } from "@angular/material/dialog";
import {CreateTaskComponent} from "../../../../commands/commands-task/create-task/create-task.component";
import {QueueConfirmationModalComponent} from "../../../../../shared/queue-confirmation-modal/queue-confirmation-modal.component";
import {Component, EventEmitter, Output} from '@angular/core';
import {SelectionModel} from "@angular/cdk/collections";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
import {ConfigService} from "@services/config.service";
import {ActivatedRoute, Router} from "@angular/router";
import {SaveScriptComponent} from "./save-script/save-script.component";
import {MatDialog} from "@angular/material/dialog";
@Component({
selector: 'app-run-script-assistant',
templateUrl: './run-script-assistant.component.html',
styleUrl: './run-script-assistant.component.css'
})
export class RunScriptAssistantComponent implements OnInit{
export class RunScriptAssistantComponent {
baseUrl: string;
@Output() dataChange = new EventEmitter<any>();
@ -34,7 +32,6 @@ export class RunScriptAssistantComponent implements OnInit{
newScript: string = '';
selection = new SelectionModel(true, []);
parameterNames: string[] = Object.keys(this.parameters);
runScriptContext: any = null;
constructor(
private http: HttpClient,
@ -49,39 +46,19 @@ export class RunScriptAssistantComponent implements OnInit{
if (params['clientData']) {
this.clientData = JSON.parse(params['clientData']);
}
if (params['runScriptContext']) {
this.runScriptContext = params['runScriptContext'];
}
});
this.clientId = this.clientData?.length ? this.clientData[0]['@id'] : null;
this.clientData.forEach((client: { selected: boolean; status: string}) => { client.selected = true; });
this.selectedClients = this.clientData.filter((client: { selected: boolean; status: string}) => client.selected);
this.clientData.forEach((client: { selected: boolean; status: string}) => {
if (client.status === 'og-live') {
client.selected = true;
}
});
this.selectedClients = this.clientData.filter(
(client: { status: string }) => client.status === 'og-live'
);
this.loadScripts()
}
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.runScriptContext = params['runScriptContext'] ? JSON.parse(params['runScriptContext']) : null;
});
}
get runScriptTitle(): string {
const ctx = this.runScriptContext;
if (!ctx) {
return '';
}
if (Array.isArray(ctx)) {
return ctx.map(c => c.name).join(', ');
}
if (typeof ctx === 'object' && 'name' in ctx) {
return ctx.name;
}
return String(ctx);
}
loadScripts(): void {
this.loading = true;
@ -117,12 +94,18 @@ export class RunScriptAssistantComponent implements OnInit{
}
updateSelectedClients() {
this.selectedClients = this.clientData.filter((client: { selected: boolean; status: string}) => client.selected);
this.selectedClients = this.clientData.filter(
(client: { selected: boolean; status: string }) => client.selected && client.status === "og-live"
);
}
toggleSelectAll() {
this.allSelected = !this.allSelected;
this.clientData.forEach((client: { selected: boolean; status: string }) => { client.selected = this.allSelected; });
this.clientData.forEach((client: { selected: boolean; status: string }) => {
if (client.status === "og-live") {
client.selected = this.allSelected;
}
});
}
getPartitionsTooltip(client: any): string {
@ -131,7 +114,7 @@ export class RunScriptAssistantComponent implements OnInit{
}
return client.partitions
.map((p: { partitionNumber: any; size: any; filesystem: any }) => `#${p.partitionNumber} ${p.filesystem} - ${p.size / 1024}GB`)
.map((p: { partitionNumber: any; size: any; filesystem: any }) => `#${p.partitionNumber} ${p.filesystem} - ${p.size / 1024 }GB`)
.join('\n');
}
@ -167,62 +150,28 @@ export class RunScriptAssistantComponent implements OnInit{
this.scriptContent = updatedScript;
}
save(): void {
const dialogRef = this.dialog.open(QueueConfirmationModalComponent, {
width: '400px',
disableClose: true,
hasBackdrop: true
});
dialogRef.afterClosed().subscribe(result => {
if (result !== undefined) {
this.loading = true;
this.http.post(`${this.baseUrl}/commands/run-script`, {
clients: this.selectedClients.map((client: any) => client.uuid),
script: this.commandType === 'existing' ? this.scriptContent : this.newScript,
queue: result
}).subscribe(
response => {
this.toastService.success('Script ejecutado correctamente');
this.dataChange.emit();
this.router.navigate(['/commands-logs']);
this.loading = false;
},
error => {
this.toastService.error('Error al ejecutar el script');
this.loading = false;
}
);
}
});
trackByIndex(index: number): number {
return index;
}
openScheduleModal(): void {
const dialogRef = this.dialog.open(CreateTaskComponent, {
width: '800px',
data: {
scope: this.runScriptContext.type,
organizationalUnit: this.runScriptContext['@id'],
source: 'assistant'
}
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.http.post(`${this.baseUrl}/command-task-scripts`, {
commandTask: result['@id'],
content: this.commandType === 'existing' ? this.scriptContent : this.newScript,
order: 1,
type: 'run-script',
}).subscribe({
next: () => {
this.toastService.success('Script añadido con éxito a la tarea');
},
error: (error) => {
this.toastService.error(error.error['hydra:description']);
}
})
save(): void {
this.loading = true;
this.http.post(`${this.baseUrl}/commands/run-script`, {
clients: this.selectedClients.map((client: any) => client.uuid),
script: this.commandType === 'existing' ? this.scriptContent : this.newScript,
}).subscribe(
response => {
this.toastService.success('Script ejecutado correctamente');
this.dataChange.emit();
this.router.navigate(['/commands-logs']);
},
error => {
this.toastService.error('Error al ejecutar el script');
}
});
);
this.loading = false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +1,25 @@
<app-modal-overlay
[isVisible]="loading"
message="Cargando...">
</app-modal-overlay>
<div class="groups-container">
<!-- HEADER -->
<div class="header-container">
<button mat-icon-button color="primary" (click)="initTour()">
<div class="header-container" joyrideStep="tabsStep" text="{{ 'tabsStepText' | translate }}">
<button mat-icon-button color="primary" (click)="iniciarTour()">
<mat-icon>help</mat-icon>
</button>
<div class="header-container-title">
<h2 joyrideStep="groupsTitleStep" text="{{ 'groupsTitleStepText' | translate }}">
<h2 joyrideStep="groupsTitleStepText" text="{{ 'groupsTitleStepText' | translate }}">
{{ 'adminGroupsTitle' | translate }}
</h2>
</div>
<div class="groups-button-row">
<div joyrideStep="addStep" text="{{ 'groupsAddStepText' | translate }}" style="display: flex; gap: 15px;">
<button class="action-button" (click)="addOU($event)" *ngIf="auth.userCategory !== 'ou-minimal'"
matTooltip="{{ 'newOrganizationalUnitTooltip' | translate }}" matTooltipShowDelay="1000">
{{ 'newOrganizationalUnitButton' | translate }}
</button>
<button class="action-button" [matMenuTriggerFor]="menuClients" *ngIf="auth.userCategory !== 'ou-minimal'">{{
'newClientButton' | translate }}</button>
<mat-menu #menuClients="matMenu">
<button mat-menu-item (click)="addClient($event)">{{ 'newSingleClientButton' | translate }}</button>
<button mat-menu-item (click)="addMultipleClients($event)">{{ 'newMultipleClientButton' | translate
}}</button>
</mat-menu>
</div>
<div class="groups-button-row" joyrideStep="addStep" text="{{ 'groupsAddStepText' | translate }}">
<button class="action-button" (click)="addOU($event)"
matTooltip="{{ 'newOrganizationalUnitTooltip' | translate }}" matTooltipShowDelay="1000">
{{ 'newOrganizationalUnitButton' | translate }}
</button>
<button class="action-button" [matMenuTriggerFor]="menuClients">{{ 'newClientButton' | translate }}</button>
<mat-menu #menuClients="matMenu">
<button mat-menu-item (click)="addClient($event)">{{ 'newSingleClientButton' | translate }}</button>
<button mat-menu-item (click)="addMultipleClients($event)">{{ 'newMultipleClientButton' | translate }}</button>
</mat-menu>
<button class="ordinary-button" (click)="openBottomSheet()" joyrideStep="keyStep"
text="{{ 'keyStepText' | translate }}" matTooltipShowDelay="1000">
{{ 'legendButton' | translate }}
@ -89,7 +81,7 @@
</button>
</mat-form-field>
<mat-form-field class="form-field search-select" appearance="outline">
<mat-select placeholder="{{ 'searchState' | translate }}" #clientSearchStatusInput
<mat-select placeholder="Buscar por estado..." #clientSearchStatusInput
(selectionChange)="onClientFilterStatusInput($event.value)">
<mat-option *ngFor="let option of status" [value]="option.value">
{{ option.name }}
@ -101,6 +93,8 @@
</button>
</mat-form-field>
<mat-divider class="tree-mat-divider" style="padding-top: 10px;"></mat-divider>
<!-- Funcionalidad actualmente deshabilitada-->
<!-- <mat-form-field appearance="outline">
<mat-select (selectionChange)="loadSelectedFilter($event.value)" placeholder="Cargar filtro" disabled>
@ -122,108 +116,49 @@
</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-node [ngClass]="{'selected-node': selectedNode?.id === node.id, 'tree-node': true}"
<div class="tree-container">
<mat-tree [dataSource]="treeDataSource" [treeControl]="treeControl">
<mat-tree-node [ngClass]="{'selected-node': selectedNode?.id === node.id}"
*matTreeNodeDef="let node; when: hasChild" matTreeNodePadding (click)="onNodeClick($event, node)">
<div class="node-content">
<button mat-icon-button matTreeNodeToggle [disabled]="!node.expandable"
[ngClass]="{'disabled-toggle': !node.expandable}" class="expand-button">
<mat-icon class="expand-icon">{{ treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}</mat-icon>
</button>
<div class="node-info">
<div class="node-main">
<mat-icon class="node-icon {{ node.type }}" [matTooltip]="getNodeTypeTooltip(node.type)">
{{
node.type === 'organizational-unit' ? 'business'
: node.type === 'classrooms-group' ? 'meeting_room'
: node.type === 'classroom' ? 'school'
: node.type === 'clients-group' ? 'dns'
: node.type === 'client' ? 'computer'
: 'folder'
}}
</mat-icon>
<span class="node-name" [matTooltip]="node.name">{{ node.name }}</span>
</div>
<div class="node-details">
<ng-container *ngIf="node.type === 'client'">
<span class="node-ip">{{ node.ip }}</span>
</ng-container>
<ng-container *ngIf="node.children && node.children.length > 0">
<span class="node-count">{{ node.children.length }} {{ getNodeCountLabel(node.children.length) }}</span>
</ng-container>
</div>
</div>
<div class="node-actions">
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)"
class="menu-button" matTooltip="{{ 'moreActions' | translate }}">
<mat-icon>more_vert</mat-icon>
</button>
</div>
</div>
<button mat-icon-button matTreeNodeToggle [disabled]="!node.expandable"
[ngClass]="{'disabled-toggle': !node.expandable}">
<mat-icon>{{ treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}</mat-icon>
</button>
<mat-icon class="node-icon {{ node.type }}">
{{
node.type === 'organizational-unit' ? 'apartment'
: node.type === 'classrooms-group' ? 'meeting_room'
: node.type === 'classroom' ? 'school'
: node.type === 'clients-group' ? 'lan'
: node.type === 'client' ? 'computer'
: 'group'
}}
</mat-icon>
<span>{{ node.name }}</span>
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)">
<mat-icon>more_vert</mat-icon>
</button>
</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}"
*matTreeNodeDef="let node; when: isLeafNode" matTreeNodePadding (click)="onNodeClick($event, node)">
<div class="node-content">
<button mat-icon-button matTreeNodeToggle [disabled]="true" class="disabled-toggle expand-button">
<mat-icon class="expand-icon">chevron_right</mat-icon>
</button>
<div class="node-info">
<div class="node-main">
<mat-icon class="node-icon {{ node.type }}" [ngClass]="{'client-status': node.type === 'client'}"
[matTooltip]="getNodeTypeTooltip(node.type)">
{{
node.type === 'organizational-unit' ? 'business'
: node.type === 'classrooms-group' ? 'meeting_room'
: node.type === 'classroom' ? 'school'
: node.type === 'clients-group' ? 'dns'
: node.type === 'client' ? 'computer'
: 'folder'
}}
</mat-icon>
<span class="node-name" [matTooltip]="node.name">{{ node.name }}</span>
</div>
<div class="node-details">
<ng-container *ngIf="node.type === 'client'">
<span class="node-ip">{{ node.ip }}</span>
<span class="node-mac">{{ node.mac }}</span>
<span class="node-status" [ngClass]="'status-' + (node.status || 'off')">
{{ getStatusLabel(node.status) }}
</span>
</ng-container>
</div>
</div>
<div class="node-actions">
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)"
class="menu-button" matTooltip="{{ 'moreActions' | translate }}">
<mat-icon>more_vert</mat-icon>
</button>
</div>
</div>
<button mat-icon-button matTreeNodeToggle [disabled]="true" class="disabled-toggle"></button>
<mat-icon style="color: green;">
{{
node.type === 'organizational-unit' ? 'apartment'
: node.type === 'classrooms-group' ? 'meeting_room'
: node.type === 'classroom' ? 'school'
: node.type === 'clients-group' ? 'lan'
: node.type === 'client' ? 'computer'
: 'group'
}}
</mat-icon>
<span>{{ node.name }}</span>
<ng-container *ngIf="node.type === 'client'">
<span> - IP: {{ node.ip }}</span>
</ng-container>
<button mat-icon-button [matMenuTriggerFor]="menuNode" (click)="onMenuClick($event, node)">
<mat-icon>more_vert</mat-icon>
</button>
</mat-tree-node>
</mat-tree>
</div>
@ -243,40 +178,28 @@
<mat-icon>map</mat-icon>
<span>{{ 'roomMap' | translate }}</span>
</button>
<button mat-menu-item (click)="addClient($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="addClient($event, selectedNode)">
<mat-icon>add</mat-icon>
<span>{{ 'newSingleClientButton' | translate }}</span>
</button>
<button mat-menu-item (click)="addMultipleClients($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="addMultipleClients($event, selectedNode)">
<mat-icon>playlist_add</mat-icon>
<span>{{ 'newMultipleClientButton' | translate }}</span>
</button>
<button mat-menu-item (click)="addOU($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="addOU($event, selectedNode)">
<mat-icon>account_tree</mat-icon>
<span>{{ 'addOrganizationalUnit' | translate }}</span>
</button>
<button mat-menu-item (click)="onEditNode($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onEditNode($event, selectedNode)">
<mat-icon>edit</mat-icon>
<span>{{ 'edit' | translate }}</span>
</button>
<button mat-menu-item (click)="onDeleteClick($event, selectedNode)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onDeleteClick($event, selectedNode)">
<mat-icon>delete</mat-icon>
<span>{{ 'delete' | translate }}</span>
</button>
<button mat-menu-item (click)="openPartitionTypeModal($event, selectedNode)">
<mat-icon>storage</mat-icon>
<span>{{ 'partitions' | translate }}</span>
</button>
<button mat-menu-item (click)="openOUPendingTasks($event, selectedNode)">
<mat-icon>pending_actions</mat-icon>
<span>{{ 'colaAcciones' | translate }}</span>
</button>
<app-execute-command [clientData]="selectedNode?.clients || []" [buttonType]="'menu-item'"
[buttonText]="'ejecutarComandos' | translate" [icon]="'terminal'"
[disabled]="!((selectedNode?.clients ?? []).length > 0)" [runScriptContext]="selectedNode?.name || ''"
[runScriptContext]="getRunScriptContext(selectedNode?.clients || [])">
</app-execute-command>
</mat-menu>
</div>
<mat-divider [vertical]="true"></mat-divider>
@ -291,23 +214,15 @@
<strong>{{ selectedNode?.name }}</strong>
</span>
<div class="view-type-container">
<button class="action-button" [disabled]="selection.selected.length === 0" (click)="changeParent($event)"
matTooltip="{{ 'moveClientsTooltip' | translate }}" matTooltipShowDelay="1000">
{{ 'changeOU' | translate }}
</button>
<div joyrideStep="executeCommandStep" text="{{ 'executeCommandStepText' | translate }}">
<app-execute-command [clientData]="selection.selected" [buttonType]="'text'"
[buttonText]="'ejecutarComandos' | translate" [disabled]="selection.selected.length === 0"
[runScriptContext]="getRunScriptContext(selection.selected)"></app-execute-command>
</div>
<app-execute-command [clientData]="selection.selected" [buttonType]="'text'"
[buttonText]="'Ejecutar comandos'" [disabled]="selection.selected.length === 0"></app-execute-command>
<mat-button-toggle-group name="viewType" aria-label="View Type" [hideSingleSelectionIndicator]="true"
(change)="toggleView($event.value)" joyrideStep="tabsStep" text="{{ 'tabsStepText' | translate }}">
(change)="toggleView($event.value)">
<mat-button-toggle value="list" [disabled]="currentView === 'list'">
<mat-icon>list</mat-icon> <span class="type-view-text">{{ 'vistalista' | translate }}</span>
<mat-icon>list</mat-icon> <span class="type-view-text">{{ 'Vista Lista' | translate }}</span>
</mat-button-toggle>
<mat-button-toggle value="card" [disabled]="currentView === 'card'">
<mat-icon>grid_view</mat-icon> <span class="type-view-text">{{ 'vistatarjeta' | translate }}</span>
<mat-icon>grid_view</mat-icon> <span class="type-view-text">{{ 'Vista Tarjeta' | translate }}</span>
</mat-button-toggle>
</mat-button-toggle-group>
</div>
@ -316,49 +231,9 @@
<app-loading [isLoading]="isLoadingClients"></app-loading>
<!-- CLIENTS VIEWS-->
<div class="clients-view" *ngIf="!isLoadingClients" joyrideStep="clientsViewStep"
text="{{ 'clientsViewStepText' | translate }}">
<div class="clients-view" *ngIf="!isLoadingClients">
<div *ngIf="hasClients; else noClientsTemplate">
<div class="stats-container" *ngIf="currentView === 'list'">
<div class="stat-card">
<div class="stat-icon">
<mat-icon>computer</mat-icon>
</div>
<div class="stat-content">
<div class="stat-number">{{ totalStats.total }}</div>
<div class="stat-label">{{ 'totalClients' | translate }}</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon offline">
<mat-icon>wifi_off</mat-icon>
</div>
<div class="stat-content">
<div class="stat-number">{{ getStatusCount('off') }}</div>
<div class="stat-label">{{ 'offline' | translate }}</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon online">
<mat-icon>wifi</mat-icon>
</div>
<div class="stat-content">
<div class="stat-number">{{ getStatusCount('og-live') + getStatusCount('linux') + getStatusCount('windows') }}</div>
<div class="stat-label">{{ 'online' | translate }}</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon busy">
<mat-icon>hourglass_empty</mat-icon>
</div>
<div class="stat-content">
<div class="stat-number">{{ getStatusCount('busy') }}</div>
<div class="stat-label">{{ 'busy' | translate }}</div>
</div>
</div>
</div>
<!-- Cards view -->
<div *ngIf="currentView === 'card'">
<section class="cards-view">
@ -367,24 +242,22 @@
[indeterminate]="selection.hasValue() && !isAllSelected()">
</mat-checkbox>
<div class="clients-grid">
<div *ngFor="let client of arrayClients" class="client-item" [ngClass]="'status-' + client.status">
<div *ngFor="let client of arrayClients" class="client-item">
<div class="client-card">
<mat-checkbox (click)="$event.stopPropagation()" (change)="toggleRow(client)"
[checked]="selection.isSelected(client)">
[checked]="selection.isSelected(client)" [disabled]="client.status === 'busy' || client.status === 'off' || client.status === 'disconnected'">
</mat-checkbox>
<img style="margin-top: 0.5em;" [src]="'assets/images/computer_' + client.status + '.svg'"
alt="Client Icon" class="client-image" />
<div class="client-details">
<span class="client-name truncate-cell-wide" [matTooltip]="client.name">{{ client.name }}</span>
<span class="client-name">{{ client.name }}</span>
<span class="client-ip">{{ client.ip }}</span>
<span class="client-mac">{{ client.mac }}</span>
<span class="client-ip">{{ client.mac }}</span>
<div class="action-icons">
<app-execute-command [clientState]="client.status" [clientData]="[client]"
[buttonType]="'icon'" [icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
[runScriptContext]="getRunScriptContext([client])"></app-execute-command>
<app-execute-command [clientData]="[client]" [buttonType]="'icon'" [icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"></app-execute-command>
<button
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
@ -397,7 +270,7 @@
</span>
<mat-menu #clientMenu="matMenu">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)">
<mat-icon>edit</mat-icon>
<span>{{ 'edit' | translate }}</span>
</button>
@ -410,19 +283,7 @@
<mat-icon>sync</mat-icon>
<span>{{ 'sync' | 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>Logs en tiempo real</span>
</button>
<button mat-menu-item (click)="onDeleteClick($event, client)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onDeleteClick($event, client)">
<mat-icon>delete</mat-icon>
<span>{{ 'delete' | translate }}</span>
</button>
@ -440,24 +301,10 @@
</div>
</div>
<!-- List view mejorada -->
<!-- List view -->
<div *ngIf="currentView === 'list'" class="list-view">
<div class="table-header">
<div class="table-info">
<span>{{ 'showingResults' | translate: { from: getPaginationFrom(), to: getPaginationTo(), total: getPaginationTotal() } }}</span>
</div>
<div class="table-actions">
<button mat-icon-button (click)="refreshClientData()" matTooltip="{{ 'refresh' | translate }}">
<mat-icon>refresh</mat-icon>
</button>
<button mat-icon-button (click)="exportToCSV()" matTooltip="{{ 'exportCSV' | translate }}">
<mat-icon>download</mat-icon>
</button>
</div>
</div>
<section class="clients-table" tabindex="0">
<table mat-table [dataSource]="selectedClients" class="mat-elevation-z8">
<table mat-table matSort [dataSource]="selectedClients">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? toggleAllRows() : null"
@ -467,19 +314,12 @@
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox (click)="$event.stopPropagation()" (change)="toggleRow(row)"
[checked]="selection.isSelected(row)">
[checked]="selection.isSelected(row)" [disabled]="row.status === 'busy' || row.status === 'off' || row.status === 'disconnected'">
</mat-checkbox>
</td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef>
<div class="column-header">
<span>{{ 'status' | translate }}</span>
<button mat-icon-button (click)="sortColumn('status')" class="sort-button">
<mat-icon>{{ getSortIcon('status') }}</mat-icon>
</button>
</div>
</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'status' | translate }} </th>
<td mat-cell *matCellDef="let client" matTooltip="{{ getClientPath(client) }}"
matTooltipPosition="left" matTooltipShowDelay="500">
<div class="client-status-container">
@ -493,103 +333,55 @@
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>
<div class="column-header">
<span>{{ 'name' | translate }}</span>
<button mat-icon-button (click)="sortColumn('name')" class="sort-button">
<mat-icon>{{ getSortIcon('name') }}</mat-icon>
</button>
</div>
</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'name' | translate }} </th>
<td mat-cell *matCellDef="let client" matTooltip="{{ getClientPath(client) }}"
matTooltipPosition="left" matTooltipShowDelay="500">
<div class="client-cell">
<span class="client-name truncate-cell-wide" [matTooltip]="client.name">{{ client.name }}</span>
</div>
<p>{{ client.name }}</p>
</td>
</ng-container>
<ng-container matColumnDef="ip">
<th mat-header-cell *matHeaderCellDef>
<div class="column-header">
<span>IP</span>
<button mat-icon-button (click)="sortColumn('ip')" class="sort-button">
<mat-icon>{{ getSortIcon('ip') }}</mat-icon>
</button>
</div>
</th>
<th mat-header-cell *matHeaderCellDef mat-sort-header>IP </th>
<td mat-cell *matCellDef="let client" matTooltip="{{ getClientPath(client) }}"
matTooltipPosition="left" matTooltipShowDelay="500">
<div class="client-cell">
<span class="client-ip">{{ client.ip }}</span>
<span class="client-mac">{{ client.mac }}</span>
</div>
{{ client.ip }}
</td>
</ng-container>
<ng-container matColumnDef="firmwareType">
<th mat-header-cell *matHeaderCellDef>
<div class="column-header">
<span>{{ 'firmwareType' | translate }}</span>
<button mat-icon-button (click)="sortColumn('firmwareType')" class="sort-button">
<mat-icon>{{ getSortIcon('firmwareType') }}</mat-icon>
</button>
</div>
</th>
<td mat-cell *matCellDef="let client">
<mat-chip *ngIf="client.firmwareType" class="firmware-chip">
{{ client.firmwareType }}
</mat-chip>
</td>
</ng-container>
<ng-container matColumnDef="oglive">
<th mat-header-cell *matHeaderCellDef> OG Live </th>
<td mat-cell *matCellDef="let client">
<div class="oglive-cell">
<span class="oglive-kernel">{{ client.ogLive?.kernel }}</span>
<span class="oglive-date">{{ client.ogLive?.date | date }}</span>
</div>
</td>
<th mat-header-cell *matHeaderCellDef mat-sort-header> OG Live </th>
<td mat-cell *matCellDef="let client"> {{ client.ogLive?.date | date }} </td>
</ng-container>
<ng-container matColumnDef="maintenace">
<th mat-header-cell *matHeaderCellDef> {{ 'maintenance' | translate }} </th>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'maintenance' | translate }} </th>
<td mat-cell *matCellDef="let client"> {{ client.maintenance }} </td>
</ng-container>
<ng-container matColumnDef="subnet">
<th mat-header-cell *matHeaderCellDef> {{ 'subnet' | translate }} </th>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'subnet' | translate }} </th>
<td mat-cell *matCellDef="let client"> {{ client.subnet }} </td>
</ng-container>
<ng-container matColumnDef="pxeTemplate">
<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>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'pxeTemplate' | translate }} </th>
<td mat-cell *matCellDef="let client"> {{ client.template?.name }} </td>
</ng-container>
<ng-container matColumnDef="parentName">
<th mat-header-cell *matHeaderCellDef> {{ 'parent' | translate }} </th>
<td mat-cell *matCellDef="let client" class="truncate-cell-medium" [matTooltip]="client.parentName"> {{ client.parentName }} </td>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'parent' | translate }} </th>
<td mat-cell *matCellDef="let client"> {{ client.parentName }} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> {{ 'actions' | translate }} </th>
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{ 'actions' | translate }} </th>
<td mat-cell *matCellDef="let client">
<div class="action-buttons">
<button
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary" matTooltip="{{ 'moreActions' | translate }}">
<mat-icon>more_vert</mat-icon>
</button>
<app-execute-command [clientState]="client.status" [clientData]="[client]" [buttonType]="'icon'"
[icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
[runScriptContext]="getRunScriptContext([client])" matTooltip="{{ 'executeCommand' | translate }}">
</app-execute-command>
<button mat-icon-button color="primary" (click)="onShowClientDetail($event, client)" matTooltip="{{ 'viewDetails' | translate }}">
<mat-icon>visibility</mat-icon>
</button>
</div>
<button
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))"
mat-icon-button [matMenuTriggerFor]="clientMenu" color="primary">
<mat-icon>more_vert</mat-icon>
</button>
<app-execute-command [clientData]="[client]" [buttonType]="'icon'" [icon]="'terminal'"
[disabled]="selection.selected.length > 1 || (selection.selected.length === 1 && !selection.isSelected(client))">
</app-execute-command>
<mat-menu #clientMenu="matMenu">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onEditClick($event, client.type, client.uuid)">
<mat-icon>edit</mat-icon>
<span>{{ 'edit' | translate }}</span>
</button>
@ -601,30 +393,16 @@
<mat-icon>sync</mat-icon>
<span>{{ 'sync' | 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>Logs en tiempo real</span>
</button>
<button mat-menu-item (click)="onDeleteClick($event, client)" *ngIf="auth.userCategory !== 'ou-minimal'">
<button mat-menu-item (click)="onDeleteClick($event, client)">
<mat-icon>delete</mat-icon>
<span>{{ 'delete' | translate }}</span>
</button>
</mat-menu>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" class="mat-row"
[ngClass]="'status-' + row.status"
[class.selected-row]="selectedClient?.uuid === row.uuid"
(click)="selectClient(row)"></tr>
<tr mat-header-row style="background-color: #f3f3f3;"
*matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</section>
<mat-paginator class="list-paginator" [length]="length" [pageSize]="itemsPerPage" [pageIndex]="page"

View File

@ -27,7 +27,6 @@ import { TreeNode } from './model/model';
import { LoadingComponent } from '../../shared/loading/loading.component';
import { ExecuteCommandComponent } from '../commands/main-commands/execute-command/execute-command.component';
import { ConfigService } from '@services/config.service';
import { ModalOverlayComponent } from '../../shared/modal-overlay/modal-overlay.component';
describe('GroupsComponent', () => {
let component: GroupsComponent;
@ -40,7 +39,7 @@ describe('GroupsComponent', () => {
};
await TestBed.configureTestingModule({
declarations: [GroupsComponent, ExecuteCommandComponent, LoadingComponent, ModalOverlayComponent],
declarations: [GroupsComponent, ExecuteCommandComponent, LoadingComponent],
imports: [
HttpClientTestingModule,
ToastrModule.forRoot(),

View File

@ -1,4 +1,4 @@
import { Component, OnInit, OnDestroy, ViewChild, QueryList, ViewChildren, ChangeDetectorRef } from '@angular/core';
import { Component, OnInit, OnDestroy, ViewChild, QueryList, ViewChildren } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
@ -15,6 +15,7 @@ import { ShowOrganizationalUnitComponent } from './shared/organizational-units/s
import { LegendComponent } from './shared/legend/legend.component';
import { DeleteModalComponent } from '../../shared/delete_modal/delete-modal/delete-modal.component';
import { ClassroomViewDialogComponent } from './shared/classroom-view/classroom-view-modal';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { PageEvent } from '@angular/material/paginator';
import { CreateMultipleClientComponent } from "./shared/clients/create-multiple-client/create-multiple-client.component";
@ -25,12 +26,6 @@ import { Subject } from 'rxjs';
import { ConfigService } from '@services/config.service';
import { BreakpointObserver } from '@angular/cdk/layout';
import { MatMenuTrigger } from '@angular/material/menu';
import { ClientDetailsComponent } from './shared/client-details/client-details.component';
import { PartitionTypeOrganizatorComponent } from './shared/partition-type-organizator/partition-type-organizator.component';
import { ClientTaskLogsComponent } from '../task-logs/client-task-logs/client-task-logs.component';
import {ChangeParentComponent} from "./shared/change-parent/change-parent.component";
import { AuthService } from '@services/auth.service';
import { ClientPendingTasksComponent } from '../task-logs/client-pending-tasks/client-pending-tasks.component';
enum NodeType {
OrganizationalUnit = 'organizational-unit',
@ -79,29 +74,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
arrayClients: any[] = [];
filters: { [key: string]: string } = {};
private clientFilterSubject = new Subject<string>();
loading = false;
// Nuevas propiedades para funcionalidades mejoradas
selectedClient: any = null;
sortBy: string = 'name';
sortDirection: 'asc' | 'desc' = 'asc';
currentSortColumn: string = 'name';
// Estadísticas totales
totalStats: {
total: number;
off: number;
online: number;
busy: number;
} = {
total: 0,
off: 0,
online: 0,
busy: 0
};
// Tipos de firmware disponibles
firmwareTypes: string[] = [];
protected status = [
{ value: 'off', name: 'Apagado' },
@ -113,10 +85,19 @@ export class GroupsComponent implements OnInit, OnDestroy {
{ value: 'windows-session', name: 'Windows Session' },
{ value: 'busy', name: 'Ocupado' },
{ value: 'mac', name: 'Mac' },
{ value: 'disconnected', name: 'Desconectado' }
];
displayedColumns: string[] = ['select', 'status', 'ip', 'firmwareType', 'name', 'oglive', 'subnet', 'pxeTemplate', 'actions'];
displayedColumns: string[] = ['select', 'status', 'ip', 'name', 'oglive', 'subnet', 'pxeTemplate', 'actions'];
private _sort!: MatSort;
@ViewChild(MatSort)
set matSort(ms: MatSort) {
this._sort = ms;
if (this.selectedClients) {
this.selectedClients.sort = this._sort;
}
}
private subscriptions: Subscription = new Subscription();
@ -129,9 +110,7 @@ export class GroupsComponent implements OnInit, OnDestroy {
private joyrideService: JoyrideService,
private breakpointObserver: BreakpointObserver,
private toastr: ToastrService,
public auth: AuthService,
private configService: ConfigService,
private cd: ChangeDetectorRef,
private configService: ConfigService
) {
this.baseUrl = this.configService.apiUrl;
this.mercureUrl = this.configService.mercureUrl;
@ -148,7 +127,7 @@ export class GroupsComponent implements OnInit, OnDestroy {
);
this.treeDataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
this.currentView = this.auth.groupsView || 'list';
this.currentView = localStorage.getItem('groupsView') || 'list';
}
@ -196,35 +175,23 @@ export class GroupsComponent implements OnInit, OnDestroy {
})
}
private updateClientStatus(clientUuid: string, status: string): void {
let updated = false;
private updateClientStatus(clientUuid: string, newStatus: string): void {
const clientIndex = this.selectedClients.data.findIndex(client => client['@id'] === clientUuid);
const index = this.arrayClients.findIndex(client => client['@id'] === clientUuid);
if (index !== -1) {
const updatedClient = { ...this.arrayClients[index], status };
this.arrayClients = [
...this.arrayClients.slice(0, index),
updatedClient,
...this.arrayClients.slice(index + 1)
];
updated = true;
}
const tableIndex = this.selectedClients.data.findIndex(client => client['@id'] === clientUuid);
if (tableIndex !== -1) {
if (clientIndex !== -1) {
const updatedClients = [...this.selectedClients.data];
updatedClients[tableIndex] = {
...updatedClients[tableIndex],
status: status
updatedClients[clientIndex] = {
...updatedClients[clientIndex],
status: newStatus
};
this.selectedClients.data = updatedClients;
}
this.arrayClients = updatedClients;
if (updated) {
this.cd.detectChanges();
console.log(`Estado actualizado para el cliente ${clientUuid}: ${newStatus}`);
} else {
console.warn(`Cliente con UUID ${clientUuid} no encontrado en la lista.`);
}
}
@ -402,34 +369,23 @@ export class GroupsComponent implements OnInit, OnDestroy {
onNodeClick(event: MouseEvent, node: TreeNode): void {
event.stopPropagation();
this.selectedNode = node;
const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid);
this.fetchClientsForNode(node, selectedClientsBeforeEdit);
this.fetchClientsForNode(node);
}
onMenuClick(event: Event, node: any): void {
event.stopPropagation();
this.selectedNode = node;
const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid);
this.fetchClientsForNode(node, selectedClientsBeforeEdit);
this.fetchClientsForNode(node);
}
public fetchClientsForNode(node: any, selectedClientsBeforeEdit: string[] = []): void {
const params = new HttpParams({ fromObject: this.filters });
// Agregar parámetros de ordenamiento al backend
let backendParams = { ...this.filters };
if (this.sortBy) {
backendParams['order[' + this.sortBy + ']'] = this.sortDirection;
}
this.isLoadingClients = true;
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 }).subscribe({
next: (response: any) => {
this.selectedClients.data = response['hydra:member'];
if (this.selectedNode) {
this.selectedNode.clients = response['hydra:member'];
}
this.length = response['hydra:totalItems'];
this.arrayClients = this.selectedClients.data;
this.hasClients = this.selectedClients.data.length > 0;
@ -442,9 +398,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.selection.select(client);
}
});
// Calcular estadísticas después de cargar los clientes
this.calculateLocalStats();
},
error: () => {
this.isLoadingClients = false;
@ -460,35 +413,25 @@ export class GroupsComponent implements OnInit, OnDestroy {
}
addOU(event: MouseEvent, parent: TreeNode | null = null): void {
this.loading = true;
event.stopPropagation();
const dialogRef = this.dialog.open(ManageOrganizationalUnitComponent, {
data: { parent },
width: '900px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
});
dialogRef.afterClosed().subscribe((newUnit) => {
if (newUnit) {
if (newUnit?.uuid) {
this.refreshData(newUnit.uuid);
}
this.loading = false;
});
}
addClient(event: MouseEvent, organizationalUnit: TreeNode | null = null): void {
this.loading = true;
event.stopPropagation();
const targetNode = organizationalUnit || this.selectedNode;
const dialogRef = this.dialog.open(ManageClientComponent, {
data: { organizationalUnit: targetNode },
width: '900px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
});
dialogRef.afterClosed().subscribe((result) => {
@ -501,22 +444,17 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.refreshData(parentNode.uuid);
}
}
this.loading = false;
});
}
addMultipleClients(event: MouseEvent, organizationalUnit: TreeNode | null = null): void {
this.loading = true;
event.stopPropagation();
const targetNode = organizationalUnit || this.selectedNode;
const dialogRef = this.dialog.open(CreateMultipleClientComponent, {
data: { organizationalUnit: targetNode },
width: '900px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
});
dialogRef.afterClosed().subscribe((result) => {
if (result?.success) {
@ -531,33 +469,29 @@ export class GroupsComponent implements OnInit, OnDestroy {
console.error('No se encontró el nodo padre después de la creación masiva.');
}
}
this.loading = false;
});
}
onEditNode(event: MouseEvent, node: TreeNode | null): void {
event.stopPropagation();
this.loading = true;
const uuid = node ? this.extractUuid(node['@id']) : null;
if (!uuid) return;
const dialogRef = node?.type !== NodeType.Client
? this.dialog.open(ManageOrganizationalUnitComponent, { data: { uuid }, width: '900px', disableClose: true, hasBackdrop: true, backdropClass: 'non-clickable-backdrop' })
: this.dialog.open(ManageClientComponent, { data: { uuid }, width: '900px', disableClose: true, hasBackdrop: true, backdropClass: 'non-clickable-backdrop' });
? this.dialog.open(ManageOrganizationalUnitComponent, { data: { uuid }, width: '900px' })
: this.dialog.open(ManageClientComponent, { data: { uuid }, width: '900px' });
dialogRef.afterClosed().subscribe((result) => {
if (result?.success) {
this.refreshData(node?.id);
}
this.menuTriggers.forEach(trigger => trigger.closeMenu());
this.loading = false;
});
}
onDeleteClick(event: MouseEvent, entity: TreeNode | Client | null): void {
event.stopPropagation();
this.loading = true;
if (!entity) return;
const uuid = entity['@id'] ? this.extractUuid(entity['@id']) : null;
@ -574,7 +508,6 @@ export class GroupsComponent implements OnInit, OnDestroy {
if (result === true) {
this.deleteEntityorClient(uuid, type);
}
this.loading = false;
});
}
@ -612,18 +545,16 @@ export class GroupsComponent implements OnInit, OnDestroy {
onEditClick(event: MouseEvent, type: string, uuid: string): void {
event.stopPropagation();
this.loading = true;
const selectedClientsBeforeEdit = this.selection.selected.map(client => client.uuid);
const dialogRef = type !== NodeType.Client
? this.dialog.open(ManageOrganizationalUnitComponent, { data: { uuid }, width: '900px', disableClose: true, hasBackdrop: true, backdropClass: 'non-clickable-backdrop' })
: this.dialog.open(ManageClientComponent, { data: { uuid }, width: '900px', disableClose: true, hasBackdrop: true, backdropClass: 'non-clickable-backdrop' });
? this.dialog.open(ManageOrganizationalUnitComponent, { data: { uuid }, width: '900px' })
: this.dialog.open(ManageClientComponent, { data: { uuid }, width: '900px' });
dialogRef.afterClosed().subscribe((result) => {
if (result?.success) {
this.refreshData(this.selectedNode?.id, selectedClientsBeforeEdit);
}
this.menuTriggers.forEach(trigger => trigger.closeMenu());
this.loading = false;
});
}
@ -631,14 +562,11 @@ export class GroupsComponent implements OnInit, OnDestroy {
onRoomMap(room: TreeNode | null): void {
if (!room || !room['@id']) return;
this.subscriptions.add(
this.http.get<{ clients: Client[] }>(`${this.baseUrl}/clients?organizationalUnit.id=${room.id}`).subscribe(
(response: any) => {
this.http.get<{ clients: Client[] }>(`${this.baseUrl}${room['@id']}`).subscribe(
(response) => {
this.dialog.open(ClassroomViewDialogComponent, {
width: '90vw',
data: { clients: response['hydra:member'] },
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
data: { clients: response.clients },
});
},
(error) => {
@ -650,46 +578,31 @@ export class GroupsComponent implements OnInit, OnDestroy {
executeCommand(command: Command, selectedNode: TreeNode | null): void {
this.loading = true;
if (!selectedNode) {
this.toastr.error('No hay un nodo seleccionado.');
return;
} else {
this.toastr.success(`Ejecutando comando: ${command.name} en ${selectedNode.name}`);
}
this.loading = false;
}
onShowClientDetail(event: MouseEvent, client: Client): void {
event.stopPropagation();
this.loading = true;
const dialogRef = this.dialog.open(ClientDetailsComponent, {
width: '70vw',
height: '90vh',
data: { clientData: client },
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
})
dialogRef.afterClosed().subscribe((result) => {
this.loading = false;
});
this.router.navigate(['clients', client.uuid], { state: { clientData: client } });
}
onShowDetailsClick(event: MouseEvent, data: TreeNode | null): void {
event.stopPropagation();
this.loading = true;
if (data && data.type !== NodeType.Client) {
this.dialog.open(ShowOrganizationalUnitComponent, { data: { data }, width: '800px', disableClose: true, hasBackdrop: true, backdropClass: 'non-clickable-backdrop' });
this.dialog.open(ShowOrganizationalUnitComponent, { data: { data }, width: '800px' });
} else {
if (data) {
this.router.navigate(['clients', this.extractUuid(data['@id'])], { state: { clientData: data } });
}
}
this.loading = false;
}
@ -698,9 +611,9 @@ export class GroupsComponent implements OnInit, OnDestroy {
}
initTour(): void {
iniciarTour(): void {
this.joyrideService.startTour({
steps: ['groupsTitleStep', 'filtersPanelStep', 'treePanelStep', 'addStep', 'keyStep', 'executeCommandStep', 'tabsStep', 'clientsViewStep'],
steps: ['groupsTitleStepText', 'filtersPanelStep', 'addStep', 'keyStep', 'tabsStep'],
showPrevButton: true,
themeColor: '#3f51b5',
});
@ -808,8 +721,8 @@ export class GroupsComponent implements OnInit, OnDestroy {
this.syncingClientId = null;
this.refreshData(parentNodeId)
},
(error) => {
this.toastr.error(error.error['hydra:description'] || 'Error al actualizar el cliente');
() => {
this.toastr.error('Error de conexión con el cliente');
this.syncStatus = false;
this.syncingClientId = null;
this.refreshData(parentNodeId)
@ -892,339 +805,4 @@ export class GroupsComponent implements OnInit, OnDestroy {
clientSearchStatusInput.value = null;
this.fetchClientsForNode(this.selectedNode);
}
getRunScriptContext(clientData: any[]): any {
const selectedClientNames = clientData.map(client => client.name);
if (clientData.length === 1) {
return clientData[0]; // devuelve el objeto cliente completo
} else if (
clientData.length === this.selectedClients.data.length &&
selectedClientNames.every(name => this.selectedClients.data.some(c => c.name === name))
) {
return this.selectedNode || null; // devuelve el nodo completo
} else if (clientData.length > 1) {
return clientData; // devuelve array de objetos cliente
} else if (this.selectedNode && clientData.length === 0) {
return this.selectedNode;
}
return null;
}
openPartitionTypeModal(event: MouseEvent, node: TreeNode | null = null): void {
event.stopPropagation();
const simplifiedClientsData = node?.clients?.map((client: any) => ({
name: client.name,
partitions: client.partitions
}));
this.dialog.open(PartitionTypeOrganizatorComponent, {
width: '1200px',
data: simplifiedClientsData
});
}
changeParent(event: MouseEvent, ): void {
event.stopPropagation();
const dialogRef = this.dialog.open(ChangeParentComponent, {
data: { clients: this.selection.selected },
width: '700px',
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.refreshData();
}
});
}
openClientTaskLogs(event: MouseEvent, client: Client): void {
this.loading = true;
event.stopPropagation();
const dialogRef = this.dialog.open(ClientTaskLogsComponent, {
width: '1200px',
data: { client },
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
})
dialogRef.afterClosed().subscribe((result) => {
this.loading = false;
});
}
openClientPendingTasks(event: MouseEvent, client: Client): void {
event.stopPropagation();
const dialogRef = this.dialog.open(ClientPendingTasksComponent, {
width: '90vw',
height: '80vh',
data: {
client: client,
parentNode: this.selectedNode
}
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.refreshClientData();
}
});
}
openClientLogsInNewTab(event: MouseEvent, client: Client): void {
event.stopPropagation();
if (client.ip) {
const logsUrl = `${this.baseUrl}/pcclients/${client.ip}/cgi-bin/httpd-log.sh`;
const windowName = `logs_${client.ip.replace(/\./g, '_')}`;
const newWindow = window.open(logsUrl, windowName);
if (newWindow) {
newWindow.document.write(`
<title>Logs - ${client.ip}</title>
<iframe src="${logsUrl}" width="100%" height="100%" style="border:none;"></iframe>
`);
}
} else {
this.toastr.error('No se puede acceder a los logs: IP del cliente no disponible', 'Error');
}
}
openOUPendingTasks(event: MouseEvent, node: any): void {
event.stopPropagation();
this.loading = true;
this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${node.id}&page=1&itemsPerPage=10000`).subscribe({
next: (response) => {
const allClients = response['hydra:member'] || [];
if (allClients.length === 0) {
this.toastr.warning('Esta unidad organizativa no tiene clientes');
return;
}
const ouClientData = {
name: node.name,
id: node.id,
uuid: node.uuid,
type: 'organizational-unit',
clients: allClients
};
const dialogRef = this.dialog.open(ClientPendingTasksComponent, {
width: '1200px',
data: { client: ouClientData, isOrganizationalUnit: true },
disableClose: true,
hasBackdrop: true,
backdropClass: 'non-clickable-backdrop',
});
dialogRef.afterClosed().subscribe((result) => {
this.loading = false;
});
},
error: (error) => {
console.error('Error al obtener los clientes de la unidad organizativa:', error);
this.toastr.error('Error al cargar los clientes de la unidad organizativa');
this.loading = false;
}
});
}
// Métodos para paginación
getPaginationFrom(): number {
return (this.page * this.itemsPerPage) + 1;
}
getPaginationTo(): number {
return Math.min((this.page + 1) * this.itemsPerPage, this.length);
}
getPaginationTotal(): number {
return this.length;
}
refreshClientData(): void {
this.fetchClientsForNode(this.selectedNode);
this.toastr.success('Datos actualizados', 'Éxito');
}
exportToCSV(): void {
const headers = ['Nombre', 'IP', 'MAC', 'Estado', 'Firmware', 'Subnet', 'Parent'];
const csvData = this.arrayClients.map(client => [
client.name,
client.ip || '',
client.mac || '',
client.status || '',
client.firmwareType || '',
client.subnet || '',
client.parentName || ''
]);
const csvContent = [headers, ...csvData]
.map(row => row.map(cell => `"${cell}"`).join(','))
.join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', `clients_${new Date().toISOString().split('T')[0]}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.toastr.success('Archivo CSV exportado correctamente', 'Éxito');
}
private calculateLocalStats(): void {
const clients = this.arrayClients;
this.totalStats = {
total: clients.length,
off: clients.filter(client => client.status === 'off').length,
online: clients.filter(client => ['og-live', 'linux', 'windows', 'linux-session', 'windows-session'].includes(client.status)).length,
busy: clients.filter(client => client.status === 'busy').length
};
// Actualizar tipos de firmware disponibles
this.firmwareTypes = [...new Set(clients.map(client => client.firmwareType).filter(Boolean))];
}
// Métodos para funcionalidades mejoradas
selectClient(client: any): void {
this.selectedClient = client;
}
sortColumn(columnDef: string): void {
if (this.currentSortColumn === columnDef) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.currentSortColumn = columnDef;
this.sortDirection = 'asc';
}
this.sortBy = columnDef;
this.onSortChange();
}
getSortIcon(columnDef: string): string {
if (this.currentSortColumn !== columnDef) {
return 'unfold_more';
}
return this.sortDirection === 'asc' ? 'expand_less' : 'expand_more';
}
onSortChange(): void {
// Hacer nueva llamada al backend con el ordenamiento actualizado
this.fetchClientsForNode(this.selectedNode);
}
getStatusCount(status: string): number {
switch(status) {
case 'off':
return this.totalStats.off;
case 'online':
return this.totalStats.online;
case 'busy':
return this.totalStats.busy;
default:
return this.arrayClients.filter(client => client.status === status).length;
}
}
// Métodos para el árbol mejorado
expandAll(): void {
this.treeControl.expandAll();
}
collapseAll(): void {
this.treeControl.collapseAll();
}
getNodeTypeTooltip(nodeType: string): string {
switch (nodeType) {
case 'organizational-unit':
return 'Unidad Organizacional - Estructura principal de la organización';
case 'classrooms-group':
return 'Grupo de Aulas - Conjunto de aulas relacionadas';
case 'classroom':
return 'Aula - Espacio físico con equipos informáticos';
case 'clients-group':
return 'Grupo de Equipos - Conjunto de equipos informáticos';
case 'client':
return 'Equipo Informático - Computadora o dispositivo individual';
case 'group':
return 'Grupo - Agrupación lógica de elementos';
default:
return 'Elemento del árbol organizacional';
}
}
getNodeCountLabel(count: number): string {
if (count === 1) return 'elemento';
return 'elementos';
}
getStatusLabel(status: string): string {
const statusLabels: { [key: string]: string } = {
'off': 'Apagado',
'og-live': 'OG Live',
'linux': 'Linux',
'linux-session': 'Linux Session',
'windows': 'Windows',
'windows-session': 'Windows Session',
'busy': 'Ocupado',
'mac': 'Mac',
'disconnected': 'Desconectado',
'initializing': 'Inicializando'
};
return statusLabels[status] || status;
}
// Funciones para el dashboard de estadísticas
getTotalOrganizationalUnits(): number {
let total = 0;
const countOrganizationalUnits = (nodes: TreeNode[]) => {
nodes.forEach(node => {
if (node.type === 'organizational-unit') {
total += 1;
}
if (node.children) {
countOrganizationalUnits(node.children);
}
});
};
countOrganizationalUnits(this.originalTreeData);
return total;
}
getTotalClassrooms(): number {
let total = 0;
const countClassrooms = (nodes: TreeNode[]) => {
nodes.forEach(node => {
if (node.type === 'classroom') {
total += 1;
}
if (node.children) {
countClassrooms(node.children);
}
});
};
countClassrooms(this.originalTreeData);
return total;
}
// Función para actualizar estadísticas cuando cambian los datos
private updateDashboardStats(): void {
// Las estadísticas de equipos ya se calculan en calculateLocalStats()
// Solo necesitamos asegurar que se actualicen cuando cambian los datos
this.calculateLocalStats();
}
}

View File

@ -1,39 +0,0 @@
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100px;
}
mat-form-field {
width: 100%;
}
mat-dialog-actions {
display: flex;
justify-content: flex-end;
}
.checkbox-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.selected-list ul {
list-style: none;
padding: 0;
}
.selected-item {
display: flex;
justify-content: space-between; /* Alinea texto a la izquierda y botón a la derecha */
align-items: center; /* Centra verticalmente */
padding: 8px;
border-bottom: 1px solid #ccc;
}
.selected-item button {
margin-left: 10px;
}

View File

@ -1,15 +0,0 @@
<h2 mat-dialog-title>Mover clientes a:</h2>
<mat-dialog-content>
<mat-form-field appearance="fill" class="full-width">
<mat-label>Seleccione aula</mat-label>
<mat-select [(ngModel)]="newOU">
<mat-option *ngFor="let unit of units" [value]="unit">{{ unit.name }}</mat-option>
</mat-select>
</mat-form-field>
</mat-dialog-content>
<div class="action-container">
<button class="ordinary-button" (click)="close()">Cancelar</button>
<button class="submit-button" (click)="save()" [disabled]="!newOU">Continuar</button>
</div>

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