diff --git a/cmd/web/main.go b/cmd/web/main.go index aceebce..e779b22 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -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) }) diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 8913ff2..37d097e 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -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 +} diff --git a/internal/web/handlers.go b/internal/web/handlers.go index 0c76838..ff4ca98 100644 --- a/internal/web/handlers.go +++ b/internal/web/handlers.go @@ -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() diff --git a/internal/web/templates/view.html b/internal/web/templates/view.html index 050baf5..78dfaf5 100644 --- a/internal/web/templates/view.html +++ b/internal/web/templates/view.html @@ -99,7 +99,13 @@