package bot import ( "database/sql" "errors" "fmt" "log/slog" "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} } type actionFunc func(int64) (string, error) func (h *Handler) handleActionMsg(msg *tgbotapi.Message, fn actionFunc) { text, err := fn(msg.Chat.ID) if err != nil { h.sendText(msg.Chat.ID, err.Error()) } else { h.sendSuccessWithMenu(msg.Chat.ID, text) } } func (h *Handler) handleActionCallback(chatID int64, msgID int, callbackID string, fn actionFunc) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) text, err := fn(chatID) if err != nil { text = err.Error() } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) } // --- Entry points --- func (h *Handler) HandleMessage(update tgbotapi.Update) { msg := update.Message if len(h.AllowedUsers) > 0 && !h.AllowedUsers[msg.Chat.ID] { slog.Warn("unauthorized message", "chat_id", msg.Chat.ID, "user", msg.From.UserName, "text", msg.Text) return } slog.Info("message", "chat_id", msg.Chat.ID, "text", msg.Text) switch msg.Text { case "/start": h.handleStart(msg) case "/clockin", "Clock In": h.handleActionMsg(msg, h.clockIn) case "/clockout", "Clock Out": h.handleActionMsg(msg, h.clockOut) case "/remote": h.handleActionMsg(msg, h.toggleRemote) case "/report": h.handleActionMsg(msg, h.report) case "/export": h.handleExport(msg) case "/dayoff": h.handleActionMsg(msg, h.dayOff) 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] { slog.Warn("unauthorized callback", "chat_id", cb.Message.Chat.ID, "data", cb.Data) h.Bot.Request(tgbotapi.NewCallback(cb.ID, "Unauthorized")) return } slog.Info("callback", "chat_id", cb.Message.Chat.ID, "data", cb.Data) chatID := cb.Message.Chat.ID msgID := cb.Message.MessageID switch cb.Data { case "clockin": h.handleActionCallback(chatID, msgID, cb.ID, h.clockIn) case "clockout": h.handleActionCallback(chatID, msgID, cb.ID, h.clockOut) case "remote": h.handleActionCallback(chatID, msgID, cb.ID, h.toggleRemote) case "report": h.handleActionCallback(chatID, msgID, cb.ID, h.report) case "export": h.exportCallback(chatID, msgID, cb.ID) case "dayoff": h.handleActionCallback(chatID, msgID, cb.ID, h.dayOff) case "back_menu": h.backToMenu(chatID, msgID, cb.ID) } } // --- Actions (shared by msg + callback) --- func (h *Handler) clockIn(chatID int64) (string, error) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(chatID, today) if err != nil { return "", err } if isOff { return "", errors.New("Today is a day off. Use /dayoff to remove it first.") } last, err := h.DB.GetLastEvent(chatID) if err != nil && err != sql.ErrNoRows { return "", err } if last != nil && last.EventType == "in" { return "", errors.New("Already clocked in") } if _, err := h.DB.GetSetting(chatID, "remote_flag"); err != nil { h.DB.SetSetting(chatID, "remote_flag", "onsite") } if err := h.DB.CreateEvent(chatID, "in", time.Now().Unix(), ""); err != nil { return "", err } return "Clocked in at " + time.Now().Format("15:04"), nil } func (h *Handler) clockOut(chatID int64) (string, error) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(chatID, today) if err != nil { return "", err } if isOff { return "", errors.New("Today is a day off. Use /dayoff to remove it first.") } last, err := h.DB.GetLastEvent(chatID) if err != nil { return "", err } if last == nil { return "", errors.New("No clock-in found. Start with /clockin first") } if last.EventType == "out" { return "", errors.New("Already clocked out") } if err := h.DB.CreateEvent(chatID, "out", time.Now().Unix(), ""); err != nil { return "", err } return "Clocked out at " + time.Now().Format("15:04"), nil } func (h *Handler) toggleRemote(chatID int64) (string, error) { current, err := h.DB.GetSetting(chatID, "remote_flag") if err != nil { current = "onsite" } var newMode, text string if current == "remote" { newMode = "onsite" text = "Onsite mode enabled" } else { newMode = "remote" text = "Remote mode enabled" } if err := h.DB.SetSetting(chatID, "remote_flag", newMode); err != nil { return "", err } return text, nil } func (h *Handler) dayOff(chatID int64) (string, error) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(chatID, today) if err != nil { return "", err } if isOff { if err := h.DB.RemoveDayOff(chatID, today); err != nil { return "", err } return "Day off removed", nil } if err := h.DB.SetDayOff(chatID, today, ""); err != nil { return "", err } return "Today marked as day off", nil } func (h *Handler) report(chatID int64) (string, error) { return h.buildDailyReport(chatID, time.Now()), nil } // --- /start --- func (h *Handler) handleStart(msg *tgbotapi.Message) { h.DB.SetSetting(0, "report_chat_id", fmt.Sprintf("%d", msg.Chat.ID)) slog.Info("start", "chat_id", msg.Chat.ID) reply := tgbotapi.NewMessage(msg.Chat.ID, "We hope you have a happy day working.") reply.ReplyMarkup = quickKeyboard() h.Bot.Send(reply) menu := tgbotapi.NewMessage(msg.Chat.ID, "Welcome. Choose an action:") menu.ReplyMarkup = mainKeyboard() h.Bot.Send(menu) } // --- Export (different flow — sends a file) --- func (h *Handler) handleExport(msg *tgbotapi.Message) { now := time.Now() slog.Info("export", "chat_id", msg.Chat.ID, "year", now.Year(), "month", now.Month()) data, err := GenerateMonthlyReport(h.DB, msg.Chat.ID, now.Year(), now.Month()) if err != nil { slog.Error("generate report", "error", err) h.sendText(msg.Chat.ID, "Error generating report") return } slog.Info("report generated", "bytes", len(data)) 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 { slog.Error("send document", "error", err) h.sendText(msg.Chat.ID, "Error sending file") } } func (h *Handler) exportCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) now := time.Now() slog.Info("export", "chat_id", chatID, "year", now.Year(), "month", now.Month()) data, err := GenerateMonthlyReport(h.DB, chatID, now.Year(), now.Month()) if err != nil { slog.Error("generate report", "error", err) edit := tgbotapi.NewEditMessageText(chatID, msgID, "Error generating report") kb := backKeyboard() edit.ReplyMarkup = &kb h.Bot.Send(edit) return } slog.Info("report generated", "bytes", len(data)) edit := tgbotapi.NewEditMessageText(chatID, msgID, "Report ready:") 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, }) if _, err := h.Bot.Send(doc); err != nil { slog.Error("send document", "error", err) } } // --- Back to menu --- 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) } // --- Daily report builder --- func (h *Handler) buildDailyReport(chatID int64, now time.Time) string { dateStr := now.Format("2006-01-02") isOff, _ := h.DB.IsDayOff(chatID, dateStr) events, err := h.DB.EventsForDay(chatID, dateStr) if err != nil { return "Error fetching events." } if len(events) == 0 { if isOff { return fmt.Sprintf("%s — Day Off", dateStr) } return fmt.Sprintf("%s — No events recorded.", dateStr) } mode := "Onsite" current, err := h.DB.GetSetting(chatID, "remote_flag") if err == nil && current == "remote" { mode = "Remote" } totals := ComputeDailyTotals(events) if totals.PairCount == 0 { t := time.Unix(events[0].OccurredAt, 0).Format("15:04") return fmt.Sprintf("%s\nMode: %s\nClocked in at %s\n\nStill working — no clock-out yet.", dateStr, mode, t) } lines := fmt.Sprintf("Report for %s\nMode: %s", dateStr, mode) if isOff { lines += "\nDay Off: Yes" } lines += "\n\n" for _, e := range events { t := time.Unix(e.OccurredAt, 0).Format("15:04") label := "IN" action := "Clock In" if e.EventType == "out" { label = "OUT" action = "Clock Out" } lines += fmt.Sprintf("%s %s — %s\n", label, t, action) } workStr := formatDuration(totals.TotalSeconds) breakStr := formatDuration(totals.BreakSeconds) lines += fmt.Sprintf("\nSummary:\n Work: %s\n Break: %s\n", workStr, breakStr) return lines } // --- Scheduled report --- func (h *Handler) SendDailyReport(chatID int64) { text := h.buildDailyReport(chatID, time.Now()) reply := tgbotapi.NewMessage(chatID, text) reply.ReplyMarkup = quickKeyboard() h.Bot.Send(reply) } // --- Keyboards --- 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"), ), ) } // --- 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) reply.ReplyMarkup = quickKeyboard() h.Bot.Send(reply) } func (h *Handler) sendSuccessWithMenu(chatID int64, text string) { reply := tgbotapi.NewMessage(chatID, text) reply.ReplyMarkup = mainKeyboard() h.Bot.Send(reply) }