Browse Source

feat: enhance modal functionality and event creation process

EmilianoChavarria 3 weeks ago
parent
commit
452a0c74a0
1 changed files with 100 additions and 48 deletions
  1. 100 48
      Front/src/app/modules/Administrador/pages/calendar/calendar.component.ts

+ 100 - 48
Front/src/app/modules/Administrador/pages/calendar/calendar.component.ts

@@ -106,10 +106,15 @@ export class CalendarComponent implements OnInit {
   }
 
   openDialog() {
-    this.dialog.open(ModalEvent, {
+    const dialogRef = this.dialog.open(ModalEvent, {
       autoFocus: false,
       width: '1600px',
     });
+
+    // ✅ Cuando el modal se cierre, vuelve a cargar los eventos
+    dialogRef.afterClosed().subscribe(() => {
+      this.getEvents();
+    });
   }
 }
 
@@ -155,8 +160,20 @@ export class ModalEvent implements OnInit, OnDestroy {
 
   ngOnInit(): void {
     this.editor = new Editor();
+
+    // Escuchar cambios en el campo de audiencia
+    this.form.get('audiencia')?.valueChanges.subscribe((value) => {
+      if (value === 'TD') {
+        this.form.get('destinos')?.disable();
+        this.form.get('destinos')?.setValue('todos'); // valor por defecto
+      } else {
+        this.form.get('destinos')?.enable();
+        this.form.get('destinos')?.setValue(''); // limpia el valor
+      }
+    });
   }
 
+
   ngOnDestroy(): void {
     this.editor.destroy();
   }
@@ -206,6 +223,7 @@ export class ModalEvent implements OnInit, OnDestroy {
     { value: 'PF', audiencia: 'Padre de Familia' },
     { value: 'AD', audiencia: 'Administradores' },
     { value: 'PR', audiencia: 'Profesores' },
+    { value: 'TD', audiencia: 'Todos' },
   ];
 
   onTodoDiaChange(event: any): void {
@@ -335,83 +353,117 @@ export class ModalEvent implements OnInit, OnDestroy {
 
   private arrayIdDestinatarios: any;
   crearEvento() {
-
     console.log(this.form.value);
+
     const formattedFechaInicio = moment(this.form.value.fechaInicio).format("YYYY-MM-DD");
     const formattedFechaFinal = moment(this.form.value.fechaFin).format("YYYY-MM-DD");
-    const horaInicio = this.form.value.horaInicio || '00:00:00'; // Valor por defecto
+    const horaInicio = this.form.value.horaInicio || '00:00:00';
     const horaFinal = this.form.value.horaFinal || '23:30:00';
 
+    // Mostrar alerta de carga mientras se realiza el proceso
+    Swal.fire({
+      title: 'Enviando evento...',
+      text: 'Por favor espera mientras se procesa la información.',
+      allowOutsideClick: false,
+      didOpen: () => {
+        Swal.showLoading();
+      }
+    });
+
+    const objeto =
+      this.form.value.audiencia === 'TD'
+        ? { Audiencia: 'TD', Destino: 'todos', id: 'todos' }
+        : {
+          Audiencia: this.form.value.audiencia,
+          Destino: this.form.value.destinos?.[1] ?? '',
+          id: this.form.value.destinos?.[0] ?? '',
+        };
+
     const formattedData = {
       ...this.form.value,
-      objeto: {
-        Audiencia: this.form.value.audiencia,
-        Destino: this.form.value.destinos?.[1] ?? '',
-        id: this.form.value.destinos?.[0] ?? '',
-
-      },
+      objeto,
       fechaInicio: `${formattedFechaInicio} ${horaInicio}`,
       fechaFin: `${formattedFechaFinal} ${horaFinal}`,
-    }
-
-    this.circularService.obtenerDestinatarios(formattedData.objeto).subscribe((response: any) => {
-      // Eliminar duplicados del array
-      console.log(response);
-      this.arrayIdDestinatarios = [...new Set(response.idUsuario)];
-      console.log(this.arrayIdDestinatarios);
-    });
+    };
 
     console.log(formattedData);
 
-    this.eventoService.crearEvento(formattedData).subscribe(
+    // Obtener destinatarios (incluso si es TD)
+    this.circularService.obtenerDestinatarios(formattedData.objeto).subscribe(
       (response: any) => {
         console.log(response);
-        console.log(this.arrayIdDestinatarios);
-
-        // Iterar sobre los destinatarios y guardar en el calendario
-        this.arrayIdDestinatarios.forEach((element: any) => {
-          this.eventoService.savecalendarioUsuarios({ idEvento: response.idEvento, idUsuario: element }).subscribe(
-            (response1) => {
-              console.log(response1);
-            },
-            (error) => {
-              console.log(error);
-            }
-          );
-        });
+        this.arrayIdDestinatarios = [...new Set(response.idUsuario)];
 
-        // Mostrar alerta de éxito
+        // Luego guardar evento
+        this.guardarEvento(formattedData);
+      },
+      (error) => {
+        console.error('Error al obtener destinatarios:', error);
         Swal.fire({
-          icon: 'success',
-          title: 'Evento creado',
-          text: 'El evento se ha creado y asignado correctamente.',
+          icon: 'error',
+          title: 'Error al obtener destinatarios',
+          text: 'No fue posible recuperar los destinatarios.',
           confirmButtonText: 'Aceptar'
         });
-        
-        // Opcional: Resetear el formulario y cerrar el diálogo
-        this.form.reset();
-        this.dialog.closeAll();
-        // timeout para recargar la página
-        setTimeout(() => {
-          this.dialog.closeAll();
-        }, 2000);
+      }
+    );
+  }
+
+
+
 
+  guardarEvento(formattedData: any) {
+    this.eventoService.crearEvento(formattedData).subscribe(
+      (response: any) => {
+        console.log(response);
+
+        const asignaciones = this.arrayIdDestinatarios.map((element: any) =>
+          this.eventoService.savecalendarioUsuarios({ idEvento: response.idEvento, idUsuario: element })
+        );
+
+        // Esperar a que todas las peticiones terminen antes de mostrar el éxito
+        forkJoin(asignaciones).subscribe(
+          () => {
+            Swal.close(); // Cierra el "cargando"
+            Swal.fire({
+              icon: 'success',
+              title: 'Evento creado correctamente',
+              text: 'El evento se ha creado y asignado a los destinatarios.',
+              confirmButtonText: 'Aceptar',
+              timer: 2000,
+              timerProgressBar: true
+            });
+
+            this.form.reset();
+            this.dialog.closeAll();
+          },
+          (error) => {
+            console.error(error);
+            Swal.close();
+            Swal.fire({
+              icon: 'error',
+              title: 'Error al asignar destinatarios',
+              text: 'El evento fue creado, pero no se pudo asignar a todos los usuarios.',
+              confirmButtonText: 'Aceptar'
+            });
+          }
+        );
       },
       (error) => {
         console.error(error.error);
-
-        // Mostrar alerta de error
+        Swal.close();
         Swal.fire({
           icon: 'error',
-          title: 'Error',
+          title: 'Error al crear evento',
           text: 'Ocurrió un error al crear el evento. Por favor, inténtalo de nuevo.',
           confirmButtonText: 'Aceptar'
         });
       }
     );
-
   }
 
+
+
   generarHorasDelDia(): { hora24: string, hora12: string }[] {
     const horas: { hora24: string, hora12: string }[] = [];
     let hora: number = 0;
@@ -471,5 +523,5 @@ export class EventInfoModal {
   constructor(
     public dialogRef: MatDialogRef<EventInfoModal>,
     @Inject(MAT_DIALOG_DATA) public data: any
-  ) {}
+  ) { }
 }