Files
website/internal/handlers/notifications.go

74 lines
2.6 KiB
Go

package handlers
import (
"log"
"net/http"
"strconv"
templateHandlers "synlotto-website/internal/handlers/template"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/platform/bootstrap"
"synlotto-website/internal/platform/sessionkeys"
notificationsStorage "synlotto-website/internal/storage/notifications"
)
// NotificationsHandler serves the notifications index page.
// New signature: accept *bootstrap.App (not *sql.DB)
func NotificationsHandler(app *bootstrap.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := templateHandlers.BuildTemplateData(app, w, r)
context := templateHelpers.TemplateContext(w, r, data)
tmpl := templateHelpers.LoadTemplateFiles("index.html", "web/templates/account/notifications/index.html")
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
log.Println("❌ Template render error:", err)
http.Error(w, "Error rendering notifications page", http.StatusInternalServerError)
return
}
}
}
// MarkNotificationReadHandler shows a single notification (and marks unread ones as read).
// New signature: accept *bootstrap.App; read user id from SCS session.
func MarkNotificationReadHandler(app *bootstrap.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
notificationIDStr := r.URL.Query().Get("id")
notificationID, err := strconv.Atoi(notificationIDStr)
if err != nil || notificationID <= 0 {
http.Error(w, "Invalid notification ID", http.StatusBadRequest)
return
}
// SCS-native session access
userID := app.SessionManager.GetInt(r.Context(), sessionkeys.UserID)
if userID == 0 {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Load + mark-as-read (if needed)
notification, err := notificationsStorage.GetNotificationByID(app.DB, userID, notificationID)
if err != nil {
log.Printf("❌ Notification not found or belongs to another user: %v", err)
notification = nil
} else if !notification.IsRead {
if err := notificationsStorage.MarkNotificationAsRead(app.DB, userID, notificationID); err != nil {
log.Printf("⚠️ Failed to mark as read: %v", err)
}
}
data := templateHandlers.BuildTemplateData(app, w, r)
context := templateHelpers.TemplateContext(w, r, data)
context["Notification"] = notification
tmpl := templateHelpers.LoadTemplateFiles("read.html", "web/templates/account/notifications/read.html")
if err := tmpl.ExecuteTemplate(w, "layout", context); err != nil {
log.Printf("❌ Template render error: %v", err)
http.Error(w, "Template render error", http.StatusInternalServerError)
return
}
}
}