Clean up: remove unused packages, switch to slog, tidy Makefile

This commit is contained in:
2026-06-23 22:34:01 +03:30
parent 32446a99d1
commit b4fab29d45
7 changed files with 122 additions and 60 deletions

View File

@@ -20,8 +20,6 @@ WORKDIR /data
COPY --from=builder /usr/local/bin/worktime-bot /usr/local/bin/worktime-bot COPY --from=builder /usr/local/bin/worktime-bot /usr/local/bin/worktime-bot
COPY --from=builder /src/db/schema.sql ./db/schema.sql COPY --from=builder /src/db/schema.sql ./db/schema.sql
# i18n removed — strings are hardcoded in handlers
VOLUME ["/data"] VOLUME ["/data"]
CMD ["worktime-bot"] CMD ["worktime-bot"]

View File

@@ -5,7 +5,7 @@ BUILD_DIR=.build
build: $(BUILD_DIR)/$(BINARY) 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) mkdir -p $(BUILD_DIR)
go build -o $(BUILD_DIR)/$(BINARY) ./cmd/bot/ go build -o $(BUILD_DIR)/$(BINARY) ./cmd/bot/

View File

@@ -1,7 +1,7 @@
package main package main
import ( import (
"log" "log/slog"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
@@ -16,6 +16,10 @@ import (
) )
func main() { func main() {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
})))
godotenv.Load() godotenv.Load()
token := os.Getenv("BOT_TOKEN") token := os.Getenv("BOT_TOKEN")
@@ -25,29 +29,34 @@ func main() {
botAPI, err := tgbotapi.NewBotAPIWithClient(token, tgbotapi.APIEndpoint, httpClient) botAPI, err := tgbotapi.NewBotAPIWithClient(token, tgbotapi.APIEndpoint, httpClient)
if err != nil { if err != nil {
log.Fatal(err) slog.Error("failed to create bot API", "error", err)
os.Exit(1)
} }
dbStore, err := db.NewStore(dbPath) dbStore, err := db.NewStore(dbPath)
if err != nil { 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")) allowedUsers := parseAllowedUsers(os.Getenv("BOT_ALLOWED_USERS"))
handler := bot.NewHandler(botAPI, dbStore, allowedUsers) 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") webhookURL := os.Getenv("BOT_WEBHOOK_URL")
if webhookURL != "" { if webhookURL != "" {
startWebhook(botAPI, handler, webhookURL) startWebhook(botAPI, handler, webhookURL)
} else { } else {
if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil { 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) go dailyReportScheduler(handler, dbStore)
u := tgbotapi.NewUpdate(0) u := tgbotapi.NewUpdate(0)
@@ -74,6 +83,8 @@ func parseAllowedUsers(raw string) map[int64]bool {
id, err := strconv.ParseInt(s, 10, 64) id, err := strconv.ParseInt(s, 10, 64)
if err == nil { if err == nil {
m[id] = true m[id] = true
} else {
slog.Warn("invalid user ID in BOT_ALLOWED_USERS", "value", s)
} }
} }
return m return m
@@ -86,16 +97,20 @@ func dailyReportScheduler(h *bot.Handler, store *db.Store) {
if now.After(next) { if now.After(next) {
next = next.AddDate(0, 0, 1) next = next.AddDate(0, 0, 1)
} }
slog.Info("daily report scheduler", "next_run", next)
time.Sleep(time.Until(next)) time.Sleep(time.Until(next))
chatIDStr, err := store.GetSetting("chat_id") chatIDStr, err := store.GetSetting("chat_id")
if err != nil { if err != nil {
slog.Error("daily report: chat_id not found")
continue continue
} }
chatID, err := strconv.ParseInt(chatIDStr, 10, 64) chatID, err := strconv.ParseInt(chatIDStr, 10, 64)
if err != nil { if err != nil {
slog.Error("daily report: invalid chat_id", "value", chatIDStr)
continue continue
} }
slog.Info("sending daily report", "chat_id", chatID)
h.SendDailyReport(chatID) h.SendDailyReport(chatID)
} }
} }

View File

