import {Component, OnInit, ViewChild} from '@angular/core'; import { DataService } from './services/data.service'; import { ClientCollection, UnidadOrganizativa } from './model/model'; import { MatDialog } from '@angular/material/dialog'; import { CreateOrganizationalUnitComponent } from './shared/organizational-units/create-organizational-unit/create-organizational-unit.component'; import { DeleteModalComponent } from '../../shared/delete_modal/delete-modal/delete-modal.component'; import { CreateClientComponent } from './shared/clients/create-client/create-client.component'; import { EditOrganizationalUnitComponent } from './shared/organizational-units/edit-organizational-unit/edit-organizational-unit.component'; import { EditClientComponent } from './shared/clients/edit-client/edit-client.component'; import { ShowOrganizationalUnitComponent} from "./shared/organizational-units/show-organizational-unit/show-organizational-unit.component"; import {ToastrService} from "ngx-toastr"; import {TreeViewComponent} from "./shared/tree-view/tree-view.component"; import {MatBottomSheet} from "@angular/material/bottom-sheet"; import {LegendComponent} from "./shared/legend/legend.component"; import { ClassroomViewDialogComponent } from './shared/classroom-view/classroom-view-modal'; import {HttpClient} from "@angular/common/http"; import {PageEvent} from "@angular/material/paginator"; import { SaveFiltersDialogComponent } from './shared/save-filters-dialog/save-filters-dialog.component'; import { AcctionsModalComponent } from './shared/acctions-modal/acctions-modal.component'; import {MatTableDataSource} from "@angular/material/table"; import {DatePipe} from "@angular/common"; import {AdvancedSearchComponent} from "./components/advanced-search/advanced-search.component"; import {MatTabChangeEvent} from "@angular/material/tabs"; import {ClientTabViewComponent} from "./components/client-tab-view/client-tab-view.component"; import { OrganizationalUnitTabViewComponent } from "./components/organizational-unit-tab-view/organizational-unit-tab-view.component"; @Component({ selector: 'app-groups', templateUrl: './groups.component.html', styleUrls: ['./groups.component.css'] }) export class GroupsComponent implements OnInit { baseUrl: string = import.meta.env.NG_APP_BASE_API_URL; dataSource = new MatTableDataSource(); organizationalUnits: UnidadOrganizativa[] = []; selectedUnidad: UnidadOrganizativa | null = null; selectedDetail: any | null = null; children: any[] = []; breadcrumb: string[] = []; clientsData: any[] = []; breadcrumbData: any[] = []; loading:boolean = false; loadingChildren:boolean = false; searchTerm: string = ''; selectedFilter1: string = 'none'; selectedFilter2: string = 'none'; selectedFilterOS: string[] = []; selectedFilterStatus: string[] = []; filterIP: string = ''; filterMAC: string = ''; filterName: string = ''; filteredResults: any[] = []; savedFilterNames: any[] = []; length: number = 0; itemsPerPage: number = 10; page: number = 1; pageSizeOptions: number[] = [5, 10, 25, 100]; selectedElements: any[] = []; isAllSelected: boolean = false; filters: { [key: string]: string } = {}; datePipe: DatePipe = new DatePipe('es-ES'); constructor( private dataService: DataService, public dialog: MatDialog, private toastService: ToastrService, private _bottomSheet: MatBottomSheet, private http: HttpClient ) {} ngOnInit(): void { this.search(); this.getFilters(); } @ViewChild('clientTab') clientTabComponent!: ClientTabViewComponent; @ViewChild('organizationalUnitTab') organizationalUnitTabComponent!: OrganizationalUnitTabViewComponent; onTabChange(event: MatTabChangeEvent) { switch (event.index) { case 2: this.clientTabComponent.search(); break; case 3: this.organizationalUnitTabComponent.search(); break; default: break; } } getFilters(): void { this.dataService.getFilters().subscribe( data => { this.savedFilterNames = data.map((filter: any) => [filter.name, filter.uuid]); }, error => { console.error('Error fetching filters:', error); } ); } search(): void { this.loading = true; this.dataService.getOrganizationalUnits(this.searchTerm).subscribe( data => { this.organizationalUnits = data; this.loading = false; }, error => { console.error('Error fetching unidades organizativas', error); this.loading = false; } ); } onSelectUnidad(unidad: UnidadOrganizativa): void { this.selectedUnidad = unidad; this.selectedDetail = unidad; this.breadcrumb = [unidad.name]; this.breadcrumbData = [unidad]; this.loadChildrenAndClients(unidad.id); } onSelectChild(child: any): void { this.selectedDetail = child; if (child.type !== 'client' && child.uuid && child.id) { this.breadcrumb.push(child.name || child.name); this.breadcrumbData.push(child); this.loadChildrenAndClients(child.id); } } navigateToBreadcrumb(index: number): void { this.breadcrumb = this.breadcrumb.slice(0, index + 1); const target = this.breadcrumbData[index]; this.breadcrumbData = this.breadcrumbData.slice(0, index + 1); if (target.type === 'client') { this.selectedDetail = target; } else { this.loadChildrenAndClients(target.id); } } loadChildrenAndClients(id: string): void { this.loadingChildren = true this.dataService.getChildren(id).subscribe( childrenData => { this.dataService.getClients(id).subscribe( clientsData => { this.clientsData = clientsData; const newChildren = [...childrenData, ...clientsData]; if (newChildren.length > 0) { this.children = newChildren; } else { this.children = []; } this.loadingChildren = false }, error => { console.error('Error fetching clients', error); this.clientsData = []; this.children = []; this.loadingChildren = false } ); }, error => { console.error('Error fetching children', error); this.children = []; this.loadingChildren = false } ); } addOU(event: MouseEvent, parent:any = null): void { event.stopPropagation(); const dialogRef = this.dialog.open(CreateOrganizationalUnitComponent, { data: { parent }, width: '900px'}); dialogRef.afterClosed().subscribe(() => { this.dataService.getOrganizationalUnits().subscribe( data => { this.organizationalUnits = data this.loadChildrenAndClients(parent?.id); }, error => console.error('Error fetching unidades organizativas', error) ); }); } addClient(event: MouseEvent, organizationalUnit: any = null): void { event.stopPropagation(); const dialogRef = this.dialog.open(CreateClientComponent, { data: { organizationalUnit }, width: '900px' }); dialogRef.afterClosed().subscribe(() => { this.dataService.getOrganizationalUnits().subscribe( data => { this.organizationalUnits = data; if (organizationalUnit && organizationalUnit.id) { this.loadChildrenAndClients(organizationalUnit.id); } }, error => console.error('Error fetching unidades organizativas', error) ); }); } onDeleteClick(event: MouseEvent, uuid: string, name: string, type: string): void { event.stopPropagation(); if (type === 'client') { const dialogRef = this.dialog.open(DeleteModalComponent, { width: '400px', data: { name } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.dataService.deleteElement(uuid, type).subscribe( () => { this.loadChildrenAndClients(this.selectedUnidad?.id || ''); this.dataService.getOrganizationalUnits().subscribe( data => this.organizationalUnits = data, error => console.error('Error fetching unidades organizativas', error) ); this.openSnackBar(false, 'Entidad eliminada exitosamente') }, error => { console.error('Error deleting element', error) this.openSnackBar(true, error.error['hydra:description']) } ); } }); } else { const dialogDeleteGroupRef = this.dialog.open(DeleteModalComponent, { width: '400px', data: { name } }); dialogDeleteGroupRef.afterClosed().subscribe(result => { if (result && result === 'delete') { this.dataService.deleteElement(uuid, type).subscribe( () => { this.loadChildrenAndClients(this.selectedUnidad?.id || ''); this.dataService.getOrganizationalUnits().subscribe( data => this.organizationalUnits = data, error => console.error('Error fetching unidades organizativas', error) ); this.openSnackBar(false, 'Entidad eliminada exitosamente') }, error => { console.error('Error deleting element', error) this.openSnackBar(true, error.error['hydra:description']) } ); } else if (result && result === 'change') { this.dataService.changeParent(uuid).subscribe( () => { this.loadChildrenAndClients(this.selectedUnidad?.id || ''); this.dataService.getOrganizationalUnits().subscribe( data => this.organizationalUnits = data, error => console.error('Error fetching unidades organizativas', error) ); this.openSnackBar(false, 'Entidad eliminada exitosamente') }, error => { console.error('Error deleting element', error) this.openSnackBar(true, error.error['hydra:description']) } ); } }); } } onEditClick(event: MouseEvent, type: any, uuid: string): void { event.stopPropagation(); if (type != "client") { const dialogRef = this.dialog.open(EditOrganizationalUnitComponent, { data: { uuid }, width: '900px'}); } else { const dialogRef = this.dialog.open(EditClientComponent, { data: { uuid }, width: '900px' } ); } } onShowClick(event: MouseEvent, data: any): void { event.stopPropagation(); if (data.type != "client") { const dialogRef = this.dialog.open(ShowOrganizationalUnitComponent, { data: { data }, width: '700px'}); } } onTreeClick(event: MouseEvent, data: any): void { event.stopPropagation(); if (data.type != "client") { const dialogRef = this.dialog.open(TreeViewComponent, { data: { data }, width: '800px'}); } } openSnackBar(isError: boolean, message: string) { if (isError) { this.toastService.error(' Error al eliminar la entidad: ' + message, 'Error'); } else this.toastService.success(message, 'Éxito'); } openBottomSheet(): void { this._bottomSheet.open(LegendComponent); } roomMap(): void { if (this.selectedDetail && this.selectedDetail.type === 'classroom') { const dialogRef = this.dialog.open(ClassroomViewDialogComponent, { width: '90vw', data: { clients: this.clientsData } }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); }); } } applyFilter() { this.dataService.getFilteredResults(this.selectedFilter1, this.selectedFilter2, this.filterName, this.filterIP, this.filterMAC, this.page, this.itemsPerPage) .subscribe( response => { this.filteredResults = response.results; this.length = response.total; }, error => { console.error('Error al obtener los resultados filtrados', error); this.filteredResults = []; } ); } onPageChange(event: PageEvent) { this.page = event.pageIndex; this.itemsPerPage = event.pageSize; this.applyFilter(); } saveFilters() { const dialogRef = this.dialog.open(SaveFiltersDialogComponent); dialogRef.afterClosed().subscribe(result => { if (result) { const filters = { name: result, favourite: true, filters: { filter0: this.filterName, filter1: this.selectedFilter1, filter2: this.selectedFilter2, filter3: this.selectedFilterOS, filter4: this.selectedFilterStatus, filter5: this.filterIP, filter6: this.filterMAC, } }; this.http.post(`${this.baseUrl}/views`, filters).subscribe(response => { console.log('Response from server:', response); this.toastService.success('Se ha guardado el filtro correctamente'); }, error => { console.error('Error:', error); this.toastService.error(error); }); } }); } loadSelectedFilter(savedFilter: any) { const url = `${this.baseUrl}/views/` + savedFilter[1]; console.log('llamando a:', url); this.dataService.getFilter(savedFilter[1]).subscribe(response => { console.log('Response from server:', response.filters); if (response) { console.log('Filter1:', response.filters); this.filterName = response.filters.filter0 || ''; this.selectedFilter1 = response.filters.filter1 || null; this.selectedFilter2 = response.filters.filter2 || ''; this.selectedFilterOS = response.filters.filter3 || []; this.selectedFilterStatus = response.filters.filter4 || []; this.filterIP = response.filters.filter5 || ''; this.filterMAC = response.filters.filter6 || ''; this.applyFilter(); } }, error => { console.error('Error:', error); }); } onCheckboxChange(event: any, name: string, uuid: string) { if (event.checked) { this.selectedElements.push(uuid); } else { const index = this.selectedElements.indexOf(name); if (index > -1) { this.selectedElements.splice(index, 1); } } this.isAllSelected = this.selectedElements.length === this.filteredResults.length; } toggleSelectAll() { this.isAllSelected = !this.isAllSelected; if (this.isAllSelected) { this.selectedElements = this.filteredResults.map(result => result.uuid); } else { this.selectedElements = []; } } isSelected(name: string): boolean { return this.selectedElements.includes(name); } sendActions() { const dialogRef = this.dialog.open(AcctionsModalComponent, { data: { selectedElements: this.selectedElements }, width: '700px'}); } }