package bot import ( "database/sql" "errors" "fmt" "time" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "worktimeBot/internal/db" ) type Handler struct { Bot *tgbotapi.BotAPI DB *db.Store AllowedUsers map[int64]bool } func NewHandler(bot *tgbotapi.BotAPI, store *db.Store, allowed map[int64]bool) *Handler { return &Handler{Bot: bot, DB: store, AllowedUsers: allowed} } func (h *Handler) HandleMessage(update tgbotapi.Update) { msg := update.Message if len(h.AllowedUsers) > 0 && !h.AllowedUsers[msg.Chat.ID] { return } switch msg.Text { case "/start": h.handleStart(msg) case "/clockin", "Clock In": h.handleClockInMsg(msg) case "/clockout", "Clock Out": h.handleClockOutMsg(msg) case "/remote": h.toggleRemote(msg) case "/report": h.handleReport(msg) case "/export": h.handleExport(msg) case "/dayoff": h.handleDayOff(msg) default: h.sendText(msg.Chat.ID, "Unknown command") } } func (h *Handler) HandleCallback(update tgbotapi.Update) { cb := update.CallbackQuery if len(h.AllowedUsers) > 0 && !h.AllowedUsers[cb.Message.Chat.ID] { h.Bot.Request(tgbotapi.NewCallback(cb.ID, "Unauthorized")) return } chatID := cb.Message.Chat.ID msgID := cb.Message.MessageID switch cb.Data { case "clockin": h.clockInCallback(chatID, msgID, cb.ID) case "clockout": h.clockOutCallback(chatID, msgID, cb.ID) case "remote": h.toggleRemoteCallback(chatID, msgID, cb.ID) case "report": h.reportCallback(chatID, msgID, cb.ID) case "export": h.exportCallback(chatID, msgID, cb.ID) case "dayoff": h.dayOffCallback(chatID, msgID, cb.ID) case "back_menu": h.backToMenu(chatID, msgID, cb.ID) } } // --- /start --- func (h *Handler) handleStart(msg *tgbotapi.Message) { h.DB.SetSetting("chat_id", fmt.Sprintf("%d", msg.Chat.ID)) text := "Welcome! Choose an action:" reply := tgbotapi.NewMessage(msg.Chat.ID, text) reply.ReplyMarkup = mainKeyboard() h.Bot.Send(reply) kb := quickKeyboard() quick := tgbotapi.NewMessage(msg.Chat.ID, "Use the buttons below to quickly clock in/out:") quick.ReplyMarkup = kb h.Bot.Send(quick) } func quickKeyboard() tgbotapi.ReplyKeyboardMarkup { return tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("Clock In"), tgbotapi.NewKeyboardButton("Clock Out"), ), ) } func mainKeyboard() tgbotapi.InlineKeyboardMarkup { return tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Clock In", "clockin"), tgbotapi.NewInlineKeyboardButtonData("Clock Out", "clockout"), ), tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Report", "report"), tgbotapi.NewInlineKeyboardButtonData("Export", "export"), ), tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Toggle Remote/Onsite", "remote"), tgbotapi.NewInlineKeyboardButtonData("Day Off", "dayoff"), ), ) } func backKeyboard() tgbotapi.InlineKeyboardMarkup { return tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("Back to Menu", "back_menu"), ), ) } // --- Text command handlers --- func (h *Handler) handleClockInMsg(msg *tgbotapi.Message) { if err := h.doClockIn(); err != nil { h.sendText(msg.Chat.ID, err.Error()) } else { h.sendSuccessWithMenu(msg.Chat.ID, "āœ… Clocked in at "+time.Now().Format("15:04")) } } func (h *Handler) handleClockOutMsg(msg *tgbotapi.Message) { if err := h.doClockOut(); err != nil { h.sendText(msg.Chat.ID, err.Error()) } else { h.sendSuccessWithMenu(msg.Chat.ID, "āœ… Clocked out at "+time.Now().Format("15:04")) } } func (h *Handler) toggleRemote(msg *tgbotapi.Message) { current, err := h.DB.GetSetting("remote_flag") if err != nil { current = "onsite" } newMode := "remote" text := "šŸŒ Remote mode enabled" if current == "remote" { newMode = "onsite" text = "šŸ¢ Onsite mode enabled" } if err := h.DB.SetSetting("remote_flag", newMode); err != nil { h.sendText(msg.Chat.ID, "Error toggling mode") return } h.sendText(msg.Chat.ID, text) } func (h *Handler) handleReport(msg *tgbotapi.Message) { text := h.buildDailyReport(time.Now()) reply := tgbotapi.NewMessage(msg.Chat.ID, text) h.Bot.Send(reply) } func (h *Handler) buildDailyReport(now time.Time) string { dateStr := now.Format("2006-01-02") events, err := h.DB.EventsForDay(dateStr) if err != nil { return "Error fetching events." } if len(events) == 0 { isOff, _ := h.DB.IsDayOff(dateStr) if isOff { return fmt.Sprintf("šŸ“‹ %s — Day Off šŸŽ‰", dateStr) } return fmt.Sprintf("šŸ“‹ %s — No events recorded.", dateStr) } remoteFlag := "Onsite" current, err := h.DB.GetSetting("remote_flag") if err == nil && current == "remote" { remoteFlag = "Remote" } totals := ComputeDailyTotals(events) if totals.PairCount == 0 { t := time.Unix(events[0].OccurredAt, 0).Format("15:04") return fmt.Sprintf("šŸ“‹ %s\nšŸ“ Mode: %s\nā° Clocked in at %s\n\nStill working — no clock-out yet.", dateStr, remoteFlag, t) } lines := fmt.Sprintf("šŸ“‹ Report for %s\nšŸ“ Mode: %s\n\n", dateStr, remoteFlag) for _, e := range events { t := time.Unix(e.OccurredAt, 0).Format("15:04") icon := "ā°" label := "Clock In" if e.EventType == "out" { icon = "šŸ”“" label = "Clock Out" } lines += fmt.Sprintf("%s %s — %s\n", icon, t, label) } workStr := formatDuration(totals.TotalSeconds) breakStr := formatDuration(totals.BreakSeconds) lines += fmt.Sprintf("\nšŸ“Š Summary:\n Work: %s\n Break: %s\n", workStr, breakStr) return lines } func (h *Handler) handleExport(msg *tgbotapi.Message) { now := time.Now() year, month := now.Year(), now.Month() data, err := GenerateMonthlyReport(h.DB, year, month) if err != nil { h.sendText(msg.Chat.ID, "Error generating report") return } doc := tgbotapi.NewDocument(msg.Chat.ID, tgbotapi.FileBytes{ Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")), Bytes: data, }) if _, err := h.Bot.Send(doc); err != nil { h.sendText(msg.Chat.ID, "Error sending file") } } func (h *Handler) handleDayOff(msg *tgbotapi.Message) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(today) if err != nil { h.sendText(msg.Chat.ID, "Error checking day off") return } if isOff { if err := h.DB.RemoveDayOff(today); err != nil { h.sendText(msg.Chat.ID, "Error removing day off") return } h.sendText(msg.Chat.ID, "āœ… Day off removed") } else { if err := h.DB.SetDayOff(today, ""); err != nil { h.sendText(msg.Chat.ID, "Error setting day off") return } h.sendText(msg.Chat.ID, "āœ… Today marked as day off") } } // --- Callback handlers --- func (h *Handler) clockInCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) text := "āœ… Clocked in at " + time.Now().Format("15:04") if err := h.doClockIn(); err != nil { text = err.Error() } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } func (h *Handler) clockOutCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) text := "āœ… Clocked out at " + time.Now().Format("15:04") if err := h.doClockOut(); err != nil { text = err.Error() } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } func (h *Handler) toggleRemoteCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) current, err := h.DB.GetSetting("remote_flag") if err != nil { current = "onsite" } newMode := "remote" text := "šŸŒ Remote mode enabled" if current == "remote" { newMode = "onsite" text = "šŸ¢ Onsite mode enabled" } if err := h.DB.SetSetting("remote_flag", newMode); err != nil { return } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } func (h *Handler) reportCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) text := h.buildDailyReport(time.Now()) edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } func (h *Handler) exportCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) now := time.Now() year, month := now.Year(), now.Month() data, err := GenerateMonthlyReport(h.DB, year, month) if err != nil { edit := tgbotapi.NewEditMessageText(chatID, msgID, "Error generating report") kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) return } edit := tgbotapi.NewEditMessageText(chatID, msgID, "Here is your report:") kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")), Bytes: data, }) h.Bot.Send(doc) } func (h *Handler) dayOffCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(today) if err != nil { return } text := "āœ… Today marked as day off" if isOff { h.DB.RemoveDayOff(today) text = "āœ… Day off removed" } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } func (h *Handler) backToMenu(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) edit := tgbotapi.NewEditMessageText(chatID, msgID, "Welcome! Choose an action:") kb := mainKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } // --- Scheduled report --- func (h *Handler) SendDailyReport(chatID int64) { text := h.buildDailyReport(time.Now()) reply := tgbotapi.NewMessage(chatID, text) h.Bot.Send(reply) } // --- Pure logic --- func (h *Handler) doClockIn() error { last, err := h.DB.GetLastEvent() if err != nil && err != sql.ErrNoRows { return err } if last != nil && last.EventType == "in" { return errors.New("āš ļø You are already clocked in") } if _, err := h.DB.GetSetting("remote_flag"); err != nil { h.DB.SetSetting("remote_flag", "onsite") } return h.DB.CreateEvent("in", time.Now().Unix(), "") } func (h *Handler) doClockOut() error { last, err := h.DB.GetLastEvent() if err != nil { return err } if last == nil { return errors.New("āš ļø No clock-in found. Start with /clockin first") } switch last.EventType { case "in": return h.DB.CreateEvent("out", time.Now().Unix(), "") case "out": return errors.New("āš ļø You are already clocked out") default: return errors.New("āš ļø Error processing request") } } // --- Helpers --- func formatDuration(seconds int64) string { hours := seconds / 3600 mins := (seconds % 3600) / 60 if hours > 0 { return fmt.Sprintf("%dh %dm", hours, mins) } return fmt.Sprintf("%dm", mins) } func (h *Handler) sendText(chatID int64, text string) { reply := tgbotapi.NewMessage(chatID, text) h.Bot.Send(reply) } func (h *Handler) sendSuccessWithMenu(chatID int64, text string) { reply := tgbotapi.NewMessage(chatID, text) reply.ReplyMarkup = mainKeyboard() h.Bot.Send(reply) }