oggui/ogWebconsole/src/app/components/ogdhcp/og-dhcp-subnets.component.ts

355 lines
11 KiB
TypeScript

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { CreateSubnetComponent } from './create-subnet/create-subnet.component';
import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { AddClientsToSubnetComponent } from './add-clients-to-subnet/add-clients-to-subnet.component';
import { ServerInfoDialogComponent } from "./server-info-dialog/server-info-dialog.component";
import { Observable, of } from "rxjs";
import { JoyrideService } from 'ngx-joyride';
import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { ShowClientsComponent } from "./show-clients/show-clients.component";
import { ConfigService } from '@services/config.service';
import { ActivatedRoute } from '@angular/router';
import { SyncSubnetDialogComponent } from "./sync-subnet-dialog/sync-subnet-dialog.component";
import { SyncResultDialogComponent } from "./sync-result-dialog/sync-result-dialog.component";
export interface Subnet {
'@id': string;
'@type': string;
name: string;
netmask: string;
ipAddress: string;
nextServer: string;
router: string;
bootFileName: string;
synchronized: boolean;
serverId: number;
clients: [];
createdAt: string;
createdBy: string;
uuid: string;
id: number;
}
@Component({
selector: 'app-ogdhcp',
templateUrl: './og-dhcp-subnets.component.html',
styleUrls: ['./og-dhcp-subnets.component.css']
})
export class OgDhcpSubnetsComponent implements OnInit {
baseUrl: string;
displayedColumns: string[] = ['id', 'name', 'netmask', 'ipAddress', 'synchronized', 'serverId', 'clients', 'actions'];
dataSource = new MatTableDataSource<Subnet>([]);
length = 0;
itemsPerPage: number = 10;
page = 0;
filters: { [key: string]: string } = {};
pageSizeOptions: number[] = [5, 10, 20];
alertMessage: string | null = null;
loading: boolean = false;
serverId: string | null = null;
serverName: string = '';
@ViewChild(MatPaginator) paginator: MatPaginator | undefined;
columns = [
{ columnDef: 'id', header: 'ID', cell: (subnet: Subnet) => subnet.id },
{ columnDef: 'name', header: 'Name', cell: (subnet: Subnet) => subnet.name },
{ columnDef: 'netmask', header: 'Netmask', cell: (subnet: Subnet) => subnet.netmask },
{ columnDef: 'ipAddress', header: 'IP Address', cell: (subnet: Subnet) => subnet.ipAddress },
{ columnDef: 'synchronized', header: 'Sincronizado', cell: (subnet: Subnet) => `${subnet.synchronized}` },
{ columnDef: 'serverId', header: 'Id Servidor DHCP', cell: (subnet: Subnet) => subnet.serverId },
{ columnDef: 'clients', header: 'Lista de clientes', cell: (subnet: Subnet) => `${subnet.clients}` },
];
private apiUrl: string;
constructor(public dialog: MatDialog, private http: HttpClient, private toastService: ToastrService,
private joyrideService: JoyrideService, private configService: ConfigService, private route: ActivatedRoute) {
this.baseUrl = this.configService.apiUrl;
this.apiUrl = `${this.baseUrl}/subnets`;
}
ngOnInit() {
this.route.queryParams.subscribe(params => {
if (params['serverId']) {
this.serverId = params['serverId'];
this.filters['dhcpServer.uuid'] = params['serverId'];
this.loadServerName();
}
this.loadAlert();
this.loadSubnets();
});
}
loadServerName() {
this.http.get<any>(`${this.baseUrl}/dhcp-servers/${this.serverId}`).subscribe({
next: (response) => {
this.serverName = response.name;
},
error: () => {
console.error('No se pudo resolver el nombre del servidor DHCP');
}
});
}
loadSubnets() {
this.loading = true;
let url = `${this.baseUrl}/subnets?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`;
// Añadir filtros a la URL
Object.keys(this.filters).forEach(key => {
if (this.filters[key]) {
url += `&${key}=${this.filters[key]}`;
}
});
this.http.get<any>(url).subscribe({
next: (response) => {
this.dataSource.data = response['hydra:member'];
this.length = response['hydra:totalItems'];
this.loading = false;
},
error: error => {
const errorMsg = error.error?.['hydra:description'] || 'Error al cargar subredes';
this.toastService.error(errorMsg);
this.loading = false;
}
});
if (this.paginator) {
this.dataSource.paginator = this.paginator;
}
}
search() {
this.page = 0;
this.loadSubnets();
}
toggleAction(subnet: any, action: string): void {
switch (action) {
case 'get':
this.http.post(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/get`, {}).subscribe({
next: () => {
this.toastService.success('Subred sincronizada con servidor');
this.loadSubnets()
},
error: (error) => {
console.error('Error al crear subred en servidor', error);
this.toastService.error(error.error['hydra:description']);
}
});
break;
case 'post':
this.http.post(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/post`, {}).subscribe({
next: () => {
this.toastService.success('Petición de instalación enviada');
this.loadSubnets()
},
error: (error) => {
console.error('Error al crear subred en servidor', error);
this.toastService.error(error.error['hydra:description']);
}
});
break;
case 'put':
this.http.put(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/put`, {}).subscribe({
next: () => {
this.toastService.success('Petición de actualizacion enviada');
this.loadSubnets();
},
error: (error) => {
console.error('Error al actualizar la subred en el servidor', error);
this.toastService.error(error.error['hydra:description']);
}
});
break;
case 'delete':
const dialogRef = this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: subnet.name }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.http.delete(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/delete`, {}).subscribe({
next: () => {
this.toastService.success('Subred eliminada exitosamente');
this.loadSubnets();
},
error: (error) => {
console.error('Error al eliminar la subred', error);
this.toastService.error(error.error['hydra:description']);
}
});
}
})
break;
default:
console.error('Acción no soportada:', action);
break;
}
}
addSubnet() {
const dialogRef = this.dialog.open(CreateSubnetComponent, {
width: '600px',
data: { serverUuid: this.serverId }
});
dialogRef.afterClosed().subscribe(result => {
this.loadSubnets()
});
}
editSubnet(subnet: Subnet) {
const dialogRef = this.dialog.open(CreateSubnetComponent, {
width: '600px',
data: subnet
});
dialogRef.afterClosed().subscribe(result => {
this.loadSubnets()
});
}
loadAlert(): Observable<any> {
if (this.serverId) {
return this.http.post<any>(`${this.baseUrl}/dhcp-servers/${this.serverId}/get-collection`, {});
}
return of({message: 'Seleccione un servidor DHCP para consultar el estado'});
}
syncSubnets(): void {
if (!this.serverId) {
this.toastService.error('Debe seleccionar un servidor DHCP para sincronizar');
return;
}
const dialogRef = this.dialog.open(SyncSubnetDialogComponent, {
width: '600px',
data: { serverUuid: this.serverId }
});
dialogRef.afterClosed().subscribe(result => {
if (result === undefined) {
return; // dialog cancelled
}
this.loading = true;
const payload = result.parentOuId ? { parentOuId: result.parentOuId } : {};
this.http.post(`${this.baseUrl}/dhcp-servers/${this.serverId}/sync`, payload).subscribe({
next: (response: any) => {
this.dialog.open(SyncResultDialogComponent, {
width: '600px',
data: { skippedClients: response.skipped_clients || [] }
});
this.loadSubnets();
},
error: (error) => {
console.error('Error al sincronizar subredes', error);
this.toastService.error(error.error?.['hydra:description'] || 'Error al sincronizar subredes');
this.loading = false;
}
});
});
}
openSubnetInfoDialog() {
this.loading = true;
this.loadAlert().subscribe(
response => {
this.alertMessage = response.message;
this.dialog.open(ServerInfoDialogComponent, {
width: '600px',
data: {
message: this.alertMessage
}
});
this.loading = false;
},
error => {
this.toastService.error(error.error['hydra:description']);
console.error('Error al cargar la información del alert', error);
this.loading = false;
}
);
}
openShowClientsDialog(subnet: Subnet) {
const dialogRef = this.dialog.open(ShowClientsComponent, {
width: '85vw',
height: '85vh',
maxWidth: '85vw',
maxHeight: '85vh',
data: { subnetId: subnet.id, subnetName: subnet.name, subnetUuid: subnet.uuid }
});
dialogRef.afterClosed().subscribe(result => {
this.loadSubnets();
});
}
deleteSubnetLeases(subnet: Subnet) {
const dialogRef = this.dialog.open(DeleteModalComponent, {
width: '300px',
data: { name: `leases de ${subnet.name}` }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.http.delete(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/delete-leases`, {}).subscribe({
next: () => {
this.toastService.success('Leases de la subred eliminadas correctamente');
},
error: (error) => {
this.toastService.error(error.error?.['hydra:description'] || 'Error al eliminar leases de la subred');
}
});
}
});
}
addClientsToSubnet(subnet: Subnet) {
const dialogRef = this.dialog.open(AddClientsToSubnetComponent, {
width: '800px',
data: { subnetUuid: subnet.uuid, subnetName: subnet.name }
});
dialogRef.afterClosed().subscribe(result => {
this.loadSubnets();
});
}
onPageChange(event: any) {
this.page = event.pageIndex;
this.itemsPerPage = event.pageSize;
this.loadSubnets();
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'addSubnetStep',
'searchNameStep',
'searchNetmaskStep',
'searchIpStep',
'searchBootFileStep',
'tableStep',
'actionsStep',
'paginationStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}