Files
website/internal/handlers/template/templatedata.go

62 lines
1.7 KiB
Go

// internal/handlers/template/templatedata.go
package templateHandler
import (
"net/http"
messageStorage "synlotto-website/internal/storage/messages"
notificationStorage "synlotto-website/internal/storage/notifications"
usersStorage "synlotto-website/internal/storage/users"
"synlotto-website/internal/models"
"synlotto-website/internal/platform/bootstrap"
"synlotto-website/internal/platform/sessionkeys"
)
// BuildTemplateData aggregates common UI data (user, notifications, messages)
// from the current SCS session + DB.
func BuildTemplateData(app *bootstrap.App, w http.ResponseWriter, r *http.Request) models.TemplateData {
sm := app.SessionManager
ctx := r.Context()
var (
user *models.User
isAdmin bool
notificationCount int
notifications []models.Notification
messageCount int
messages []models.Message
)
// Read user_id from SCS (may be int or int64 depending on writes)
if v := sm.Get(ctx, sessionkeys.UserID); v != nil {
var uid int64
switch t := v.(type) {
case int64:
uid = t
case int:
uid = int64(t)
}
if uid > 0 {
if u := usersStorage.GetUserByID(app.DB, int(uid)); u != nil {
user = u
isAdmin = u.IsAdmin
notificationCount = notificationStorage.GetNotificationCount(app.DB, int(u.Id))
notifications = notificationStorage.GetRecentNotifications(app.DB, int(u.Id), 15)
messageCount, _ = messageStorage.GetMessageCount(app.DB, int(u.Id))
messages = messageStorage.GetRecentMessages(app.DB, int(u.Id), 15)
}
}
}
return models.TemplateData{
User: user,
IsAdmin: isAdmin,
NotificationCount: notificationCount,
Notifications: notifications,
MessageCount: messageCount,
Messages: messages,
}
}