@@ -1,7 +1,7 @@
package main package main
import ( import (
"log" "log/slog"
"net/http" "net/http"
"os" "os"
@@ -10,49 +10,48 @@ import (
"worktimeBot/internal/bot" "worktimeBot/internal/bot"
) )
// startWebhook configures the Telegram webhook and starts the HTTP(S) listener.
func startWebhook(botAPI *tgbotapi.BotAPI, handler *bot.Handler, webhookURL string) { func startWebhook(botAPI *tgbotapi.BotAPI, handler *bot.Handler, webhookURL string) {
// Delete any previously set webhook
if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil { 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) wh, err := tgbotapi.NewWebhook(webhookURL)
if err != nil { if err != nil {
log.Fatal("NewWebhook:", err) slog.Error("new webhook", "error", err)
os.Exit(1)
} }
if _, err := botAPI.Request(wh); err != nil { 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") updates := botAPI.ListenForWebhook("/webhook")
// Determine where to listen
listenAddr := getEnvDefault("BOT_LISTEN", ":8080") listenAddr := getEnvDefault("BOT_LISTEN", ":8080")
tlsCert := os.Getenv("BOT_TLS_CERT") tlsCert := os.Getenv("BOT_TLS_CERT")
tlsKey := os.Getenv("BOT_TLS_KEY") tlsKey := os.Getenv("BOT_TLS_KEY")
if tlsCert != "" && tlsKey != "" { if tlsCert != "" && tlsKey != "" {
log.Printf("Starting HTTPS webhook on %s", listenAddr) slog.Info("starting HTTPS webhook", "addr", listenAddr)
go func() { go func() {
if err := http.ListenAndServeTLS(listenAddr, tlsCert, tlsKey, nil); err != nil { 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 { } 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() { go func() {
if err := http.ListenAndServe(listenAddr, nil); err != nil { 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 { for update := range updates {
if update.Message != nil { if update.Message != nil {
handler.HandleMessage(update) handler.HandleMessage(update)

View File

@@ -46,6 +46,17 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte,
}, },
Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center"}, 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") 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.SetCellStyle(sheet, "A1", "E1", titleStyle)
f.SetRowHeight(sheet, 1, 30) 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 { for i, h := range headers {
cell, _ := excelize.CoordinatesToCellName(i+1, 2) cell, _ := excelize.CoordinatesToCellName(i+1, 2)
f.SetCellValue(sheet, cell, h) 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) firstDay := time.Date(year, month, 1, 0, 0, 0, 0, loc)
lastDay := firstDay.AddDate(0, 1, -1) lastDay := firstDay.AddDate(0, 1, -1)
var totalWork, totalBreak int64
for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 0, 1) { for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 0, 1) {
dateStr := d.Format("2006-01-02") dateStr := d.Format("2006-01-02")
@@ -90,6 +103,9 @@ func GenerateMonthlyReport(store *db.Store, year int, month time.Month) ([]byte,
} }
totals := ComputeDailyTotals(events) totals := ComputeDailyTotals(events)
totalWork += totals.TotalSeconds
totalBreak += totals.BreakSeconds
cellDate, _ := excelize.CoordinatesToCellName(1, row) cellDate, _ := excelize.CoordinatesToCellName(1, row)
f.SetCellValue(sheet, cellDate, dateStr) f.SetCellValue(sheet, cellDate, dateStr)
f.SetCellStyle(sheet, cellDate, cellDate, dataStyle) 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) cellOut, _ := excelize.CoordinatesToCellName(3, row)
f.SetCellValue(sheet, cellIn, time.Unix(events[0].OccurredAt, 0).Format("15:04")) f.SetCellValue(sheet, cellIn, time.Unix(events[0].OccurredAt, 0).Format("15:04"))
f.SetCellStyle(sheet, cellIn, cellIn, dataStyle) 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.SetCellValue(sheet, cellOut, time.Unix(events[len(events)-1].OccurredAt, 0).Format("15:04"))
} }
f.SetCellStyle(sheet, cellOut, cellOut, dataStyle) f.SetCellStyle(sheet, cellOut, cellOut, dataStyle)
} }
cellWork, _ := excelize.CoordinatesToCellName(4, row) cellWork, _ := excelize.CoordinatesToCellName(4, row)
hours := float64(totals.TotalSeconds) / 3600.0 f.SetCellValue(sheet, cellWork, fmtHHMM(totals.TotalSeconds))
f.SetCellValue(sheet, cellWork, fmt.Sprintf("%.2f", hours))
f.SetCellStyle(sheet, cellWork, cellWork, dataStyle) f.SetCellStyle(sheet, cellWork, cellWork, dataStyle)
cellBreak, _ := excelize.CoordinatesToCellName(5, row) cellBreak, _ := excelize.CoordinatesToCellName(5, row)
breakMin := totals.BreakSeconds / 60 f.SetCellValue(sheet, cellBreak, fmtHHMM(totals.BreakSeconds))
f.SetCellValue(sheet, cellBreak, breakMin)
f.SetCellStyle(sheet, cellBreak, cellBreak, dataStyle) f.SetCellStyle(sheet, cellBreak, cellBreak, dataStyle)
row++ 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() buf, err := f.WriteToBuffer()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return buf.Bytes(), nil 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)
}

View File

@@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"log/slog"
"time" "time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 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) { func (h *Handler) HandleMessage(update tgbotapi.Update) {
msg := update.Message msg := update.Message
if len(h.AllowedUsers) > 0 && !h.AllowedUsers[msg.Chat.ID] { 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 return
} }
slog.Info("message", "chat_id", msg.Chat.ID, "text", msg.Text)
switch msg.Text { switch msg.Text {
case "/start": case "/start":
h.handleStart(msg) h.handleStart(msg)
@@ -49,9 +52,11 @@ func (h *Handler) HandleMessage(update tgbotapi.Update) {
func (h *Handler) HandleCallback(update tgbotapi.Update) { func (h *Handler) HandleCallback(update tgbotapi.Update) {
cb := update.CallbackQuery cb := update.CallbackQuery
if len(h.AllowedUsers) > 0 && !h.AllowedUsers[cb.Message.Chat.ID] { 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")) h.Bot.Request(tgbotapi.NewCallback(cb.ID, "Unauthorized"))
return return
} }
slog.Info("callback", "chat_id", cb.Message.Chat.ID, "data", cb.Data)
chatID := cb.Message.Chat.ID chatID := cb.Message.Chat.ID
msgID := cb.Message.MessageID msgID := cb.Message.MessageID
switch cb.Data { switch cb.Data {
@@ -76,15 +81,11 @@ func (h *Handler) HandleCallback(update tgbotapi.Update) {
func (h *Handler) handleStart(msg *tgbotapi.Message) { func (h *Handler) handleStart(msg *tgbotapi.Message) {
h.DB.SetSetting("chat_id", fmt.Sprintf("%d", msg.Chat.ID)) h.DB.SetSetting("chat_id", fmt.Sprintf("%d", msg.Chat.ID))
slog.Info("start", "chat_id", msg.Chat.ID)
text := "Welcome! Choose an action:" text := "Welcome! Choose an action:"
reply := tgbotapi.NewMessage(msg.Chat.ID, text) reply := tgbotapi.NewMessage(msg.Chat.ID, text)
reply.ReplyMarkup = mainKeyboard() reply.ReplyMarkup = mainKeyboard()
h.Bot.Send(reply) h.Bot.Send(reply)
kb := quickKeyboard()
quick := tgbotapi.NewMessage(msg.Chat.ID, "—")
quick.ReplyMarkup = kb
h.Bot.Send(quick)
} }
func quickKeyboard() tgbotapi.ReplyKeyboardMarkup { func quickKeyboard() tgbotapi.ReplyKeyboardMarkup {
@@ -125,16 +126,20 @@ func backKeyboard() tgbotapi.InlineKeyboardMarkup {
func (h *Handler) handleClockInMsg(msg *tgbotapi.Message) { func (h *Handler) handleClockInMsg(msg *tgbotapi.Message) {
if err := h.doClockIn(); err != nil { 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()) h.sendText(msg.Chat.ID, err.Error())
} else { } else {
slog.Info("clocked in", "chat_id", msg.Chat.ID)
h.sendSuccessWithMenu(msg.Chat.ID, "✅ Clocked in at "+time.Now().Format("15:04")) h.sendSuccessWithMenu(msg.Chat.ID, "✅ Clocked in at "+time.Now().Format("15:04"))
} }
} }
func (h *Handler) handleClockOutMsg(msg *tgbotapi.Message) { func (h *Handler) handleClockOutMsg(msg *tgbotapi.Message) {
if err := h.doClockOut(); err != nil { 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()) h.sendText(msg.Chat.ID, err.Error())
} else { } else {
slog.Info("clocked out", "chat_id", msg.Chat.ID)
h.sendSuccessWithMenu(msg.Chat.ID, "✅ Clocked out at "+time.Now().Format("15:04")) 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" text = "🏢 Onsite mode enabled"
} }
if err := h.DB.SetSetting("remote_flag", newMode); err != nil { if err := h.DB.SetSetting("remote_flag", newMode); err != nil {
slog.Error("toggle remote", "error", err)
h.sendText(msg.Chat.ID, "Error toggling mode") h.sendText(msg.Chat.ID, "Error toggling mode")
return return
} }
slog.Info("remote toggled", "mode", newMode)
h.sendText(msg.Chat.ID, text) h.sendText(msg.Chat.ID, text)
} }
func (h *Handler) handleReport(msg *tgbotapi.Message) { func (h *Handler) handleReport(msg *tgbotapi.Message) {
text := h.buildDailyReport(time.Now()) text := h.buildDailyReport(time.Now())
slog.Info("report", "chat_id", msg.Chat.ID)
reply := tgbotapi.NewMessage(msg.Chat.ID, text) reply := tgbotapi.NewMessage(msg.Chat.ID, text)
h.Bot.Send(reply) h.Bot.Send(reply)
} }
@@ -212,16 +220,20 @@ func (h *Handler) buildDailyReport(now time.Time) string {
func (h *Handler) handleExport(msg *tgbotapi.Message) { func (h *Handler) handleExport(msg *tgbotapi.Message) {
now := time.Now() now := time.Now()
year, month := now.Year(), now.Month() year, month := now.Year(), now.Month()
slog.Info("export requested", "year", year, "month", month)
data, err := GenerateMonthlyReport(h.DB, year, month) data, err := GenerateMonthlyReport(h.DB, year, month)
if err != nil { if err != nil {
slog.Error("generate report", "error", err)
h.sendText(msg.Chat.ID, "Error generating report") h.sendText(msg.Chat.ID, "Error generating report")
return return
} }
slog.Info("report generated", "bytes", len(data))
doc := tgbotapi.NewDocument(msg.Chat.ID, tgbotapi.FileBytes{ doc := tgbotapi.NewDocument(msg.Chat.ID, tgbotapi.FileBytes{
Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")), Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")),
Bytes: data, Bytes: data,
}) })
if _, err := h.Bot.Send(doc); err != nil { if _, err := h.Bot.Send(doc); err != nil {
slog.Error("send document", "error", err)
h.sendText(msg.Chat.ID, "Error sending file") 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") today := time.Now().Format("2006-01-02")
isOff, err := h.DB.IsDayOff(today) isOff, err := h.DB.IsDayOff(today)
if err != nil { if err != nil {
slog.Error("day off check", "error", err)
h.sendText(msg.Chat.ID, "Error checking day off") h.sendText(msg.Chat.ID, "Error checking day off")
return return
} }
if isOff { if isOff {
if err := h.DB.RemoveDayOff(today); err != nil { if err := h.DB.RemoveDayOff(today); err != nil {
slog.Error("remove day off", "error", err)
h.sendText(msg.Chat.ID, "Error removing day off") h.sendText(msg.Chat.ID, "Error removing day off")
return return
} }
slog.Info("day off removed")
h.sendText(msg.Chat.ID, "✅ Day off removed") h.sendText(msg.Chat.ID, "✅ Day off removed")
} else { } else {
if err := h.DB.SetDayOff(today, ""); err != nil { if err := h.DB.SetDayOff(today, ""); err != nil {
slog.Error("set day off", "error", err)
h.sendText(msg.Chat.ID, "Error setting day off") h.sendText(msg.Chat.ID, "Error setting day off")
return return
} }
slog.Info("day off set")
h.sendText(msg.Chat.ID, "✅ Today marked as day off") 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") text := "✅ Clocked in at " + time.Now().Format("15:04")
if err := h.doClockIn(); err != nil { if err := h.doClockIn(); err != nil {
text = err.Error() 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) edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := backKeyboard() 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") text := "✅ Clocked out at " + time.Now().Format("15:04")
if err := h.doClockOut(); err != nil { if err := h.doClockOut(); err != nil {
text = err.Error() 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) edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := backKeyboard() kb := backKeyboard()
@@ -287,8 +310,10 @@ func (h *Handler) toggleRemoteCallback(chatID int64, msgID int, callbackID strin
text = "🏢 Onsite mode enabled" text = "🏢 Onsite mode enabled"
} }
if err := h.DB.SetSetting("remote_flag", newMode); err != nil { if err := h.DB.SetSetting("remote_flag", newMode); err != nil {
slog.Error("toggle remote", "error", err)
return return
} }
slog.Info("remote toggled", "mode", newMode)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text) edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := backKeyboard() kb := backKeyboard()
edit.ReplyMarkup = &kb 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) { func (h *Handler) reportCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
text := h.buildDailyReport(time.Now()) text := h.buildDailyReport(time.Now())
slog.Info("report", "chat_id", chatID)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text) edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := backKeyboard() kb := backKeyboard()
edit.ReplyMarkup = &kb edit.ReplyMarkup = &kb
@@ -308,14 +334,17 @@ func (h *Handler) exportCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, "")) defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
now := time.Now() now := time.Now()
year, month := now.Year(), now.Month() year, month := now.Year(), now.Month()
slog.Info("export", "chat_id", chatID, "year", year, "month", month)
data, err := GenerateMonthlyReport(h.DB, year, month) data, err := GenerateMonthlyReport(h.DB, year, month)
if err != nil { if err != nil {
slog.Error("generate report", "error", err)
edit := tgbotapi.NewEditMessageText(chatID, msgID, "Error generating report") edit := tgbotapi.NewEditMessageText(chatID, msgID, "Error generating report")
kb := backKeyboard() kb := backKeyboard()
edit.ReplyMarkup = &kb edit.ReplyMarkup = &kb
h.Bot.Send(edit) h.Bot.Send(edit)
return return
} }
slog.Info("report generated", "bytes", len(data))
edit := tgbotapi.NewEditMessageText(chatID, msgID, "Here is your report:") edit := tgbotapi.NewEditMessageText(chatID, msgID, "Here is your report:")
kb := backKeyboard() kb := backKeyboard()
edit.ReplyMarkup = &kb 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")), Name: fmt.Sprintf("worktime_%s.xlsx", now.Format("2006_01")),
Bytes: data, 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) { 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") today := time.Now().Format("2006-01-02")
isOff, err := h.DB.IsDayOff(today) isOff, err := h.DB.IsDayOff(today)
if err != nil { if err != nil {
slog.Error("day off check", "error", err)
return return
} }
text := "✅ Today marked as day off" text := "✅ Today marked as day off"
if isOff { if isOff {
h.DB.RemoveDayOff(today) h.DB.RemoveDayOff(today)
text = "✅ Day off removed" text = "✅ Day off removed"
slog.Info("day off removed")
} else {
slog.Info("day off set")
} }
edit := tgbotapi.NewEditMessageText(chatID, msgID, text) edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := backKeyboard() kb := backKeyboard()
@@ -358,6 +393,7 @@ func (h *Handler) backToMenu(chatID int64, msgID int, callbackID string) {
func (h *Handler) SendDailyReport(chatID int64) { func (h *Handler) SendDailyReport(chatID int64) {
text := h.buildDailyReport(time.Now()) text := h.buildDailyReport(time.Now())
reply := tgbotapi.NewMessage(chatID, text) reply := tgbotapi.NewMessage(chatID, text)
reply.ReplyMarkup = quickKeyboard()
h.Bot.Send(reply) h.Bot.Send(reply)
} }
@@ -408,6 +444,7 @@ func formatDuration(seconds int64) string {
func (h *Handler) sendText(chatID int64, text string) { func (h *Handler) sendText(chatID int64, text string) {
reply := tgbotapi.NewMessage(chatID, text) reply := tgbotapi.NewMessage(chatID, text)
reply.ReplyMarkup = quickKeyboard()
h.Bot.Send(reply) h.Bot.Send(reply)
} }

View File

@@ -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
}