Add: ability to delete events

This commit is contained in:
Óscar M. Lage 2024-11-28 22:51:32 +01:00
parent 9e7f48d038
commit b1cdfe40a9
4 changed files with 42 additions and 1 deletions

View File

@ -37,6 +37,9 @@ func main() {
e.POST("/events/edit/:id", func(c echo.Context) error {
return web.UpdateEventHandler(c, config.DB)
})
e.POST("/events/del/:id", func(c echo.Context) error {
return web.DeleteEventHandler(c, config.DB)
})
e.GET("/about", func(c echo.Context) error {
return web.AboutHandler(c, config.DB)
})

View File

@ -1,6 +1,7 @@
package repository
import (
"fmt"
"heating-monitor/internal/bot"
"gorm.io/gorm"
@ -29,3 +30,15 @@ func UpdateEventByID(db *gorm.DB, id int, updatedEvent *bot.HeatingEvent) (*bot.
}
return &event, nil
}
// DeleteEventByID elimina un evento por su ID
func DeleteEventByID(db *gorm.DB, id int) error {
result := db.Delete(&bot.HeatingEvent{}, id)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return fmt.Errorf("No se encontró un evento con el ID %d", id)
}
return nil
}

View File

@ -157,6 +157,25 @@ func UpdateEventHandler(c echo.Context, db *gorm.DB) error {
return c.Redirect(http.StatusFound, "/")
}
// DeleteEventHandler elimina un evento de la base de datos
func DeleteEventHandler(c echo.Context, db *gorm.DB) error {
// Obtener el ID del evento desde los parámetros
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
log.Printf("Error al convertir ID: %v", err)
return c.JSON(http.StatusBadRequest, "ID inválido")
}
// Eliminar el evento usando el repositorio
err = repository.DeleteEventByID(db, id)
if err != nil {
log.Printf("Error al eliminar evento con ID %d: %v", id, err)
return c.JSON(http.StatusInternalServerError, "Error al eliminar evento")
}
return c.Redirect(http.StatusFound, "/")
}
func AboutHandler(c echo.Context, db *gorm.DB) error {
// Cargar configuración desde .env
cfg, err := config.LoadConfig()

View File

@ -99,7 +99,13 @@
<td class="px-6 py-4 text-sm text-gray-700">{{.ID}}</td>
<td class="px-6 py-4 text-sm text-gray-700">{{.Timestamp}}</td>
<td class="px-6 py-4 text-sm text-gray-700">{{.EventType}}</td>
<td class="px-6 py-4 text-sm text-gray-700"><a href="/events/edit/{{.ID}}">Editar</a></td>
<td class="px-6 py-4 text-sm text-gray-700">
<a href="/events/edit/{{.ID}}">Editar</a>
<form action="/events/del/{{.ID}}" method="POST" onsubmit="return confirm('¿Estás seguro de que deseas eliminar este evento?');">
<input type="hidden" name="_method" value="DELETE">
<button type="submit" class="text-red-600 hover:underline">Eliminar</button>
</form>
</td>
</tr>
{{end}}
</tbody>