Files
Crussell/backend/handlers/notifications/notifications.go
T
popertots 44cac94f64 Fix test setup and middleware chain - Handler tests now passing
- Fix TestRequireRoleMiddleware by chaining RequireAuth before RequireRole (role context requirement)
- Remove unused 'strings' import from testdb.go
- Create crussell_test database in Docker setup
- Tests now properly initialize authentication context for role-based tests

Result: handlers test suite passes (13/13 tests)
Remaining failures in admin/auth/bookings/portfolio/scheduling/services/user packages need further investigation (environment setup, database constraints, endpoint initialization)
2026-02-21 23:50:17 +00:00

202 lines
5.0 KiB
Go

package notifications
import (
"context"
"crussell/db"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Structs returned in JSON
type AdminNotification struct {
ID int `json:"id"`
Reason string `json:"reason"`
BookingID *int `json:"booking_id,omitempty"`
UserID *int `json:"user_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type AdminNotificationListResponse struct {
Notifications []AdminNotification `json:"notifications"`
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
}
// GET /api/admin/notifications
func GetNotifications(w http.ResponseWriter, r *http.Request) {
// Parse query params
page := 1
perPage := 20
if p, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && p > 0 {
page = p
}
if pp, err := strconv.Atoi(r.URL.Query().Get("per_page")); err == nil && pp > 0 {
perPage = pp
}
reasonFilter := r.URL.Query().Get("reason")
baseQuery := `
SELECT id, reason, booking_id, user_id, created_at
FROM admin_notifications
WHERE acknowledged_at IS NULL
`
countQuery := `
SELECT COUNT(*) FROM admin_notifications
WHERE acknowledged_at IS NULL
`
args := []any{}
countArgs := []any{}
param := 1
// Optional reason filter
if reasonFilter != "" {
baseQuery += fmt.Sprintf(" AND reason = $%d", param)
countQuery += fmt.Sprintf(" AND reason = $%d", param)
args = append(args, reasonFilter)
countArgs = append(countArgs, reasonFilter)
param++
}
// ORDER & pagination
baseQuery += " ORDER BY created_at DESC"
baseQuery += fmt.Sprintf(" LIMIT $%d OFFSET $%d", param, param+1)
args = append(args, perPage, (page-1)*perPage)
// Count
var total int
err := db.DB.QueryRow(r.Context(), countQuery, countArgs...).Scan(&total)
if err != nil {
log.Printf("Failed to count notifications: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Query
rows, err := db.DB.Query(r.Context(), baseQuery, args...)
if err != nil {
log.Printf("Failed to fetch notifications: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
defer rows.Close()
notifications := []AdminNotification{}
for rows.Next() {
var n AdminNotification
var bookingID sql.NullInt32
var userID sql.NullInt32
err := rows.Scan(
&n.ID,
&n.Reason,
&bookingID,
&userID,
&n.CreatedAt,
)
if err != nil {
log.Printf("Failed to scan notification row: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if bookingID.Valid {
id := int(bookingID.Int32)
n.BookingID = &id
}
if userID.Valid {
id := int(userID.Int32)
n.UserID = &id
}
notifications = append(notifications, n)
}
resp := AdminNotificationListResponse{
Notifications: notifications,
Page: page,
PerPage: perPage,
Total: total,
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Printf("Failed to encode response: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
func AcknowledgeNotification(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
if idStr == "" {
http.Error(w, "Notification ID is required", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid notification ID", http.StatusBadRequest)
return
}
query := `
UPDATE admin_notifications
SET acknowledged_at = NOW()
WHERE id = $1 AND acknowledged_at IS NULL
`
cmdTag, err := db.DB.Exec(r.Context(), query, id)
if err != nil {
log.Printf("Failed to acknowledge notification %d: %v", id, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if cmdTag.RowsAffected() == 0 {
http.Error(w, "Notification not found or already acknowledged", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
})
}
func AcknowledgePendingBookingNotification(tx interface{}, ctx context.Context, bookingID string) error {
query := `
UPDATE admin_notifications
SET acknowledged_at = NOW()
WHERE booking_id = $1 AND reason = 'pending_booking' AND acknowledged_at IS NULL
`
// Use type assertion to get the Exec method - pgx.Tx satisfies this interface
execer, ok := tx.(interface {
Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
})
if !ok {
log.Printf("Warning: cannot acknowledge notification - tx does not satisfy Execer interface for booking %s", bookingID)
return nil // Don't fail the main operation if notification ack fails
}
_, err := execer.Exec(ctx, query, bookingID)
if err != nil {
log.Printf("Failed to acknowledge pending booking notification for %s: %v", bookingID, err)
return err
}
return nil
}