heating-monitor/internal/bot/controller.go
Óscar M. Lage 9f8af1c290 Fix: CET timestamps in the bot command
When some hour was set via bot, it stored it as GMT, not as CET.
Fixed for that cases:

- ON 20:00
- ON 2024-12-04 20:00
2024-12-04 20:44:16 +01:00

87 lines
2.0 KiB
Go

package bot
import (
"log"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"gorm.io/gorm"
)
func ProcesarMensaje(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 command != "ON" && command != "OFF" {
log.Println("Comando desconocido:", command)
return
}
loc, _ := time.LoadLocation("CET")
now := time.Now().In(loc)
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, loc,
)
} 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, loc,
)
} 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, loc,
)
} 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"))
}