77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"net/http"
|
|
|
|
httpHelpers "synlotto-website/internal/helpers/http"
|
|
securityHelpers "synlotto-website/internal/helpers/security"
|
|
templateHelpers "synlotto-website/internal/helpers/template"
|
|
|
|
"synlotto-website/internal/models"
|
|
usersStorage "synlotto-website/internal/storage/users"
|
|
)
|
|
|
|
var (
|
|
total, winners int
|
|
prizeSum float64
|
|
)
|
|
|
|
func AdminDashboardHandler(db *sql.DB) http.HandlerFunc {
|
|
return httpHelpers.AuthMiddleware(func(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := securityHelpers.GetCurrentUserID(r)
|
|
if !ok {
|
|
http.Redirect(w, r, "/account/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
user := usersStorage.GetUserByID(db, userID)
|
|
if user == nil {
|
|
http.Error(w, "User not found", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
data := models.TemplateData{}
|
|
context := templateHelpers.TemplateContext(w, r, data)
|
|
context["User"] = user
|
|
context["IsAdmin"] = user.IsAdmin
|
|
// ToDo: Missing messages, notifications, potentially syndicate notifictions if that becomes a new top bar icon.
|
|
db.QueryRow(`SELECT COUNT(*), SUM(CASE WHEN is_winner THEN 1 ELSE 0 END), SUM(prize_amount) FROM my_tickets`).Scan(&total, &winners, &prizeSum)
|
|
context["Stats"] = map[string]interface{}{
|
|
"TotalTickets": total,
|
|
"TotalWinners": winners,
|
|
"TotalPrizeAmount": prizeSum,
|
|
}
|
|
|
|
rows, err := db.Query(`
|
|
SELECT run_at, triggered_by, tickets_matched, winners_found, COALESCE(notes, '')
|
|
FROM log_ticket_matching
|
|
ORDER BY run_at DESC LIMIT 10
|
|
`)
|
|
if err != nil {
|
|
log.Println("⚠️ Failed to load logs:", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var logs []models.MatchLog
|
|
for rows.Next() {
|
|
var logEntry models.MatchLog
|
|
err := rows.Scan(&logEntry.RunAt, &logEntry.TriggeredBy, &logEntry.TicketsMatched, &logEntry.WinnersFound, &logEntry.Notes)
|
|
if err != nil {
|
|
log.Println("⚠️ Failed to scan log row:", err)
|
|
continue
|
|
}
|
|
logs = append(logs, logEntry)
|
|
}
|
|
context["MatchLogs"] = logs
|
|
|
|
tmpl := templateHelpers.LoadTemplateFiles("dashboard.html", "templates/admin/dashboard.html")
|
|
|
|
err = tmpl.ExecuteTemplate(w, "layout", context)
|
|
if err != nil {
|
|
http.Error(w, "Failed to render dashboard", http.StatusInternalServerError)
|
|
}
|
|
})
|
|
}
|