From 286a2eea18a2527f1bf2d88555c4c944db709956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?O=CC=81scar=20M=2E=20Lage?= Date: Thu, 28 Nov 2024 14:32:23 +0100 Subject: [PATCH] Add: ability to write a date in the ON/OFF telegram command Now we can do it like this: - ON (current date) - ON 7:30 (current day, custom hour) - ON 2024-11-27 7:30 (custom day, custom hour) --- internal/bot/controller.go | 75 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/internal/bot/controller.go b/internal/bot/controller.go index d02961f..632a1d6 100644 --- a/internal/bot/controller.go +++ b/internal/bot/controller.go @@ -18,6 +18,81 @@ func ProcesarMensaje(update tgbotapi.Update, db *gorm.DB) { command := strings.ToUpper(parts[0]) var timestamp time.Time + if command != "ON" && command != "OFF" { + log.Println("Comando desconocido:", command) + return + } + + now := time.Now() + if len(parts) == 1 { + // Sin fecha ni hora -> usar timestamp actual + timestamp = now + } else { + // Intentar parsear fecha y hora + var parsedDate time.Time + var parsedTime time.Time + var err error + + for i := 1; i < len(parts); i++ { + if parsedDate.IsZero() { + parsedDate, err = time.Parse("2006-01-02", parts[i]) + if err == nil { + continue + } + } + if parsedTime.IsZero() { + parsedTime, err = time.Parse("15:04", parts[i]) + if err == nil { + continue + } + } + } + + if !parsedDate.IsZero() && !parsedTime.IsZero() { + // Ambos fecha y hora proporcionados + timestamp = time.Date( + parsedDate.Year(), parsedDate.Month(), parsedDate.Day(), + parsedTime.Hour(), parsedTime.Minute(), 0, 0, now.Location(), + ) + } else if !parsedDate.IsZero() { + // Solo fecha proporcionada -> usar las 00:00 como hora + timestamp = time.Date( + parsedDate.Year(), parsedDate.Month(), parsedDate.Day(), + 0, 0, 0, 0, now.Location(), + ) + } else if !parsedTime.IsZero() { + // Solo hora proporcionada -> usar fecha actual + timestamp = time.Date( + now.Year(), now.Month(), now.Day(), + parsedTime.Hour(), parsedTime.Minute(), 0, 0, now.Location(), + ) + } else { + log.Println("Formato de entrada inválido:", parts[1:]) + return + } + } + + event := HeatingEvent{ + EventType: command, + Timestamp: timestamp, + } + if err := db.Create(&event).Error; err != nil { + log.Printf("Error al guardar el evento %s: %v", command, err) + return + } + + log.Printf("Evento %s registrado con éxito para el %s", command, timestamp.Format("2006-01-02 15:04")) +} + +func ProcesarMensaje2(update tgbotapi.Update, db *gorm.DB) { + if update.Message == nil || update.Message.Text == "" { + return + } + + parts := strings.Fields(update.Message.Text) + command := strings.ToUpper(parts[0]) + var timestamp time.Time + if len(parts) == 1 { timestamp = update.Message.Time() } else {