Kaynağa Gözat

SUBO EDITAR Y ELIMINAR MODULO ADMIN FORM

FREDY 3 ay önce
ebeveyn
işleme
0ebde643ee

+ 79 - 0
Back/backendP-Educativa/app/Http/Controllers/FormController.php

@@ -109,5 +109,84 @@ public function getFormById($id): JsonResponse
     ]);
 
 }
+public function update(Request $request, $id): JsonResponse
+{
+    try {
+        $validated = $request->validate([
+            'title' => 'required|string|max:255',
+            'tabs' => 'required|array',
+            'tabs.*.id' => 'required|string',
+            'tabs.*.title' => 'required|string',
+            'tabs.*.rows' => 'required|integer|min:1',
+            'tabs.*.columns' => 'required|integer|min:1',
+            'tabs.*.elements' => 'required|array',
+            'tabs.*.elements.*.position' => 'required|array',
+            'tabs.*.elements.*.element' => 'required|array',
+        ]);
+
+        $affected = DB::table('forms')
+            ->where('id', $id)
+            ->update([
+                'title' => $validated['title'],
+                'configuration' => json_encode([
+                    'tabs' => $validated['tabs']
+                ]),
+                'updated_at' => now()
+            ]);
+
+        if ($affected === 0) {
+            return response()->json([
+                'success' => false,
+                'message' => 'No se encontró el formulario para actualizar'
+            ], 404);
+        }
+
+        return response()->json([
+            'success' => true,
+            'message' => 'Formulario actualizado exitosamente'
+        ], 200);
+
+    } catch (ValidationException $e) {
+        return response()->json([
+            'success' => false,
+            'message' => 'Error de validación',
+            'errors' => $e->errors()
+        ], 422);
+    } catch (\Exception $e) {
+        return response()->json([
+            'success' => false,
+            'message' => 'Error interno del servidor',
+            'error' => $e->getMessage()
+        ], 500);
+    }
+}
+
+ public function destroy($id)
+    {
+        try {
+            $form = Form::findOrFail($id);
 
+            if ($form->is_published) {
+                return response()->json([
+                    'success' => false,
+                    'message' => 'No se puede eliminar un formulario ya publicado.'
+                ], 403);
+            }
+
+            // Eliminar el formulario (configuración incluida)
+            $form->delete();
+
+            return response()->json([
+                'success' => true,
+                'message' => 'Formulario eliminado correctamente.'
+            ], 200);
+        } catch (\Exception $e) {
+            return response()->json([
+                'success' => false,
+                'message' => 'Error al eliminar el formulario.',
+                'error' => $e->getMessage()
+            ], 500);
+        }
+    }
 }
+

+ 2 - 1
Back/backendP-Educativa/routes/api.php

@@ -249,6 +249,7 @@ Route::get('/alumnos/bitacora/{id}', [AlumnosBitacoraController::class, 'index']
     Route::post('/createForm', [FormController::class, 'store']); // Crear un nuevo formulario
         Route::get('/formularios',[FormController::class,'getAll']);
         Route::get('/formulario/{id}', [FormController::class, 'getFormById']);
-
+    Route::put('/updateForm/{id}', [FormController::class, 'update']);
+Route::delete('/forms/{id}', [FormController::class, 'destroy']);
 
 });

+ 1 - 1
Front/src/app/modules/Administrador/pages/admin-form/admin-form.component.html

@@ -18,7 +18,7 @@
       (rowsChange)="onRowsChange($event)"
       (columnsChange)="onColumnsChange($event)"
       (showTooltipChange)="onShowTooltipChange($event)"
-      (generateClick)="saveForm()"
+(generateClick)="saveOrUpdateForm()"
       (addTabClick)="addTab()"
       (removeTabClick)="removeTab()"
       (gridConfigChange)="buildGrid()"

+ 75 - 9
Front/src/app/modules/Administrador/pages/admin-form/admin-form.component.ts

@@ -2,7 +2,8 @@ import { FormApiService, FormConfiguration, FormListItem } from './../../service
 import { Component, OnInit } from '@angular/core';
 import { EnviarInfoService } from '../../services/enviar-info.service';
 import { FormService } from '../../services/FormService.service';
