Feature: Full notification read view with conditional mark-as-read logic

- Added dedicated route and view for reading individual notifications (/account/notifications/read)
- Ensured notification is only marked as read if it hasn't already been
- Updated Notification model to use Subject and Body fields
- Fixed field references in templates (Title → Subject, Message → Body)
- Updated topbar dropdown to use correct field names and display logic
- Gracefully handle "notification not found" cases in template output
- Ensured consistent template parsing with layout and topbar inclusion
- Improved error logging for better diagnosis
This commit is contained in:
2025-04-01 23:08:58 +01:00
parent 06e647d00f
commit e5bf12ad77
10 changed files with 110 additions and 69 deletions

View File

@@ -19,8 +19,9 @@ func Login(w http.ResponseWriter, r *http.Request) {
return
}
tmpl := template.Must(template.ParseFiles(
tmpl := template.Must(template.New("login.html").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/topbar.html",
"templates/account/login.html",
))

View File

@@ -5,60 +5,23 @@ import (
"html/template"
"log"
"net/http"
"sort"
"synlotto-website/helpers"
"synlotto-website/models"
)
// Home shows latest Thunderball results
func Home(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`
SELECT id, draw_date, machine, ballset, ball1, ball2, ball3, ball4, ball5, thunderball
FROM results_thunderball
ORDER BY id DESC
`)
if err != nil {
log.Println("❌ DB error:", err)
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
var results []models.ThunderballResult
for rows.Next() {
var res models.ThunderballResult
err := rows.Scan(
&res.Id, &res.DrawDate, &res.Machine, &res.BallSet,
&res.Ball1, &res.Ball2, &res.Ball3, &res.Ball4, &res.Ball5, &res.Thunderball,
)
if err != nil {
log.Println("❌ Row scan error:", err)
continue
}
res.SortedBalls = []int{
res.Ball1, res.Ball2, res.Ball3, res.Ball4, res.Ball5,
}
sort.Ints(res.SortedBalls)
results = append(results, res)
}
data := BuildTemplateData(db, w, r)
context := helpers.TemplateContext(w, r, data)
context["Data"] = results
tmpl := template.Must(template.New("").Funcs(helpers.TemplateFuncs()).ParseFiles(
tmpl := template.Must(template.New("index.html").Funcs(helpers.TemplateFuncs()).ParseFiles(
"templates/layout.html",
"templates/topbar.html",
"templates/index.html",
))
err = tmpl.ExecuteTemplate(w, "layout", context)
err := tmpl.ExecuteTemplate(w, "layout", context)
if err != nil {
log.Println("❌ Template error:", err)
log.Println("❌ Template render error:", err)
http.Error(w, "Error rendering homepage", http.StatusInternalServerError)
}
}

View File

@@ -2,6 +2,7 @@ package handlers
import (
"database/sql"
"log"
"net/http"
"strconv"
"text/template"
@@ -20,11 +21,12 @@ func NotificationsHandler(db *sql.DB) http.HandlerFunc {
ParseFiles(
"templates/layout.html",
"templates/topbar.html",
"templates/account/notifications/index.html",
"templates/account/notifications.html",
))
err := tmpl.ExecuteTemplate(w, "layout", context)
if err != nil {
log.Println("❌ Template render error:", err)
http.Error(w, "Error rendering notifications page", http.StatusInternalServerError)
}
}
@@ -46,12 +48,33 @@ func MarkNotificationReadHandler(db *sql.DB) http.HandlerFunc {
return
}
err = storage.MarkNotificationAsRead(db, userID, notificationID)
notification, err := storage.GetNotificationByID(db, userID, notificationID)
if err != nil {
http.Error(w, "Failed to update", http.StatusInternalServerError)
return
log.Printf("❌ Notification not found or belongs to another user: %v", err)
notification = nil
} else if !notification.IsRead {
err = storage.MarkNotificationAsRead(db, userID, notificationID)
if err != nil {
log.Printf("⚠️ Failed to mark as read: %v", err)
}
}
http.Redirect(w, r, "/account/notifications", http.StatusSeeOther)
data := BuildTemplateData(db, w, r)
context := helpers.TemplateContext(w, r, data)
context["Notification"] = notification
tmpl := template.Must(template.New("read.html").
Funcs(helpers.TemplateFuncs()).
ParseFiles(
"templates/layout.html",
"templates/topbar.html",
"templates/account/notifications/read.html",
))
err = tmpl.ExecuteTemplate(w, "layout", context)
if err != nil {
log.Printf("❌ Template render error: %v", err)
http.Error(w, "Template render error", http.StatusInternalServerError)
}
}
}

View File

@@ -15,8 +15,9 @@ type User struct {
type Notification struct {
ID int
Title string
Message string
UserId int
Subject string
Body string
IsRead bool
CreatedAt time.Time
}

View File

@@ -39,7 +39,7 @@ func GetRecentNotifications(db *sql.DB, userID int, limit int) []models.Notifica
for rows.Next() {
var n models.Notification
if err := rows.Scan(&n.ID, &n.Title, &n.Message, &n.IsRead, &n.CreatedAt); err == nil {
if err := rows.Scan(&n.ID, &n.Subject, &n.Body, &n.IsRead, &n.CreatedAt); err == nil {
notifications = append(notifications, n)
}
}
@@ -49,11 +49,10 @@ func GetRecentNotifications(db *sql.DB, userID int, limit int) []models.Notifica
func MarkNotificationAsRead(db *sql.DB, userID int, notificationID int) error {
result, err := db.Exec(`
UPDATE notifications
UPDATE users_notification
SET is_read = TRUE
WHERE id = ? AND user_id = ?
`, notificationID, userID)
if err != nil {
return err
}
@@ -62,9 +61,25 @@ func MarkNotificationAsRead(db *sql.DB, userID int, notificationID int) error {
if err != nil {
return err
}
if rowsAffected == 0 {
return fmt.Errorf("no matching notification found or not owned by user")
return fmt.Errorf("no matching notification for user_id=%d and id=%d", userID, notificationID)
}
return nil
}
func GetNotificationByID(db *sql.DB, userID, notificationID int) (*models.Notification, error) {
row := db.QueryRow(`
SELECT id, user_id, subject, body, is_read
FROM users_notification
WHERE id = ? AND user_id = ?
`, notificationID, userID)
var n models.Notification
err := row.Scan(&n.ID, &n.UserId, &n.Subject, &n.Body, &n.IsRead)
if err != nil {
return nil, err
}
return &n, nil
}

View File

@@ -1,10 +1,23 @@
{{ define "content" }}
<h2>Login</h2>
<form method="POST" action="/login">
{{ .csrfField }}
<label>Username: <input type="text" name="username" required></label><br>
<label>Password: <input type="password" name="password" required></label><br>
<label><input type="checkbox" name="remember"> Remember Me</label>
<button type="submit">Login</button>
<form method="POST" action="/login" class="form">
{{ .CSRFField }}
<div class="mb-3">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required class="form-control">
</div>
<div class="mb-3">
<label for="password">Password:</label>
<input type="password" name="password" id="password" required class="form-control">
</div>
<div class="form-check mb-3">
<input type="checkbox" name="remember" id="remember" class="form-check-input">
<label for="remember" class="form-check-label">Remember Me</label>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
{{ end }}

View File

@@ -0,0 +1,23 @@
{{ define "notifications" }}
<div class="container py-4">
<h2 class="mb-4">Notifications</h2>
{{ if .Notifications }}
<ul class="list-group">
{{ range .Notifications }}
<li class="list-group-item d-flex justify-content-between align-items-start {{ if not .IsRead }}fw-bold{{ end }}">
<div class="ms-2 me-auto">
<div class="fw-semibold">{{ .Title }}</div>
<small class="text-muted">{{ .Message }}</small>
</div>
{{ if not .IsRead }}
<a href="/account/notifications/read?id={{ .ID }}" class="badge bg-primary text-decoration-none">Mark as read</a>
{{ end }}
</li>
{{ end }}
</ul>
{{ else }}
<div class="alert alert-info">You have no notifications.</div>
{{ end }}
</div>
{{ end }}

View File

@@ -1,12 +1,13 @@
{{ define "notifications_read" }}
{{ define "content" }}
<div class="container py-4">
<h2 class="mb-3">Notification</h2>
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ .Notification.Title }}</h5>
<p class="card-text">{{ .Notification.Message }}</p>
<a href="/account/notifications" class="btn btn-primary mt-3">Back to Notifications</a>
{{ if .Notification }}
<h2>{{ .Notification.Subject }}</h2>
<p>{{ .Notification.Body }}</p>
{{ else }}
<div class="alert alert-danger text-center">
Notification not found or access denied.
</div>
</div>
{{ end }}
<a href="/account/notifications" class="btn btn-secondary mt-4">Back to Notifications</a>
</div>
{{ end }}

View File

@@ -1,3 +1,4 @@
{{ define "content" }}
<h1>Welcome to SynLotto</h1>
<p>Your trusted lottery platform!</p>
{{ end }}

View File

@@ -55,8 +55,8 @@
<div class="d-flex align-items-start">
<i class="bi bi-info-circle text-primary me-2 fs-4"></i>
<div>
<div class="fw-semibold">{{ $n.Title }}</div>
<small class="text-muted">{{ $n.Message }}</small>
<div class="fw-semibold">{{ $n.Subject }}</div>
<small class="text-muted">{{ $n.Body }}</small>
</div>
</div>
</a>