Editar uo y clientes modales

pull/4/head
Alvaro Puente Mella 2024-06-25 13:44:13 +02:00
parent 4f651c68c3
commit d64a55ba0d
18 changed files with 654 additions and 42 deletions

View File

@ -40,6 +40,8 @@ import {MatStepperModule} from '@angular/material/stepper';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { CreateClientComponent } from './components/groups/clients/create-client/create-client.component';
import { DeleteModalComponent } from './components/groups/delete-modal/delete-modal.component';
import { EditOrganizationalUnitComponent } from './components/groups/organizational-units/edit-organizational-unit/edit-organizational-unit.component';
import { EditClientComponent } from './components/groups/clients/edit-client/edit-client.component';
@NgModule({ declarations: [
@ -62,7 +64,9 @@ import { DeleteModalComponent } from './components/groups/delete-modal/delete-mo
GroupsComponent,
CreateOrganizationalUnitComponent,
CreateClientComponent,
DeleteModalComponent
DeleteModalComponent,
EditOrganizationalUnitComponent,
EditClientComponent
],
bootstrap: [AppComponent],
imports: [BrowserModule,

View File

@ -1,13 +1,19 @@
<h1 mat-dialog-title>Añadir Cliente</h1>
<div mat-dialog-content>
<form [formGroup]="clientForm" class="client-form">
<mat-form-field class="form-field">
<mat-label>Padre</mat-label>
<mat-select formControlName="organizationalUnit">
<mat-option *ngFor="let unit of parentUnits" [value]="unit['@id']">{{ unit.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Nombre</mat-label>
<input matInput formControlName="name" required>
<input matInput formControlName="name" >
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Número de Serie</mat-label>
<input matInput formControlName="serialNumber" required>
<input matInput formControlName="serialNumber" >
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Interfaz de Red</mat-label>
@ -19,23 +25,18 @@
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>MAC</mat-label>
<input matInput formControlName="mac" required pattern="^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$">
<input matInput formControlName="mac" >
<mat-error>Formato de MAC inválido. Ejemplo válido: 00:11:22:33:44:55</mat-error>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Dirección IP</mat-label>
<input matInput formControlName="ip" required pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$">
<input matInput formControlName="ip">
<mat-error>Formato de dirección IP inválido. Ejemplo válido: 127.0.0.1</mat-error>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Estado</mat-label>
<input matInput formControlName="status">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Unidad Organizativa</mat-label>
<input matInput formControlName="organizationalUnit" type="url">
<mat-error>Formato de URL inválido.</mat-error>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Menú URL</mat-label>
<input matInput formControlName="menu" type="url">

View File

@ -1,3 +1,4 @@
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
@ -9,32 +10,56 @@ import { MatDialogRef } from '@angular/material/dialog';
})
export class CreateClientComponent implements OnInit {
clientForm!: FormGroup;
parentUnits: any[] = []; // Array to store parent units fetched from API
constructor(
private fb: FormBuilder,
private dialogRef: MatDialogRef<CreateClientComponent>
private dialogRef: MatDialogRef<CreateClientComponent>,
private http: HttpClient
) { }
ngOnInit(): void {
this.loadParentUnits(); // Load parent units when component initializes
this.clientForm = this.fb.group({
organizationalUnit: [''],
name: ['', Validators.required],
serialNumber: ['', Validators.required],
netiface: [''],
netDriver: [''],
mac: ['', [Validators.required, Validators.pattern('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$')]],
ip: ['', [Validators.required, Validators.pattern('^([0-9]{1,3}\.){3}[0-9]{1,3}$')]],
status: [''],
organizationalUnit: ['', Validators.pattern('https?://.+')],
menu: ['', Validators.pattern('https?://.+')],
hardwareProfile: ['', Validators.pattern('https?://.+')],
serialNumber: [''],
netiface: "eth0",
netDriver: "e1000e",
mac: "00:11:22:33:44:55",
ip: "127.0.0.1",
status: "test",
menu: null,
hardwareProfile: null,
});
}
loadParentUnits() {
const url = 'http://127.0.0.1:8080/organizational-units?page=1&itemsPerPage=30';
this.http.get<any>(url).subscribe(
response => {
this.parentUnits = response['hydra:member'];
},
error => {
console.error('Error fetching parent units:', error);
}
);
}
onSubmit() {
console.log('Form data:', this.clientForm.value);
if (this.clientForm.valid) {
const formData = this.clientForm.value;
console.log('Form Data:', formData);
this.dialogRef.close(formData);
this.http.post('http://127.0.0.1:8080/clients', formData).subscribe(
response => {
console.log('Response from POST:', response);
this.dialogRef.close(response);
},
error => {
console.error('Error during POST:', error);
}
);
}
}

View File

@ -0,0 +1,39 @@
h1 {
text-align: center;
font-family: 'Roboto', sans-serif;
font-weight: 400;
color: #3f51b5;
margin-bottom: 20px;
}
.network-form {
display: flex;
flex-direction: column;
gap: 15px;
}
.form-field {
width: 100%;
margin-top: 10px;
}
.mat-dialog-content {
padding: 20px;
}
.mat-dialog-actions {
display: flex;
justify-content: flex-end;
padding: 10px 20px;
}
button {
text-transform: none;
font-size: 16px;
font-weight: 500;
}
.mat-slide-toggle {
margin-top: 20px;
}

View File

@ -0,0 +1,19 @@
<h1 mat-dialog-title>Editar Cliente</h1>
<div mat-dialog-content>
<form [formGroup]="clientForm" class="client-form">
<mat-form-field class="form-field">
<mat-label>Padre</mat-label>
<mat-select formControlName="organizationalUnit">
<mat-option *ngFor="let unit of parentUnits" [value]="unit['@id']">{{ unit.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Nombre</mat-label>
<input matInput formControlName="name" >
</mat-form-field>
</form>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancelar</button>
<button mat-button [disabled]="!clientForm.valid" (click)="onSubmit()">Añadir</button>
</div>

View File

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

View File

@ -0,0 +1,70 @@
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { CreateClientComponent } from '../create-client/create-client.component';
@Component({
selector: 'app-edit-client',
templateUrl: './edit-client.component.html',
styleUrl: './edit-client.component.css'
})
export class EditClientComponent {
clientForm!: FormGroup;
parentUnits: any[] = []; // Array to store parent units fetched from API
constructor(
private fb: FormBuilder,
private dialogRef: MatDialogRef<CreateClientComponent>,
private http: HttpClient
) { }
ngOnInit(): void {
this.loadParentUnits(); // Load parent units when component initializes
this.clientForm = this.fb.group({
organizationalUnit: [''],
name: ['', Validators.required],
serialNumber: [''],
netiface: "eth0",
netDriver: "e1000e",
mac: "00:11:22:33:44:55",
ip: "127.0.0.1",
status: "test",
menu: null,
hardwareProfile: null,
});
}
loadParentUnits() {
const url = 'http://127.0.0.1:8080/organizational-units?page=1&itemsPerPage=30';
this.http.get<any>(url).subscribe(
response => {
this.parentUnits = response['hydra:member'];
},
error => {
console.error('Error fetching parent units:', error);
}
);
}
onSubmit() {
console.log('Form data:', this.clientForm.value);
if (this.clientForm.valid) {
const formData = this.clientForm.value;
this.http.post('http://127.0.0.1:8080/clients', formData).subscribe(
response => {
console.log('Response from POST:', response);
this.dialogRef.close(response);
},
error => {
console.error('Error during POST:', error);
}
);
}
}
onNoClick(): void {
this.dialogRef.close();
}
}

View File

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

View File

@ -0,0 +1,30 @@
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-delete-confirm-dialog',
template: `
<h1 mat-dialog-title>Eliminar</h1>
<div mat-dialog-content>
<p>¿Estás seguro que deseas eliminar {{data.name}}?</p>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancelar</button>
<button mat-button (click)="onYesClick()">Eliminar</button>
</div>
`
})
export class DeleteModalComponent {
constructor(
public dialogRef: MatDialogRef<DeleteModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: { name: string }
) {}
onNoClick(): void {
this.dialogRef.close(false);
}
onYesClick(): void {
this.dialogRef.close(true);
}
}

View File

@ -1,6 +1,7 @@
<h2>Crear</h2>
<div class="groups-button-row">
<button mat-flat-button color="primary" (click)="addOU()">Nueva Unidad Organizativa</button>
<button mat-flat-button color="primary" (click)="addClient()">Nuevo Cliente</button>
</div>
<mat-divider></mat-divider>
<h2>Grupos</h2>

View File

@ -4,6 +4,9 @@ import { UnidadOrganizativa } from './model';
import { MatDialog } from '@angular/material/dialog';
import { CreateOrganizationalUnitComponent } from './organizational-units/create-organizational-unit/create-organizational-unit.component';
import { DeleteModalComponent } from './delete-modal/delete-modal.component';
import { CreateClientComponent } from './clients/create-client/create-client.component';
import { EditOrganizationalUnitComponent } from './organizational-units/edit-organizational-unit/edit-organizational-unit.component';
import { EditClientComponent } from './clients/edit-client/edit-client.component';
@Component({
selector: 'app-groups',
@ -41,27 +44,58 @@ export class GroupsComponent implements OnInit {
loadChildrenAndClients(uuid: string): void {
this.dataService.getChildren(uuid).subscribe(
childrenData => {
console.log('Children data:', childrenData); // Depuración
console.log('Children data:', childrenData);
this.dataService.getClients(uuid).subscribe(
clientsData => {
console.log('Clients data:', clientsData); // Depuración
console.log('Clients data:', clientsData);
const newChildren = [...childrenData, ...clientsData];
if (newChildren.length > 0) {
this.children = newChildren;
} else {
// No se encontraron elementos hijos o clientes, revertimos el breadcrumb
this.breadcrumb.pop();
this.children = []; // Limpiar card2 cuando no hay elementos
this.breadcrumb.pop(); // Revertir breadcrumb solo si no hay elementos
// Si deseas que la unidad organizativa se limpie completamente, descomenta la línea siguiente:
// this.selectedUnidad = null;
}
},
error => console.error('Error fetching clients', error)
error => {
console.error('Error fetching clients', error);
this.children = []; // Limpiar card2 en caso de error
}
);
},
error => console.error('Error fetching children', error)
error => {
console.error('Error fetching children', error);
this.children = []; // Limpiar card2 en caso de error
}
);
}
addOU(): void {
this.dialog.open(CreateOrganizationalUnitComponent);
const dialogRef = this.dialog.open(CreateOrganizationalUnitComponent);
// Subscribirse al evento unitAdded del componente de creación después de cerrar el diálogo
dialogRef.afterClosed().subscribe(() => {
// Aquí puedes actualizar las cards o hacer cualquier otra acción necesaria después de añadir una unidad organizativa
this.dataService.getUnidadesOrganizativas().subscribe(
data => this.unidadesOrganizativas = data,
error => console.error('Error fetching unidades organizativas', error)
);
});
}
addClient(): void {
const dialogRef = this.dialog.open(CreateClientComponent);
// Subscribirse al evento unitAdded del componente de creación después de cerrar el diálogo
dialogRef.afterClosed().subscribe(() => {
// Aquí puedes actualizar las cards o hacer cualquier otra acción necesaria después de añadir una unidad organizativa
this.dataService.getUnidadesOrganizativas().subscribe(
data => this.unidadesOrganizativas = data,
error => console.error('Error fetching unidades organizativas', error)
);
});
}
getIcon(type: string): string {
@ -92,6 +126,12 @@ export class GroupsComponent implements OnInit {
this.dataService.deleteElement(uuid, type).subscribe(
() => {
this.loadChildrenAndClients(this.selectedUnidad?.uuid || '');
this.dataService.getUnidadesOrganizativas().subscribe(
data => this.unidadesOrganizativas = data,
error => console.error('Error fetching unidades organizativas', error)
);
},
error => console.error('Error deleting element', error)
);
@ -102,6 +142,15 @@ export class GroupsComponent implements OnInit {
onEditClick(type: any, uuid: string): void {
console.log('Tipo del elemento a editar:', type);
console.log('UUID del elemento a editar:', uuid);
// Aquí puedes agregar lógica adicional para editar el elemento si es necesario
if (type != "client") {
const dialogRef = this.dialog.open(EditOrganizationalUnitComponent, {
data: { type, uuid }
});
} else {
console.log('Editar cliente');
const dialogRef = this.dialog.open(EditClientComponent, {
data: { type, uuid }
});
}
}
}

View File

@ -17,8 +17,10 @@
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Padre</mat-label>
<input matInput formControlName="parent" required>
</mat-form-field>
<mat-select formControlName="parent">
<mat-option *ngFor="let unit of parentUnits" [value]="unit['@id']">{{ unit.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Descripción</mat-label>
<textarea matInput formControlName="description"></textarea>

View File

@ -1,6 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-create-organizational-unit',
@ -13,14 +14,18 @@ export class CreateOrganizationalUnitComponent implements OnInit {
additionalInfoFormGroup: FormGroup;
networkSettingsFormGroup: FormGroup;
types: string[] = ['organizational-unit', 'classrooms-group', 'classroom', 'clients-group'];
parentUnits: any[] = []; // Array to store parent units fetched from API
@Output() unitAdded = new EventEmitter(); // Event emitter to notify parent component about unit addition
constructor(
private _formBuilder: FormBuilder,
private dialogRef: MatDialogRef<CreateOrganizationalUnitComponent>
private dialogRef: MatDialogRef<CreateOrganizationalUnitComponent>,
private http: HttpClient // Inject HttpClient for HTTP requests
) {
this.generalFormGroup = this._formBuilder.group({
name: ['', Validators.required],
parent: ['', Validators.required],
parent: [''],
description: [''],
type: ['', Validators.required]
});
@ -45,19 +50,55 @@ export class CreateOrganizationalUnitComponent implements OnInit {
});
}
ngOnInit() {}
ngOnInit() {
this.loadParentUnits(); // Load parent units when component initializes
}
loadParentUnits() {
const url = 'http://127.0.0.1:8080/organizational-units?page=1&itemsPerPage=30';
this.http.get<any>(url).subscribe(
response => {
this.parentUnits = response['hydra:member'];
},
error => {
console.error('Error fetching parent units:', error);
}
);
}
onSubmit() {
if (this.generalFormGroup.valid && this.additionalInfoFormGroup.valid && this.networkSettingsFormGroup.valid) {
const parentValue = this.generalFormGroup.value.parent;
const formData = {
...this.generalFormGroup.value,
...this.additionalInfoFormGroup.value,
...this.networkSettingsFormGroup.value,
name: this.generalFormGroup.value.name,
parent: parentValue || null,
description: this.generalFormGroup.value.description,
comments: this.additionalInfoFormGroup.value.comments,
type: this.generalFormGroup.value.type
};
console.log('Form Data:', formData);
this.dialogRef.close(formData);
// Realizar la solicitud POST
console.log('POST data:', formData);
const postUrl = 'http://127.0.0.1:8080/organizational-units';
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.post<any>(postUrl, formData, { headers }).subscribe(
response => {
console.log('POST successful:', response);
// Emitir evento para notificar que se ha añadido una nueva unidad
this.unitAdded.emit();
this.dialogRef.close(); // Cerrar el diálogo después de añadir
},
error => {
console.error('Error al realizar POST:', error);
// Manejar el error según sea necesario
}
);
}
}
onNoClick(): void {
this.dialogRef.close();

View File

@ -0,0 +1,39 @@
h1 {
text-align: center;
font-family: 'Roboto', sans-serif;
font-weight: 400;
color: #3f51b5;
margin-bottom: 20px;
}
.network-form {
display: flex;
flex-direction: column;
gap: 15px;
}
.form-field {
width: 100%;
margin-top: 10px;
}
.mat-dialog-content {
padding: 20px;
}
.mat-dialog-actions {
display: flex;
justify-content: flex-end;
padding: 10px 20px;
}
button {
text-transform: none;
font-size: 16px;
font-weight: 500;
}
.mat-slide-toggle {
margin-top: 20px;
}

View File

@ -0,0 +1,116 @@
<h1 mat-dialog-title>Editar Unidad Organizativa</h1>
<div mat-dialog-content>
<mat-stepper orientation="vertical" [linear]="isLinear">
<!-- Step 1: General -->
<mat-step [stepControl]="generalFormGroup">
<form [formGroup]="generalFormGroup">
<ng-template matStepLabel>General</ng-template>
<mat-form-field class="form-field">
<mat-label>Tipo</mat-label>
<mat-select formControlName="type" required>
<mat-option *ngFor="let type of types" [value]="type">{{ type }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Nombre</mat-label>
<input matInput formControlName="name" required>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Padre</mat-label>
<mat-select formControlName="parent">
<mat-option *ngFor="let unit of parentUnits" [value]="unit['@id']">{{ unit.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Descripción</mat-label>
<textarea matInput formControlName="description"></textarea>
</mat-form-field>
<div>
<button mat-button matStepperNext>Siguiente</button>
</div>
</form>
</mat-step>
<!-- Step 2: Información Adicional -->
<mat-step [stepControl]="additionalInfoFormGroup">
<form [formGroup]="additionalInfoFormGroup">
<ng-template matStepLabel>Información Adicional</ng-template>
<mat-form-field class="form-field">
<mat-label>Comentarios</mat-label>
<textarea matInput formControlName="comments"></textarea>
</mat-form-field>
<div>
<button mat-button matStepperPrevious>Atrás</button>
<button mat-button matStepperNext>Siguiente</button>
</div>
</form>
</mat-step>
<!-- Step 3: Configuración de Red -->
<mat-step [stepControl]="networkSettingsFormGroup">
<form [formGroup]="networkSettingsFormGroup">
<ng-template matStepLabel>Configuración de Red</ng-template>
<mat-form-field class="form-field">
<mat-label>Proxy</mat-label>
<input matInput formControlName="proxy">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>DNS</mat-label>
<input matInput formControlName="dns">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Máscara de Red</mat-label>
<input matInput formControlName="netmask">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Router</mat-label>
<input matInput formControlName="router">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>NTP</mat-label>
<input matInput formControlName="ntp">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Modo P2P</mat-label>
<input matInput formControlName="p2pMode">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Tiempo P2P</mat-label>
<input matInput formControlName="p2pTime" type="number">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>IP Multicast</mat-label>
<input matInput formControlName="mcastIp">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Velocidad Multicast</mat-label>
<input matInput formControlName="mcastSpeed" type="number">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Puerto Multicast</mat-label>
<input matInput formControlName="mcastPort" type="number">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Modo Multicast</mat-label>
<input matInput formControlName="mcastMode">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Menú URL</mat-label>
<input matInput formControlName="menu" type="url">
</mat-form-field>
<mat-form-field class="form-field">
<mat-label>Perfil de Hardware</mat-label>
<input matInput formControlName="hardwareProfile" type="url">
</mat-form-field>
<mat-slide-toggle formControlName="validation">Validación</mat-slide-toggle>
<div>
<button mat-button matStepperPrevious>Atrás</button>
<button mat-button (click)="onSubmit()" [disabled]="!networkSettingsFormGroup.valid">Añadir</button>
</div>
</form>
</mat-step>
</mat-stepper>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancelar</button>
</div>

View File

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

View File

@ -0,0 +1,107 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, EventEmitter, Output } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { CreateOrganizationalUnitComponent } from '../create-organizational-unit/create-organizational-unit.component';
@Component({
selector: 'app-edit-organizational-unit',
templateUrl: './edit-organizational-unit.component.html',
styleUrl: './edit-organizational-unit.component.css'
})
export class EditOrganizationalUnitComponent {
isLinear = true;
generalFormGroup: FormGroup;
additionalInfoFormGroup: FormGroup;
networkSettingsFormGroup: FormGroup;
types: string[] = ['organizational-unit', 'classrooms-group', 'classroom', 'clients-group'];
parentUnits: any[] = []; // Array to store parent units fetched from API
@Output() unitAdded = new EventEmitter(); // Event emitter to notify parent component about unit addition
constructor(
private _formBuilder: FormBuilder,
private dialogRef: MatDialogRef<CreateOrganizationalUnitComponent>,
private http: HttpClient // Inject HttpClient for HTTP requests
) {
this.generalFormGroup = this._formBuilder.group({
name: ['', Validators.required],
parent: [''],
description: [''],
type: ['', Validators.required]
});
this.additionalInfoFormGroup = this._formBuilder.group({
comments: [''],
});
this.networkSettingsFormGroup = this._formBuilder.group({
proxy: [''],
dns: [''],
netmask: [''],
router: [''],
ntp: [''],
p2pMode: [''],
p2pTime: [0, Validators.min(0)],
mcastIp: [''],
mcastSpeed: [0, Validators.min(0)],
mcastPort: [0, Validators.min(0)],
mcastMode: [''],
menu: ['', Validators.pattern('https?://.+')],
hardwareProfile: ['', Validators.pattern('https?://.+')],
validation: [false]
});
}
ngOnInit() {
this.loadParentUnits(); // Load parent units when component initializes
}
loadParentUnits() {
const url = 'http://127.0.0.1:8080/organizational-units?page=1&itemsPerPage=30';
this.http.get<any>(url).subscribe(
response => {
this.parentUnits = response['hydra:member'];
},
error => {
console.error('Error fetching parent units:', error);
}
);
}
onSubmit() {
if (this.generalFormGroup.valid && this.additionalInfoFormGroup.valid && this.networkSettingsFormGroup.valid) {
const parentValue = this.generalFormGroup.value.parent;
const formData = {
name: this.generalFormGroup.value.name,
parent: parentValue || null,
description: this.generalFormGroup.value.description,
comments: this.additionalInfoFormGroup.value.comments,
type: this.generalFormGroup.value.type
};
// Realizar la solicitud POST
console.log('POST data:', formData);
const postUrl = 'http://127.0.0.1:8080/organizational-units';
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.post<any>(postUrl, formData, { headers }).subscribe(
response => {
console.log('POST successful:', response);
// Emitir evento para notificar que se ha añadido una nueva unidad
this.unitAdded.emit();
this.dialogRef.close(); // Cerrar el diálogo después de añadir
},
error => {
console.error('Error al realizar POST:', error);
// Manejar el error según sea necesario
}
);
}
}
onNoClick(): void {
this.dialogRef.close();
}
}