-
+import { ActivatedRoute } from '@angular/router';
+import { FormArray } from '@angular/forms';
 interface GridCell {
   row: number;
   col: number;
@@ -73,17 +74,27 @@ export class AdminFormComponent implements OnInit {
     { type: 'checkbox', label: 'Casilla', required: false }
   ];
   formData: any;
+  form: any;
+  fb: any;
 
   constructor(
     private _enviarInfo: EnviarInfoService,
     private formApiService: FormApiService,
-    private formService: FormService
+    private formService: FormService,
+    private route: ActivatedRoute
   ) {}
 
   ngOnInit() {
     this._enviarInfo.currentTextColor.subscribe(color => this.textColor = color);
     this._enviarInfo.currentColor.subscribe(color => this.color = color);
     this.addTab();
+     this.route.queryParams.subscribe(params => {
+    const id = params['id'];
+    if (id) {
+      this.cargarFormulario(+id);
+      console.log('ID recibido:', id);
+    }
+  });
     // this.loadSavedForms();
   }
 
@@ -111,6 +122,7 @@ export class AdminFormComponent implements OnInit {
   }
 
 
+
   const tabConError = this.tabs.find(tab => tab.rows < 1 || tab.columns < 1);
   if (tabConError) {
     alert(` La sección "${tabConError.name}" tiene un número inválido de filas o columnas.\n\n
@@ -482,13 +494,67 @@ export class AdminFormComponent implements OnInit {
       this.updateCurrentTabGrid();
     }
   }
-   cargarFormulario(id: number): void {
-    this.formService.getFormById(id).subscribe(data => {
-      this.formData = data;
-      // Aquí ya puedes inyectar los datos en tu formulario dinámico
-      console.log('Form a editar:', this.formData);
-      // ejemplo: this.form.patchValue(this.formData)
-    });
+ cargarFormulario(id: number): void {
+  this.formService.getFormById(id).subscribe(data => {
+    this.formData = data;
+    console.log('Form a editar:', this.formData);
+
+    // Llama al método que reconstruye el formulario visual
+    this.loadFormConfiguration(this.formData.form.configuration);
+    this.formTitle = this.formData.form.title;
+    this.currentFormId = this.formData.form.id;
+  });
+}
+
+
+  updateForm() {
+  if (!this.formTitle.trim()) {
+    alert('Por favor, ingresa un título para el formulario');
+    return;
+  }
+
+  if (!this.currentFormId) {
+    alert('No se ha cargado ningún formulario para editar');
+    return;
+  }
+
+  const tabConError = this.tabs.find(tab => tab.rows < 1 || tab.columns < 1);
+  if (tabConError) {
+    alert(`La sección "${tabConError.name}" tiene dimensiones inválidas (mínimo 1 fila y 1 columna).`);
+    return;
+  }
+
+  if (this.currentTab) {
+    this.currentTab.grid = [...this.grid];
+  }
+
+  const config = this.buildFormConfiguration();
+  this.isLoading = true;
+  this.saveStatus = 'Actualizando formulario...';
+
+  this.formService.updateForm(this.currentFormId, config).subscribe({
+    next: (response) => {
+      console.log('Formulario actualizado:', response);
+      this.saveStatus = 'Formulario actualizado correctamente';
+      this.isLoading = false;
+    },
+    error: (error) => {
+      console.error('Error al actualizar formulario:', error);
+      this.saveStatus = 'Error al actualizar el formulario';
+      this.isLoading = false;
+    }
+  });
+}
+saveOrUpdateForm() {
+  if (this.currentFormId) {
+    this.updateForm();
+  } else {
+    this.saveForm();
   }
 }
 
+ }
+
+
+
+

+ 10 - 0
Front/src/app/modules/Administrador/pages/admin-form/form-selector/form-selector.component.html

@@ -59,6 +59,16 @@
             </button>
           </td>
         </ng-container>
+        <!-- Eliminar Column -->
+<ng-container matColumnDef="eliminar">
+  <th mat-header-cell *matHeaderCellDef> Eliminar </th>
+  <td mat-cell *matCellDef="let form">
+    <button mat-icon-button color="warn" (click)="deleteForm(form.id)">
+      <mat-icon>delete</mat-icon>
+    </button>
+  </td>
+</ng-container>
+
 
         <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
         <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

+ 14 - 1
Front/src/app/modules/Administrador/pages/admin-form/form-selector/form-selector.component.ts

@@ -28,7 +28,7 @@ export class FormSelectorComponent implements OnInit {
   formTitle: string = '';
   forms: any[] = [];
  dataSource = new MatTableDataSource<any>([]);
-displayedColumns: string[] = ['id', 'title', 'ver', 'editar', 'publicar'];
+displayedColumns: string[] = ['id', 'title', 'ver', 'editar', 'publicar', 'eliminar'];
   selectedFormId: number | null = null;
   isLoading = false;
 
@@ -71,6 +71,19 @@ loadForms(): void {
 editForm(id: number) {
   this.router.navigate(['homeAdmin/formularios'], { queryParams: { id } });
 }
+deleteForm(id: number) {
+  if (confirm('¿Estás seguro de que deseas eliminar este formulario?')) {
+    this.formService.deleteForm(id).subscribe({
+      next: (res) => {
+        console.log('Formulario eliminado:', res);
+        this.loadForms; // refresca la tabla
+      },
+      error: (err) => {
+        console.error('Error al eliminar formulario:', err);
+      }
+    });
+  }
+}
 
 
 }

+ 13 - 0
Front/src/app/modules/Administrador/services/FormService.service.ts

@@ -42,6 +42,13 @@ export class FormService {
       headers: this.getHeaders()
     });
   }
+// ✅ Actualizar un formulario existente
+updateForm(id: number, data: any): Observable<any> {
+  return this.http.put(`${this.URL}/updateForm/${id}`, data, {
+    headers: this.getHeaders()
+  });
+}
+
 
   // ✅ Publicar un formulario
   publishForm(id: number): Observable<any> {
@@ -63,4 +70,10 @@ export class FormService {
       headers: this.getHeaders()
     });
   }
+  deleteForm(id: number): Observable<any> {
+  return this.http.delete(`${this.URL}/forms/${id}`, {
+    headers: this.getHeaders()
+  });
+}
+
 }