Changes to pagination and fixing archive messages in progress

This commit is contained in:
2025-10-31 22:55:04 +00:00
parent 8529116ad2
commit 9dc01f925a
9 changed files with 219 additions and 41 deletions

View File

@@ -5,10 +5,13 @@
package accountMessageHandler
import (
"bytes"
"net/http"
"strconv"
templateHandlers "synlotto-website/internal/handlers/template"
templateHelpers "synlotto-website/internal/helpers/template"
errors "synlotto-website/internal/http/error"
"synlotto-website/internal/logging"
"synlotto-website/internal/platform/bootstrap"
@@ -22,30 +25,118 @@ import (
func (h *AccountMessageHandlers) ArchivedList(c *gin.Context) {
app := c.MustGet("app").(*bootstrap.App)
sm := app.SessionManager
userID := mustUserID(c)
msgs, err := h.Svc.ListArchived(userID)
// pagination
page := 1
if ps := c.Query("page"); ps != "" {
if n, err := strconv.Atoi(ps); err == nil && n > 0 {
page = n
}
}
pageSize := 20
totalPages, totalCount, err := templateHelpers.GetTotalPages(
c.Request.Context(),
app.DB,
"user_messages",
"recipientId = ? AND is_archived = TRUE",
[]any{userID},
pageSize,
)
if err != nil {
logging.Info("❌ count archived error: %v", err)
c.String(http.StatusInternalServerError, "Failed to load archived messages")
return
}
if page > totalPages {
page = totalPages
}
msgsAll, err := h.Svc.ListArchived(userID)
if err != nil {
logging.Info("❌ list archived error: %v", err)
c.String(http.StatusInternalServerError, "Failed to load archived messages")
return
}
// slice in-memory for now
start := (page - 1) * pageSize
if start > len(msgsAll) {
start = len(msgsAll)
}
end := start + pageSize
if end > len(msgsAll) {
end = len(msgsAll)
}
msgs := msgsAll[start:end]
data := templateHandlers.BuildTemplateData(app, c.Writer, c.Request)
ctx := templateHelpers.TemplateContext(c.Writer, c.Request, data)
if f := sm.PopString(c.Request.Context(), "flash"); f != "" {
ctx["Flash"] = f
}
ctx["CSRFToken"] = nosurf.Token(c.Request)
ctx["Title"] = "Archived Messages"
ctx["Messages"] = msgs
ctx["CurrentPage"] = page
ctx["TotalPages"] = totalPages
ctx["TotalCount"] = totalCount
ctx["PageRange"] = templateHelpers.MakePageRange(1, totalPages)
tmpl := templateHelpers.LoadTemplateFiles("layout.html", "web/templates/account/messages/archived.html")
c.Status(http.StatusOK)
if err := tmpl.ExecuteTemplate(c.Writer, "layout", ctx); err != nil {
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "layout", ctx); err != nil {
logging.Info("❌ Template render error: %v", err)
c.String(http.StatusInternalServerError, "Error rendering archived messages")
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
}
// POST /account/messages/archive
func (h *AccountMessageHandlers) ArchivePost(c *gin.Context) {
app := c.MustGet("app").(*bootstrap.App)
sm := app.SessionManager
userID := mustUserID(c)
idStr := c.PostForm("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
errors.RenderStatus(c, sm, http.StatusBadRequest)
return
}
if err := h.Svc.Archive(userID, id); err != nil {
logging.Info("❌ Archive error: %v", err)
sm.Put(c.Request.Context(), "flash", "Could not archive message.")
c.Redirect(http.StatusSeeOther, "/account/messages")
return
}
sm.Put(c.Request.Context(), "flash", "Message archived.")
c.Redirect(http.StatusSeeOther, "/account/messages")
}
// POST /account/messages/restore
func (h *AccountMessageHandlers) RestorePost(c *gin.Context) {
app := c.MustGet("app").(*bootstrap.App)
sm := app.SessionManager
//userID := mustUserID(c)
idStr := c.PostForm("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
errors.RenderStatus(c, sm, http.StatusBadRequest)
return
}
//
// if err := h.Svc.Unarchive(userID, id); err != nil {
// logging.Info("❌ Restore error: %v", err)
// sm.Put(c.Request.Context(), "flash", "Could not restore message.")
// } else {
// sm.Put(c.Request.Context(), "flash", "Message restored.")
// }
c.Redirect(http.StatusSeeOther, "/account/messages/archived")
}

View File

@@ -2,7 +2,6 @@
// Path: /internal/handlers/account/messages
// File: read.go
// ToDo: Remove SQL
// add LIMIT/OFFSET in service
package accountMessageHandler
@@ -13,8 +12,8 @@ import (
templateHandlers "synlotto-website/internal/handlers/template"
templateHelpers "synlotto-website/internal/helpers/template"
errors "synlotto-website/internal/http/error"
"synlotto-website/internal/logging"
"synlotto-website/internal/platform/bootstrap"
@@ -27,31 +26,36 @@ import (
func (h *AccountMessageHandlers) List(c *gin.Context) {
app := c.MustGet("app").(*bootstrap.App)
sm := app.SessionManager
userID := mustUserID(c)
// 1) Parse page param (default 1)
// --- Pagination ---
page := 1
if ps := c.Query("page"); ps != "" {
if n, err := strconv.Atoi(ps); err == nil && n > 0 {
page = n
}
}
pageSize := 20
// 2) Count total for this user (so TotalPages is accurate)
totalPages, totalCount := templateHelpers.GetTotalPages(
totalPages, totalCount, err := templateHelpers.GetTotalPages(
c.Request.Context(),
app.DB,
"user_messages",
"WHERE recipientId = ? AND is_archived = FALSE",
[]interface{}{userID},
"recipientId = ? AND is_archived = FALSE",
[]any{userID},
pageSize,
)
if err != nil {
logging.Info("❌ count inbox error: %v", err)
c.String(http.StatusInternalServerError, "Failed to load messages")
return
}
if page > totalPages {
page = totalPages
}
// 3) Fetch (existing service returns all inbox items)
// --- Data ---
msgsAll, err := h.Svc.ListInbox(userID)
if err != nil {
logging.Info("❌ list inbox error: %v", err)
@@ -59,7 +63,7 @@ func (h *AccountMessageHandlers) List(c *gin.Context) {
return
}
// 4) Slice in-memory for now (until you add LIMIT/OFFSET in service)
// Temporary in-memory slice (until LIMIT/OFFSET is added)
start := (page - 1) * pageSize
if start > len(msgsAll) {
start = len(msgsAll)
@@ -70,7 +74,7 @@ func (h *AccountMessageHandlers) List(c *gin.Context) {
}
msgs := msgsAll[start:end]
// 5) Build context with paging + CSRF + session-driven user meta
// --- Template context ---
data := templateHandlers.BuildTemplateData(app, c.Writer, c.Request)
ctx := templateHelpers.TemplateContext(c.Writer, c.Request, data)
@@ -85,7 +89,7 @@ func (h *AccountMessageHandlers) List(c *gin.Context) {
ctx["TotalCount"] = totalCount
ctx["PageRange"] = templateHelpers.MakePageRange(1, totalPages)
// 6) Render (Buffer to avoid “headers already written” on error
// --- Render ---
tmpl := templateHelpers.LoadTemplateFiles("layout.html", "web/templates/account/messages/index.html")
var buf bytes.Buffer
@@ -97,6 +101,7 @@ func (h *AccountMessageHandlers) List(c *gin.Context) {
c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
}
// GET /account/messages/read?id=123
// Renders: web/templates/account/messages/read.html
func (h *AccountMessageHandlers) ReadGet(c *gin.Context) {
app := c.MustGet("app").(*bootstrap.App)

View File

@@ -9,9 +9,8 @@ import (
"sort"
"strconv"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/helpers"
templateHelpers "synlotto-website/internal/helpers/template"
"synlotto-website/internal/http/middleware"
"synlotto-website/internal/models"
)
@@ -20,7 +19,6 @@ func ResultsThunderball(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
limiter := middleware.GetVisitorLimiter(ip)
if !limiter.Allow() {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
return
@@ -46,7 +44,7 @@ func ResultsThunderball(db *sql.DB) http.HandlerFunc {
doSearch := isValidDate(query) || isValidNumber(query)
whereClause := "WHERE 1=1"
args := []interface{}{}
args := []any{}
if doSearch {
whereClause += " AND (draw_date = ? OR id = ?)"
@@ -65,7 +63,21 @@ func ResultsThunderball(db *sql.DB) http.HandlerFunc {
args = append(args, ballSetFilter)
}
totalPages, totalResults := templateHelpers.GetTotalPages(db, "results_thunderball", whereClause, args, pageSize)
// ✅ FIX: Proper GetTotalPages call with context + correct table name
totalPages, totalResults, err := templateHelpers.GetTotalPages(
r.Context(),
db,
"results_thunderball",
whereClause,
args,
pageSize,
)
if err != nil {
log.Println("❌ Pagination count error:", err)
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
if page < 1 || page > totalPages {
http.NotFound(w, r)
return
@@ -79,7 +91,7 @@ func ResultsThunderball(db *sql.DB) http.HandlerFunc {
LIMIT ? OFFSET ?`
argsWithLimit := append(args, pageSize, offset)
rows, err := db.Query(querySQL, argsWithLimit...)
rows, err := db.QueryContext(r.Context(), querySQL, argsWithLimit...)
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
log.Println("❌ DB error:", err)
@@ -113,7 +125,7 @@ func ResultsThunderball(db *sql.DB) http.HandlerFunc {
noResultsMsg = "No results found for \"" + query + "\""
}
tmpl := templateHelpers.LoadTemplateFiles("thunderball.html", "web/templates/results/thunderball.html")
tmpl := templateHelpers.LoadTemplateFiles("layout.html", "web/templates/results/thunderball.html")
err = tmpl.ExecuteTemplate(w, "layout", map[string]interface{}{
"Results": results,