diff --git a/Dockerfile b/Dockerfile index 610d4e6..72e1ade 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,8 +20,6 @@ WORKDIR /data COPY --from=builder /usr/local/bin/worktime-bot /usr/local/bin/worktime-bot COPY --from=builder /src/db/schema.sql ./db/schema.sql -# i18n removed — strings are hardcoded in handlers - VOLUME ["/data"] CMD ["worktime-bot"] diff --git a/Makefile b/Makefile index 50754b7..3bbc709 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ BUILD_DIR=.build build: $(BUILD_DIR)/$(BINARY) -$(BUILD_DIR)/$(BINARY): cmd/bot/*.go internal/**/*.go pkg/**/*.go go.mod go.sum +$(BUILD_DIR)/$(BINARY): cmd/bot/*.go internal/**/*.go go.mod go.sum mkdir -p $(BUILD_DIR) go build -o $(BUILD_DIR)/$(BINARY) ./cmd/bot/ diff --git a/cmd/bot/main.go b/cmd/bot/main.go index 66171cb..a1fc71a 100644 --- a/cmd/bot/main.go +++ b/cmd/bot/main.go @@ -1,7 +1,7 @@ package main import ( - "log" + "log/slog" "net/http" "os" "strconv" @@ -16,6 +16,10 @@ import ( ) func main() { + slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + AddSource: true, + Level: slog.LevelInfo, + }))) godotenv.Load() token := os.Getenv("BOT_TOKEN") @@ -25,29 +29,34 @@ func main() { botAPI, err := tgbotapi.NewBotAPIWithClient(token, tgbotapi.APIEndpoint, httpClient) if err != nil { - log.Fatal(err) + slog.Error("failed to create bot API", "error", err) + os.Exit(1) } dbStore, err := db.NewStore(dbPath) if err != nil { - log.Fatal(err) + slog.Error("failed to open database", "path", dbPath, "error", err) + os.Exit(1) } allowedUsers := parseAllowedUsers(os.Getenv("BOT_ALLOWED_USERS")) handler := bot.NewHandler(botAPI, dbStore, allowedUsers) - log.Printf("Bot started. Allowed users: %d", len(allowedUsers)) + slog.Info("bot started", + "bot_user", botAPI.Self.UserName, + "allowed_users", len(allowedUsers), + "polling", true, + ) webhookURL := os.Getenv("BOT_WEBHOOK_URL") if webhookURL != "" { startWebhook(botAPI, handler, webhookURL) } else { if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil { - log.Printf("DeleteWebhook: %v", err) + slog.Error("delete webhook", "error", err) } - // Daily report scheduler go dailyReportScheduler(handler, dbStore) u := tgbotapi.NewUpdate(0) @@ -74,6 +83,8 @@ func parseAllowedUsers(raw string) map[int64]bool { id, err := strconv.ParseInt(s, 10, 64) if err == nil { m[id] = true + } else { + slog.Warn("invalid user ID in BOT_ALLOWED_USERS", "value", s) } } return m @@ -86,16 +97,20 @@ func dailyReportScheduler(h *bot.Handler, store *db.Store) { if now.After(next) { next = next.AddDate(0, 0, 1) } + slog.Info("daily report scheduler", "next_run", next) time.Sleep(time.Until(next)) chatIDStr, err := store.GetSetting("chat_id") if err != nil { + slog.Error("daily report: chat_id not found") continue } chatID, err := strconv.ParseInt(chatIDStr, 10, 64) if err != nil { + slog.Error("daily report: invalid chat_id", "value", chatIDStr) continue } + slog.Info("sending daily report", "chat_id", chatID) h.SendDailyReport(chatID) } } diff --git a/cmd/bot/webhook.go b/cmd/bot/webhook.go index 9007626..e0b30a7 100644 --- a/cmd/bot/webhook.go +++ b/cmd/bot/webhook.go @@ -1,7 +1,7 @@ package main import ( - "log" + "log/slog" "net/http" "os" @@ -10,49 +10,48 @@ import ( "worktimeBot/internal/bot" ) -// startWebhook configures the Telegram webhook and starts the HTTP(S) listener. func startWebhook(botAPI *tgbotapi.BotAPI, handler *bot.Handler, webhookURL string) { - // Delete any previously set webhook if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil { - log.Fatal("DeleteWebhook:", err) + slog.Error("delete webhook", "error", err) + os.Exit(1) } - // Set the new webhook wh, err := tgbotapi.NewWebhook(webhookURL) if err != nil { - log.Fatal("NewWebhook:", err) + slog.Error("new webhook", "error", err) + os.Exit(1) } if _, err := botAPI.Request(wh); err != nil { - log.Fatal("SetWebhook:", err) + slog.Error("set webhook", "error", err) + os.Exit(1) } - // Register the webhook endpoint and get the updates channel updates := botAPI.ListenForWebhook("/webhook") - // Determine where to listen listenAddr := getEnvDefault("BOT_LISTEN", ":8080") tlsCert := os.Getenv("BOT_TLS_CERT") tlsKey := os.Getenv("BOT_TLS_KEY") if tlsCert != "" && tlsKey != "" { - log.Printf("Starting HTTPS webhook on %s", listenAddr) + slog.Info("starting HTTPS webhook", "addr", listenAddr) go func() { if err := http.ListenAndServeTLS(listenAddr, tlsCert, tlsKey, nil); err != nil { - log.Fatal("HTTPS server:", err) + slog.Error("HTTPS server", "error", err) + os.Exit(1) } }() } else { - log.Printf("Starting HTTP webhook on %s (TLS handled by reverse proxy)", listenAddr) + slog.Info("starting HTTP webhook (TLS by reverse proxy)", "addr", listenAddr) go func() { if err := http.ListenAndServe(listenAddr, nil); err != nil { - log.Fatal("HTTP server:", err) + slog.Error("HTTP server", "error", err) + os.Exit(1) } }() } - log.Printf("Webhook registered at %s", webhookURL) + slog.Info("webhook registered", "url", webhookURL) - // Process incoming updates for update := range updates { if update.Message != nil { handler.HandleMessage(update) diff --git a/internal/bot/export.go b/internal/bot/export.go index 4502f7d..33337e7 100644 --- a/internal/bot/export.go +++ b/internal/bot/export.go @@ -46,6 +46,17 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte, }, Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center"}, }) + totalStyle, _ := f.NewStyle(&excelize.Style{ + Font: &excelize.Font{Bold: true, Size: 11}, + Fill: excelize.Fill{Type: "pattern", Pattern: 1, Color: []string{"D9E2F3"}}, + Border: []excelize.Border{ + {Type: "left", Color: "D9D9D9", Style: 1}, + {Type: "right", Color: "D9D9D9", Style: 1}, + {Type: "top", Color: "D9D9D9", Style: 1}, + {Type: "bottom", Color: "D9D9D9", Style: 2}, + }, + Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center"}, + }) monthName := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC).Format("January 2006") @@ -54,7 +65,7 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte, f.SetCellStyle(sheet, "A1", "E1", titleStyle) f.SetRowHeight(sheet, 1, 30) - headers := []string{"Date", "Clock In", "Clock Out", "Work (h)", "Break (m)"} + headers := []string{"Date", "Clock In", "Clock Out", "Work", "Break"} for i, h := range headers { cell, _ := excelize.CoordinatesToCellName(i+1, 2) f.SetCellValue(sheet, cell, h) @@ -73,6 +84,8 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte, firstDay := time.Date(year, month, 1, 0, 0, 0, 0, loc) lastDay := firstDay.AddDate(0, 1, -1) + var totalWork, totalBreak int64 + for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 0, 1) { dateStr := d.Format("2006-01-02") @@ -90,6 +103,9 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte, } totals := ComputeDailyTotals(events) + totalWork += totals.TotalSeconds + totalBreak += totals.BreakSeconds + cellDate, _ := excelize.CoordinatesToCellName(1, row) f.SetCellValue(sheet, cellDate, dateStr) f.SetCellStyle(sheet, cellDate, cellDate, dataStyle) @@ -99,28 +115,49 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte, cellOut, _ := excelize.CoordinatesToCellName(3, row) f.SetCellValue(sheet, cellIn, time.Unix(events[0].OccurredAt, 0).Format("15:04")) f.SetCellStyle(sheet, cellIn, cellIn, dataStyle) - if len(events) > 1 && events[len(events)-1].EventType == "out" { + if events[len(events)-1].EventType == "out" { f.SetCellValue(sheet, cellOut, time.Unix(events[len(events)-1].OccurredAt, 0).Format("15:04")) } f.SetCellStyle(sheet, cellOut, cellOut, dataStyle) } cellWork, _ := excelize.CoordinatesToCellName(4, row) - hours := float64(totals.TotalSeconds) / 3600.0 - f.SetCellValue(sheet, cellWork, fmt.Sprintf("%.2f", hours)) + f.SetCellValue(sheet, cellWork, fmtHHMM(totals.TotalSeconds)) f.SetCellStyle(sheet, cellWork, cellWork, dataStyle) cellBreak, _ := excelize.CoordinatesToCellName(5, row) - breakMin := totals.BreakSeconds / 60 - f.SetCellValue(sheet, cellBreak, breakMin) + f.SetCellValue(sheet, cellBreak, fmtHHMM(totals.BreakSeconds)) f.SetCellStyle(sheet, cellBreak, cellBreak, dataStyle) row++ } + row++ + + f.SetCellValue(sheet, fmt.Sprintf("A%d", row), "Total") + f.SetCellStyle(sheet, fmt.Sprintf("A%d", row), fmt.Sprintf("A%d", row), totalStyle) + f.SetCellValue(sheet, fmt.Sprintf("D%d", row), fmtDDHHMM(totalWork)) + f.SetCellStyle(sheet, fmt.Sprintf("D%d", row), fmt.Sprintf("D%d", row), totalStyle) + f.SetCellValue(sheet, fmt.Sprintf("E%d", row), fmtDDHHMM(totalBreak)) + f.SetCellStyle(sheet, fmt.Sprintf("E%d", row), fmt.Sprintf("E%d", row), totalStyle) + buf, err := f.WriteToBuffer() if err != nil { return nil, err } return buf.Bytes(), nil } + +func fmtHHMM(seconds int64) string { + hours := seconds / 3600 + mins := (seconds % 3600) / 60 + return fmt.Sprintf("%d:%02d", hours, mins) +} + +func fmtDDHHMM(seconds int64) string { + days := seconds / 86400 + rem := seconds % 86400 + hours := rem / 3600 + mins := (rem % 3600) / 60 + return fmt.Sprintf("%d:%02d:%02d", days, hours, mins) +} diff --git a/internal/bot/handlers.go b/internal/bot/handlers.go index 4efc24a..ed2d5d9 100644 --- a/internal/bot/handlers.go +++ b/internal/bot/handlers.go @@ -4,6 +4,7 @@ import ( "database/sql" "errors" "fmt" + "log/slog" "time" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" @@ -24,8 +25,10 @@ func NewHandler(bot *tgbotapi.BotAPI, store *db.Store, allowed map[int64]bool) * 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) @@ -49,9 +52,11 @@ func (h *Handler) HandleMessage(update tgbotapi.Update) { 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 { @@ -76,15 +81,11 @@ func (h *Handler) HandleCallback(update tgbotapi.Update) { func (h *Handler) handleStart(msg *tgbotapi.Message) { h.DB.SetSetting("chat_id", fmt.Sprintf("%d", msg.Chat.ID)) + slog.Info("start", "chat_id", 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, "—") - quick.ReplyMarkup = kb - h.Bot.Send(quick) } func quickKeyboard() tgbotapi.ReplyKeyboardMarkup { @@ -125,16 +126,20 @@ func backKeyboard() tgbotapi.InlineKeyboardMarkup { func (h *Handler) handleClockInMsg(msg *tgbotapi.Message) { if err := h.doClockIn(); err != nil { + slog.Error("clock in failed", "chat_id", msg.Chat.ID, "error", err) h.sendText(msg.Chat.ID, err.Error()) } else { + slog.Info("clocked in", "chat_id", msg.Chat.ID) 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 { + slog.Error("clock out failed", "chat_id", msg.Chat.ID, "error", err) h.sendText(msg.Chat.ID, err.Error()) } else { + slog.Info("clocked out", "chat_id", msg.Chat.ID) h.sendSuccessWithMenu(msg.Chat.ID, "✅ Clocked out at "+time.Now().Format("15:04")) } } @@ -151,14 +156,17 @@ func (h *Handler) toggleRemote(msg *tgbotapi.Message) { text = "🏢 Onsite mode enabled" } if err := h.DB.SetSetting("remote_flag", newMode); err != nil { + slog.Error("toggle remote", "error", err) h.sendText(msg.Chat.ID, "Error toggling mode") return } + slog.Info("remote toggled", "mode", newMode) h.sendText(msg.Chat.ID, text) } func (h *Handler) handleReport(msg *tgbotapi.Message) { text := h.buildDailyReport(time.Now()) + slog.Info("report", "chat_id", msg.Chat.ID) reply := tgbotapi.NewMessage(msg.Chat.ID, text) h.Bot.Send(reply) } @@ -212,16 +220,20 @@ func (h *Handler) buildDailyReport(now time.Time) string { func (h *Handler) handleExport(msg *tgbotapi.Message) { now := time.Now() year, month := now.Year(), now.Month() + slog.Info("export requested", "year", year, "month", month) data, err := GenerateMonthlyReport(h.DB, year, 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") } } @@ -230,20 +242,25 @@ func (h *Handler) handleDayOff(msg *tgbotapi.Message) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(today) if err != nil { + slog.Error("day off check", "error", err) h.sendText(msg.Chat.ID, "Error checking day off") return } if isOff { if err := h.DB.RemoveDayOff(today); err != nil { + slog.Error("remove day off", "error", err) h.sendText(msg.Chat.ID, "Error removing day off") return } + slog.Info("day off removed") h.sendText(msg.Chat.ID, "✅ Day off removed") } else { if err := h.DB.SetDayOff(today, ""); err != nil { + slog.Error("set day off", "error", err) h.sendText(msg.Chat.ID, "Error setting day off") return } + slog.Info("day off set") h.sendText(msg.Chat.ID, "✅ Today marked as day off") } } @@ -255,6 +272,9 @@ func (h *Handler) clockInCallback(chatID int64, msgID int, callbackID string) { text := "✅ Clocked in at " + time.Now().Format("15:04") if err := h.doClockIn(); err != nil { text = err.Error() + slog.Error("clock in failed", "chat_id", chatID, "error", err) + } else { + slog.Info("clocked in", "chat_id", chatID) } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() @@ -267,6 +287,9 @@ func (h *Handler) clockOutCallback(chatID int64, msgID int, callbackID string) { text := "✅ Clocked out at " + time.Now().Format("15:04") if err := h.doClockOut(); err != nil { text = err.Error() + slog.Error("clock out failed", "chat_id", chatID, "error", err) + } else { + slog.Info("clocked out", "chat_id", chatID) } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() @@ -287,8 +310,10 @@ func (h *Handler) toggleRemoteCallback(chatID int64, msgID int, callbackID strin text = "🏢 Onsite mode enabled" } if err := h.DB.SetSetting("remote_flag", newMode); err != nil { + slog.Error("toggle remote", "error", err) return } + slog.Info("remote toggled", "mode", newMode) edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb @@ -298,6 +323,7 @@ func (h *Handler) toggleRemoteCallback(chatID int64, msgID int, callbackID strin func (h *Handler) reportCallback(chatID int64, msgID int, callbackID string) { defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) text := h.buildDailyReport(time.Now()) + slog.Info("report", "chat_id", chatID) edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() edit.ReplyMarkup = &kb @@ -308,14 +334,17 @@ 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() + slog.Info("export", "chat_id", chatID, "year", year, "month", month) data, err := GenerateMonthlyReport(h.DB, year, 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, "Here is your report:") kb := backKeyboard() edit.ReplyMarkup = &kb @@ -324,7 +353,9 @@ func (h *Handler) exportCallback(chatID int64, msgID int, callbackID string) { Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")), Bytes: data, }) - h.Bot.Send(doc) + if _, err := h.Bot.Send(doc); err != nil { + slog.Error("send document", "error", err) + } } func (h *Handler) dayOffCallback(chatID int64, msgID int, callbackID string) { @@ -332,12 +363,16 @@ func (h *Handler) dayOffCallback(chatID int64, msgID int, callbackID string) { today := time.Now().Format("2006-01-02") isOff, err := h.DB.IsDayOff(today) if err != nil { + slog.Error("day off check", "error", err) return } text := "✅ Today marked as day off" if isOff { h.DB.RemoveDayOff(today) text = "✅ Day off removed" + slog.Info("day off removed") + } else { + slog.Info("day off set") } edit := tgbotapi.NewEditMessageText(chatID, msgID, text) kb := backKeyboard() @@ -358,6 +393,7 @@ func (h *Handler) backToMenu(chatID int64, msgID int, callbackID string) { func (h *Handler) SendDailyReport(chatID int64) { text := h.buildDailyReport(time.Now()) reply := tgbotapi.NewMessage(chatID, text) + reply.ReplyMarkup = quickKeyboard() h.Bot.Send(reply) } @@ -408,6 +444,7 @@ func formatDuration(seconds int64) string { func (h *Handler) sendText(chatID int64, text string) { reply := tgbotapi.NewMessage(chatID, text) + reply.ReplyMarkup = quickKeyboard() h.Bot.Send(reply) } diff --git a/internal/config/loader.go b/internal/config/loader.go deleted file mode 100644 index 10f9429..0000000 --- a/internal/config/loader.go +++ /dev/null @@ -1,24 +0,0 @@ -package config - -import ( - "encoding/json" - "os" -) - -type Config struct { - BotToken string `json:"bot_token"` - ProxyAddr string `json:"proxy_address"` - LogLevel string `json:"log_level"` -} - -func Load(path string) (*Config, error) { - data, err := os.ReadFile(path) - if err != nil { - return nil, err - } - var cfg Config - if err := json.Unmarshal(data, &cfg); err != nil { - return nil, err - } - return &cfg, nil -}