oggui/ogWebconsole/src/app/components/ogboot/pxe-boot-files/pxe-boot-files.component.ts

257 lines
8.1 KiB
TypeScript

import { inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';
import { JoyrideService } from 'ngx-joyride';
import {MatTableDataSource} from "@angular/material/table";
import { ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { DeleteModalComponent } from 'src/app/shared/delete_modal/delete-modal/delete-modal.component';
import { forkJoin } from 'rxjs';
import { DataService as GroupsDataService } from '../../groups/services/data.service';
@Component({
selector: 'app-pxe-boot-files',
templateUrl: './pxe-boot-files.component.html',
styleUrls: ['./pxe-boot-files.component.css']
})
export class PxeBootFilesComponent implements OnInit {
public translate = inject(TranslateService);
baseUrl: string;
availableOrganizationalUnits: any[] = [];
selectedUnitChildren: any[] = [];
dataSource = new MatTableDataSource<any>();
taskForm: FormGroup;
units: any[] = [];
selectedUnit: any = null;
bootServers: any[] = [];
@Input() selectedServerId: string | null = null;
isFromDashboard: boolean = false;
ogLiveOptions: any[] = [];
globalOgLive: string | null = null;
unitSearchText: string = '';
length: number = 0;
itemsPerPage: number = 10;
page: number = 0;
pageSizeOptions: number[] = [5, 10, 20, 40, 100];
filters: any = {};
displayedColumns: string[] = ['id', 'ip', 'mac', 'name', 'bootServer', 'ogLive'];
constructor(
private fb: FormBuilder,
private http: HttpClient,
private toastService: ToastrService,
private configService: ConfigService,
private joyrideService: JoyrideService,
private route: ActivatedRoute,
private dialog: MatDialog,
private groupsDataService: GroupsDataService
) {
this.baseUrl = this.configService.apiUrl;
this.taskForm = this.fb.group({
organizationalUnit: ['', Validators.required],
selectedChild: ['', Validators.required]
});
}
ngOnInit(): void {
if (this.selectedServerId) {
this.isFromDashboard = true;
this.onServerChange();
} else {
const serverIdParam = this.route.snapshot.queryParamMap.get('serverId');
if (serverIdParam) {
this.selectedServerId = serverIdParam;
this.isFromDashboard = true;
this.onServerChange();
}
}
this.loadBootServers();
this.loadUnits()
}
loadBootServers(): void {
const url = `${this.baseUrl}/boot-servers?page=1&itemsPerPage=10000`;
this.http.get<any>(url).subscribe(
response => {
this.bootServers = response['hydra:member'];
if (this.bootServers.length > 0 && !this.selectedServerId) {
this.selectedServerId = this.bootServers[0].uuid || this.bootServers[0]['@id'].split('/').pop();
this.onServerChange();
}
},
error => {
console.error(this.translate.instant('fetchingBootserversError'), error);
}
);
}
onServerChange(): void {
this.filters['bootServer.uuid'] = this.selectedServerId!;
this.page = 0;
this.fetchPxeTemplates();
}
loadUnits() {
this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe(
response => {
const rawUnits = response['hydra:member'];
this.units = rawUnits
.filter((unit: any) => unit.type === 'classroom')
.map((unit: any) => ({
...unit,
path: this.groupsDataService.getOrganizationalUnitPath(unit, rawUnits)
}));
this.units.sort((a, b) => {
const pathA = a.path || a.name;
const pathB = b.path || b.name;
return pathA.localeCompare(pathB);
});
},
error => console.error(this.translate.instant('errorFetchingOrganizationalUnits1'), error)
);
}
fetchPxeTemplates(): void {
this.http.get<any>(`${this.baseUrl}/pxe-templates?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters })
.subscribe(
response => {
this.ogLiveOptions = response['hydra:member'];
this.length = response['hydra:totalItems'];
},
error => {
this.toastService.error(this.translate.instant('errorLoadingTemplates'));
}
);
}
loadChildUnits(event: any) {
let unitId = event.value;
if (typeof event.value === 'object' && event.value !== null) {
unitId = event.value.id;
} else if (typeof event.value === 'string' && event.value.includes('/')) {
unitId = event.value.split('/').pop();
}
this.selectedUnit = this.units.find(u => u.id == unitId || u['@id'] === event.value) || event.value;
this.refreshClientList();
}
refreshClientList(): void {
if (!this.selectedUnit) return;
this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${this.selectedUnit.id}`).subscribe(
response => {
this.dataSource.data = response['hydra:member'].map((client: any) => ({
...client,
ogLive: client.pxeTemplate ? client.pxeTemplate['@id'] : null
}));
},
error => console.error(this.translate.instant('errorFetchingChildUnits'), error)
);
}
applyToAll(): void {
this.dataSource.data = this.dataSource.data.map(client => ({
...client,
ogLive: this.globalOgLive || client.ogLive
}));
}
saveOgLiveTemplates(): void {
let hasDifferentServer = false;
// Check for clients with different boot server
this.dataSource.data.forEach(client => {
if (client.ogLive && client.bootServer?.uuid !== this.selectedServerId) {
hasDifferentServer = true;
}
});
if (hasDifferentServer) {
const dialogRef = this.dialog.open(DeleteModalComponent, {
width: '500px',
data: {
title : this.translate.instant('confirmServerMigration'),
message : this.translate.instant('associatedComputersHaveBeenDetected'),
confirmText: 'Mover y Guardar',
cancelText: 'Solo de este servidor'
}
});
dialogRef.afterClosed().subscribe(result => {
// result is true if YES, false if NO, undefined if closed
if (result === undefined) return;
this.processSave(result);
});
} else {
this.processSave(true);
}
}
private processSave(moveClients: boolean): void {
const groupedByTemplate: { [key: string]: string[] } = {};
this.dataSource.data.forEach(client => {
if (client.ogLive) {
// Decide whether to include this client
const isSameServer = client.bootServer?.uuid === this.selectedServerId;
if (!isSameServer && !moveClients) {
return; // Skip if user said NO to moving
}
if (!groupedByTemplate[client.ogLive]) {
groupedByTemplate[client.ogLive] = [];
}
groupedByTemplate[client.ogLive].push(client['@id']);
}
});
const templateIds = Object.keys(groupedByTemplate);
if (templateIds.length === 0) {
this.toastService.info(this.translate.instant('noChangesPending'));
return;
}
const requests = templateIds.map(templateId => {
const clients = groupedByTemplate[templateId];
const url = `${this.baseUrl}${templateId}/add-clients`;
const payload = { clients: clients };
return this.http.post(url, payload);
});
forkJoin(requests).subscribe({
next: () => {
this.toastService.success(`Clientes guardados correctamente`);
this.refreshClientList();
},
error: () => {
this.toastService.error(`Error al guardar clientes`);
}
});
}
iniciarTour(): void {
this.joyrideService.startTour({
steps: [
'titleStep',
'selectUnitStep',
'selectClassStep',
'applyToAllStep',
'saveButtonStep',
'tableStep',
'selectTemplateStep'
],
showPrevButton: true,
themeColor: '#3f51b5'
});
}
}