浏览代码

feat: implement event update and delete functionality in modal and service

EmilianoChavarria 3 周之前
父节点
当前提交
a02f05db8c

+ 140 - 45
Front/src/app/modules/Administrador/pages/calendar/calendar.component.ts

@@ -19,9 +19,6 @@ import { EventoServiceService } from '../../services/evento-service.service';
 import { CircularService } from '../../services/circular.service';
 import Swal from 'sweetalert2';
 
-
-
-
 @Component({
   selector: 'app-calendar',
   templateUrl: './calendar.component.html',
@@ -73,9 +70,11 @@ export class CalendarComponent implements OnInit {
 
   handleEventClick(info: any) {
     const event = info.event;
-    this.dialog.open(EventInfoModal, {
+    const dialogRef = this.dialog.open(EventInfoModal, {
+      autoFocus: false,
       width: '500px',
       data: {
+        id: event.id,
         title: event.title,
         description: event.extendedProps.description,
         start: event.start,
@@ -84,6 +83,12 @@ export class CalendarComponent implements OnInit {
         textColor: event.textColor
       }
     });
+
+    dialogRef.afterClosed().subscribe((result) => {
+      if (result === 'refresh') {
+        this.getEvents();
+      }
+    });
   }
 
   getEvents() {
@@ -100,8 +105,6 @@ export class CalendarComponent implements OnInit {
 
       this.calendarOptions.events = events;
       console.log(this.calendarOptions.events);
-
-
     });
   }
 
@@ -111,7 +114,7 @@ export class CalendarComponent implements OnInit {
       width: '1600px',
     });
 
-    // ✅ Cuando el modal se cierre, vuelve a cargar los eventos
+    
     dialogRef.afterClosed().subscribe(() => {
       this.getEvents();
     });
@@ -124,7 +127,6 @@ export class CalendarComponent implements OnInit {
   styleUrl: './calendar.component.css',
   providers: [provideNativeDateAdapter()],
 })
-
 export class ModalEvent implements OnInit, OnDestroy {
   editor!: Editor;
   toolbar: Toolbar = [
@@ -154,13 +156,38 @@ export class ModalEvent implements OnInit, OnDestroy {
     "#800080", // Púrpura
     "#008080", // Verde azulado
     "#C0C0C0"  // Plata
-
   ];
 
+  public modoEdicion = !!this.data?.evento;
 
   ngOnInit(): void {
     this.editor = new Editor();
 
+    if (this.data?.evento) {
+      const evento = this.data.evento;
+
+      this.form.patchValue({
+        titulo: evento.titulo,
+        fechaInicio: evento.fechaInicio ? evento.fechaInicio.split(' ')[0] : '',
+        fechaFin: evento.fechaFin ? evento.fechaFin.split(' ')[0] : '',
+        horaInicio: evento.fechaInicio ? evento.fechaInicio.split(' ')[1] : '',
+        horaFinal: evento.fechaFin ? evento.fechaFin.split(' ')[1] : '',
+        todoDia: evento.diaCompleto === 'Sí' || evento.diaCompleto === 'Si' || evento.diaCompleto === 'Yes',
+        categoria: evento.colorEvento,
+        contenido: evento.descripcion
+      });
+
+      console.log(evento.fechaInicio.split(' ')[1]);
+
+      // Si era todo el día, deshabilita campos
+      if (evento.diaCompleto === 'Si') {
+        this.form.get('fechaInicio')?.disable();
+        this.form.get('fechaFin')?.disable();
+        this.form.get('horaInicio')?.disable();
+        this.form.get('horaFinal')?.disable();
+      }
+    }
+
     // Escuchar cambios en el campo de audiencia
     this.form.get('audiencia')?.valueChanges.subscribe((value) => {
       if (value === 'TD') {
@@ -168,12 +195,11 @@ export class ModalEvent implements OnInit, OnDestroy {
         this.form.get('destinos')?.setValue('todos'); // valor por defecto
       } else {
         this.form.get('destinos')?.enable();
-        this.form.get('destinos')?.setValue(''); // limpia el valor
+        this.form.get('destinos')?.setValue(''); 
       }
     });
   }
 
-
   ngOnDestroy(): void {
     this.editor.destroy();
   }
@@ -186,16 +212,18 @@ export class ModalEvent implements OnInit, OnDestroy {
     { value: '#F5890F', text: 'Académico' },
     { value: '#3A56E0', text: 'Eventos' },
     { value: '#E0A33A', text: 'Suspensiones' },
-
   ]
-  // public hoy = new Date();
-  constructor(public dialog: MatDialog,
+
+  constructor(
+    public dialog: MatDialog,
+    public dialogRef: MatDialogRef<ModalEvent>,
     private nivelService: NivelEducativoService,
     private gradoService: GradosEducativosService,
     private grupoService: GruposService,
     private materiaService: MateriaService,
     private eventoService: EventoServiceService,
-    private circularService: CircularService
+    private circularService: CircularService,
+    @Inject(MAT_DIALOG_DATA) public data: any
   ) {
     this.lista();
   }
@@ -227,25 +255,21 @@ export class ModalEvent implements OnInit, OnDestroy {
   ];
 
   onTodoDiaChange(event: any): void {
-    const today = new Date(); // Obtiene la fecha de hoy en formato Date
+    const today = new Date();
 
     if (event.checked) {
       console.log('El checkbox "Todo el día" ha sido seleccionado.');
-      // Establece la fecha de hoy en los inputs de fechaInicio y fechaFin
       this.form.get('fechaInicio')?.setValue(today);
       this.form.get('fechaFin')?.setValue(today);
       this.form.get('horaInicio')?.setValue('00:00:00');
       this.form.get('horaFinal')?.setValue('23:30:00');
 
-      // Deshabilita los campos de hora
       this.form.get('fechaInicio')?.disable();
       this.form.get('fechaFin')?.disable();
       this.form.get('horaInicio')?.disable();
       this.form.get('horaFinal')?.disable();
     } else {
       console.log('El checkbox "Todo el día" ha sido deseleccionado.');
-      // Habilita los campos de hora
-
       this.form.get('fechaInicio')?.setValue('');
       this.form.get('fechaFin')?.setValue('');
       this.form.get('horaInicio')?.setValue('');
@@ -295,7 +319,6 @@ export class ModalEvent implements OnInit, OnDestroy {
           })),
         },
       ];
-
     });
   }
 
@@ -345,12 +368,8 @@ export class ModalEvent implements OnInit, OnDestroy {
         console.warn('Opción no reconocida:', value);
         return;
     }
-
-
-
   }
 
-
   private arrayIdDestinatarios: any;
   crearEvento() {
     console.log(this.form.value);
@@ -360,7 +379,6 @@ export class ModalEvent implements OnInit, OnDestroy {
     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.',
@@ -388,13 +406,10 @@ export class ModalEvent implements OnInit, OnDestroy {
 
     console.log(formattedData);
 
-    // Obtener destinatarios (incluso si es TD)
     this.circularService.obtenerDestinatarios(formattedData.objeto).subscribe(
       (response: any) => {
         console.log(response);
         this.arrayIdDestinatarios = [...new Set(response.idUsuario)];
-
-        // Luego guardar evento
         this.guardarEvento(formattedData);
       },
       (error) => {
@@ -409,8 +424,31 @@ export class ModalEvent implements OnInit, OnDestroy {
     );
   }
 
+  actualizarEvento() {
+    const formattedFechaInicio = moment(this.form.value.fechaInicio).format("YYYY-MM-DD");
+    const formattedFechaFinal = moment(this.form.value.fechaFin).format("YYYY-MM-DD");
 
+    const dataActualizada = {
+      idEvento: this.data.evento.idEvento,
+      ...this.form.value,
+      fechaInicio: `${formattedFechaInicio} ${this.form.value.horaInicio}`,
+      fechaFin: `${formattedFechaFinal} ${this.form.value.horaFinal}`,
+    };
 
+    Swal.fire({ title: 'Actualizando...', didOpen: () => Swal.showLoading() });
+
+    this.eventoService.actualizarEvento(dataActualizada).subscribe(
+      () => {
+        Swal.close();
+        Swal.fire('Actualizado', 'El evento se actualizó correctamente.', 'success');
+        this.dialogRef.close('refresh');
+      },
+      (error) => {
+        console.error(error);
+        Swal.fire('Error', 'No se pudo actualizar el evento.', 'error');
+      }
+    );
+  }
 
   guardarEvento(formattedData: any) {
     this.eventoService.crearEvento(formattedData).subscribe(
@@ -421,10 +459,9 @@ export class ModalEvent implements OnInit, OnDestroy {
           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.close();
             Swal.fire({
               icon: 'success',
               title: 'Evento creado correctamente',
@@ -435,7 +472,8 @@ export class ModalEvent implements OnInit, OnDestroy {
             });
 
             this.form.reset();
-            this.dialog.closeAll();
+            // Devolver señal para que el calendario se refresque
+            this.dialogRef.close('refresh');
           },
           (error) => {
             console.error(error);
@@ -462,8 +500,6 @@ export class ModalEvent implements OnInit, OnDestroy {
     );
   }
 
-
-
   generarHorasDelDia(): { hora24: string, hora12: string }[] {
     const horas: { hora24: string, hora12: string }[] = [];
     let hora: number = 0;
@@ -496,19 +532,24 @@ export class ModalEvent implements OnInit, OnDestroy {
 
     return horas;
   }
-
-
-
-
-
-
 }
 
-
 @Component({
   selector: 'app-event-info-modal',
   template: `
-  <h2 mat-dialog-title [style.color]="data.color">{{ data.title }}</h2>
+  <div style="display: flex; justify-content: space-between; align-items: center; padding-right: 24px;">
+    <h2 mat-dialog-title [style.color]="data.color">{{ data.title }}</h2>
+    <div>
+      <button (click)="findOneEvento(data.id)" 
+              style="background-color: #ebac3f; border-radius:10px; border:none; padding: 5px 10px; color:white; margin-right: 10px">
+        Editar
+      </button>
+      <button (click)="confirmarEliminar(data.id)" 
+              style="background-color: red; border-radius:10px; border:none; padding: 5px 10px; color:white">
+        Eliminar
+      </button>
+    </div>
+  </div>
   <mat-dialog-content>
     <p [innerHTML]="data.description || 'Sin descripción disponible.'"></p>
     <p><strong>Inicio:</strong> {{ data.start | date: 'medium' }}</p>
@@ -522,7 +563,61 @@ export class ModalEvent implements OnInit, OnDestroy {
 export class EventInfoModal {
   constructor(
     public dialogRef: MatDialogRef<EventInfoModal>,
+    private eventoService: EventoServiceService,
+    private dialog: MatDialog,
     @Inject(MAT_DIALOG_DATA) public data: any
-  ) { }
-  
-}
+  ) {}
+
+  findOneEvento(id: number) {
+    this.eventoService.findOne(id).subscribe((response: any) => {
+      const editRef = this.dialog.open(ModalEvent, {
+        autoFocus: false,
+        width: '1600px',
+        data: { evento: response }
+      });
+
+      editRef.afterClosed().subscribe((result) => {
+        if (result === 'refresh') {
+          this.dialogRef.close('refresh');
+        }
+      });
+    });
+  }
+
+  confirmarEliminar(id: number) {
+    Swal.fire({
+      title: '¿Estás seguro?',
+      text: 'Este evento será eliminado permanentemente.',
+      icon: 'warning',
+      showCancelButton: true,
+      confirmButtonColor: '#d33',
+      cancelButtonColor: '#3085d6',
+      confirmButtonText: 'Sí, eliminar',
+      cancelButtonText: 'Cancelar'
+    }).then((result) => {
+      if (result.isConfirmed) {
+        Swal.fire({
+          title: 'Eliminando...',
+          text: 'Por favor espera.',
+          allowOutsideClick: false,
+          didOpen: () => {
+            Swal.showLoading();
+          }
+        });
+
+        this.eventoService.eliminarEvento(id).subscribe(
+          () => {
+            Swal.close();
+            Swal.fire('Eliminado', 'El evento fue eliminado correctamente.', 'success');
+            this.dialogRef.close('refresh'); 
+          },
+          (error:any) => {
+            console.error(error);
+            Swal.close();
+            Swal.fire('Error', 'No se pudo eliminar el evento.', 'error');
+          }
+        );
+      }
+    });
+  }
+}

+ 15 - 7
Front/src/app/modules/Administrador/pages/calendar/modalEvent.component.html

@@ -4,7 +4,9 @@
 <!--
     <div class="titulo-modal">
     </div>-->
-<span class="center">Agregar Evento</span>
+<span class="center">
+    {{ data ? 'Editar Evento' : 'Agregar Evento' }}
+</span>
 <!-- --------------------------------------------------------------------------------- -->
 <!-- form -->
 
@@ -40,11 +42,13 @@
 
                             <mat-form-field class="ml-10" style="width: 140px;">
                                 <mat-label>Hora</mat-label>
-                                <mat-select matNativeControl name="horaInicio" formControlName="horaInicio">
-                                    <mat-option *ngFor="let hora of horasDelDia" [value]="hora.hora24">{{hora.hora12}}
+                                <mat-select name="horaInicio" formControlName="horaInicio">
+                                    <mat-option *ngFor="let hora of horasDelDia" [value]="hora.hora24">
+                                        {{hora.hora12}}
                                     </mat-option>
                                 </mat-select>
                             </mat-form-field>
+
                         </div>
 
                     </div>
@@ -63,11 +67,13 @@
 
                             <mat-form-field class="ml-10" style="width: 140px;">
                                 <mat-label>Hora</mat-label>
-                                <mat-select matNativeControl name="horaFinal" formControlName="horaFinal">
-                                    <mat-option *ngFor="let hora of horasDelDia" [value]="hora.hora24">{{hora.hora12}}
+                                <mat-select name="horaFinal" formControlName="horaFinal">
+                                    <mat-option *ngFor="let hora of horasDelDia" [value]="hora.hora24">
+                                        {{hora.hora12}}
                                     </mat-option>
                                 </mat-select>
                             </mat-form-field>
+
                         </div>
 
                     </div>
@@ -135,8 +141,10 @@
 
 <div class="align mb-10">
 
-    <button type="button" class="button-yellow" (click)="crearEvento()">Guardar <mat-icon class="icon"
-            matSuffix>description</mat-icon></button>
+    <button type="button" class="button-yellow" (click)="data ? actualizarEvento() : crearEvento()">
+        {{ data ? 'Actualizar' : 'Guardar' }}
+        <mat-icon class="icon" matSuffix>description</mat-icon>
+    </button>
 
     <button class="button-red ml-10" mat-dialog-close>Cerrar <mat-icon class="icon" matSuffix>cancel</mat-icon></button>
 </div>

+ 13 - 1
Front/src/app/modules/Administrador/services/evento-service.service.ts

@@ -22,7 +22,7 @@ export class EventoServiceService {
   crearEvento(evento: any) {
     return this.http.post(`${this.URL}/eventoSave`, evento, { headers: this.getHeaders() });
   }
-  
+
   savecalendarioUsuarios(evento: any) {
     return this.http.post(`${this.URL}/savecalendarioUsuarios`, evento, { headers: this.getHeaders() });
   }
@@ -35,4 +35,16 @@ export class EventoServiceService {
     return this.http.get(`${this.URL}/eventosSemana`, { headers: this.getHeaders() });
   }
 
+  findOne(id: number) {
+    return this.http.get(`${this.URL}/eventos/${id}`, { headers: this.getHeaders() });
+  }
+
+  actualizarEvento(evento: any) {
+    return this.http.put(`${this.URL}/eventos/${evento.idEvento}`, evento, { headers: this.getHeaders() });
+  }
+
+  eliminarEvento(id: number) {
+    return this.http.delete(`${this.URL}/eventos/${id}`, { headers: this.getHeaders() });
+  }
+
 }