This commit is contained in:
2026-03-02 22:17:43 +00:00
parent 2f08b37902
commit a7c8837073
6 changed files with 1568 additions and 14 deletions
+307 -4
View File
@@ -9,12 +9,11 @@ package admin
// - GetCurrentAndNextHandler: GET /api/admin/today/current-next - Get current & next booking // - GetCurrentAndNextHandler: GET /api/admin/today/current-next - Get current & next booking
// - GetTodayAppointmentsHandler: GET /api/admin/today/appointments - Get today's bookings // - GetTodayAppointmentsHandler: GET /api/admin/today/appointments - Get today's bookings
// - GetPendingApprovalsHandler: GET /api/admin/today/pending-approvals - Get pending bookings // - GetPendingApprovalsHandler: GET /api/admin/today/pending-approvals - Get pending bookings
// - GetNotifications: GET /api/admin/notifications - List notifications (WIP - skipped) // - Auto-status transitions: Silent background updates on GET requests
// - AcknowledgeNotification: POST /api/admin/notifications/{id}/ack - Acknowledge (WIP - skipped)
// //
// Authentication: All endpoints require admin role (403 for non-admins). // Authentication: All endpoints require admin role (403 for non-admins).
// WIP: Notification tests are skipped pending handler implementation.package admin //
// Note: Notification tests are in handlers/notifications/notifications_test.go
import ( import (
"context" "context"
"encoding/json" "encoding/json"
@@ -255,6 +254,310 @@ func TestAdminToday_PendingApprovals(t *testing.T) {
} }
} }
// =============================================================================
// Auto-Status Transition Tests
// =============================================================================
// TestAdminToday_AutoTransition_ConfirmedToInProgress verifies that a confirmed booking
// that has started but not yet ended is automatically transitioned to in_progress
// when fetching today's appointments.
//
// The transition happens silently in the background during GET requests, not via cron.
func TestAdminToday_AutoTransition_ConfirmedToInProgress(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service with 30 minute duration
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create CONFIRMED booking that started 15 minutes ago (should be in progress)
// Start time = NOW - 15 minutes, duration = 30 minutes, so still ongoing
var bookingID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW() - INTERVAL '15 minutes', 'confirmed', NOW())
RETURNING id
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
// Call the handler - this should trigger auto-transition
handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
// Verify the booking status was changed to in_progress
var status string
err = db.DB.QueryRow(context.Background(), `
SELECT status FROM bookings WHERE id = $1
`, bookingID).Scan(&status)
if err != nil {
t.Fatalf("failed to query booking status: %v", err)
}
if status != "in_progress" {
t.Errorf("expected status 'in_progress' after auto-transition, got '%s'", status)
}
}
// TestAdminToday_AutoTransition_InProgressToCompleted verifies that an in_progress
// booking that has ended is automatically transitioned to completed when fetching
// today's appointments.
//
// The transition happens silently in the background during GET requests, not via cron.
func TestAdminToday_AutoTransition_InProgressToCompleted(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service with 30 minute duration
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create IN_PROGRESS booking that ended 10 minutes ago
// Start time = NOW - 40 minutes, duration = 30 minutes, so ended 10 mins ago
var bookingID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW() - INTERVAL '40 minutes', 'in_progress', NOW())
RETURNING id
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
// Call the handler - this should trigger auto-transition
handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
// Verify the booking status was changed to completed
var status string
err = db.DB.QueryRow(context.Background(), `
SELECT status FROM bookings WHERE id = $1
`, bookingID).Scan(&status)
if err != nil {
t.Fatalf("failed to query booking status: %v", err)
}
if status != "completed" {
t.Errorf("expected status 'completed' after auto-transition, got '%s'", status)
}
}
// TestAdminToday_NoAutoTransition_BeforeStartTime verifies that a confirmed
// booking that hasn't started yet is NOT transitioned to in_progress.
func TestAdminToday_NoAutoTransition_BeforeStartTime(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create CONFIRMED booking that starts in 1 hour (should NOT transition)
var bookingID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW() + INTERVAL '1 hour', 'confirmed', NOW())
RETURNING id
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
// Call the handler
handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
// Verify the booking status is still 'confirmed' (not changed)
var status string
err = db.DB.QueryRow(context.Background(), `
SELECT status FROM bookings WHERE id = $1
`, bookingID).Scan(&status)
if err != nil {
t.Fatalf("failed to query booking status: %v", err)
}
if status != "confirmed" {
t.Errorf("expected status 'confirmed' (no auto-transition before start), got '%s'", status)
}
}
// TestAdminToday_AutoTransition_CurrentNextHandler verifies that auto-transition
// also works when calling GetCurrentAndNextHandler (not just appointments handler)
func TestAdminToday_AutoTransition_CurrentNextHandler(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create CONFIRMED booking that's currently in progress
var bookingID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW() - INTERVAL '10 minutes', 'confirmed', NOW())
RETURNING id
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
// Call GetCurrentAndNextHandler - should trigger auto-transition
handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
// Verify auto-transition happened
var status string
err = db.DB.QueryRow(context.Background(), `
SELECT status FROM bookings WHERE id = $1
`, bookingID).Scan(&status)
if err != nil {
t.Fatalf("failed to query booking status: %v", err)
}
if status != "in_progress" {
t.Errorf("expected 'in_progress' after current-next handler, got '%s'", status)
}
// Verify the response includes the booking as 'current'
var response today.CurrentNextResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.Current == nil {
t.Error("expected current booking in response")
} else if response.Current.ID != bookingID {
t.Errorf("expected current booking ID %s, got %s", bookingID, response.Current.ID)
}
}
// TestAdminNotifications_List is skipped (WIP) - tests that an admin // TestAdminNotifications_List is skipped (WIP) - tests that an admin
// can list all their notifications. // can list all their notifications.
func TestAdminNotifications_List(t *testing.T) { func TestAdminNotifications_List(t *testing.T) {
+99
View File
@@ -26,6 +26,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"time" "time"
@@ -910,5 +911,103 @@ func TestVerifyCheck_RoleChangeToVerified(t *testing.T) {
} }
} }
// =============================================================================
// Password Length Tests (Registration)
// =============================================================================
// TestRegister_PasswordLength_NoMinimum verifies that registration accepts passwords
// of any length (no minimum). The business decision is to not enforce a minimum.
// bcrypt handles passwords up to 72 chars internally (truncates longer ones).
func TestRegister_PasswordLength_NoMinimum(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
handler := http.HandlerFunc(RegisterHandler)
tests := []struct {
name string
password string
expectError bool
}{
{
name: "1_char_password",
password: "x",
expectError: false, // No minimum enforced
},
{
name: "5_char_password",
password: "short",
expectError: false, // No minimum enforced
},
{
name: "72_char_password_exact_bcrypt_limit",
password: strings.Repeat("a", 72),
expectError: false,
},
{
name: "73_char_password_exceeds_limit",
password: strings.Repeat("a", 73),
expectError: true, // Exceeds bcrypt limit
},
{
name: "100_char_password_exceeds_limit",
password: strings.Repeat("a", 100),
expectError: true, // Exceeds bcrypt limit
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := RegisterRequest{
FirstName: "Test",
LastName: "User",
Email: fmt.Sprintf("test-%s@test.com", tt.name),
Password: tt.password,
Phone: "07123456789",
DateOfBirth: "1990-01-15",
AgreedToPolicy: true,
}
w := makeRequest(handler, "POST", "/api/register", body)
if tt.expectError {
if w.Code == http.StatusCreated {
t.Errorf("expected non-201 status for password '%s', got 201", tt.password)
}
} else {
if w.Code != http.StatusCreated {
t.Errorf("expected status 201 for password len=%d, got %d. body: %s", len(tt.password), w.Code, w.Body.String())
}
}
})
}
}
// TestRegister_EmptyPassword verifies that an empty password is rejected
// because it's a required field (not because of minimum length).
func TestRegister_EmptyPassword(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
handler := http.HandlerFunc(RegisterHandler)
body := RegisterRequest{
FirstName: "Test",
LastName: "User",
Email: "empty@test.com",
Password: "", // Empty - should fail as required field
Phone: "07123456789",
DateOfBirth: "1990-01-15",
AgreedToPolicy: true,
}
w := makeRequest(handler, "POST", "/api/register", body)
// Empty password fails because it's a required field
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for empty password, got %d", w.Code)
}
}
// Ensure test compilation - import pgxpool to avoid unused import // Ensure test compilation - import pgxpool to avoid unused import
var _ = func() *pgxpool.Pool { return nil } var _ = func() *pgxpool.Pool { return nil }
+6 -1
View File
@@ -92,11 +92,16 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
req.DateOfBirth = strings.TrimSpace(req.DateOfBirth) req.DateOfBirth = strings.TrimSpace(req.DateOfBirth)
// Check required fields // Check required fields
if req.FirstName == "" || req.LastName == "" || req.Email == "" || req.Phone == "" || req.DateOfBirth == "" { if req.FirstName == "" || req.LastName == "" || req.Email == "" || req.Phone == "" || req.DateOfBirth == "" || req.Password == "" {
http.Error(w, "all fields are required", http.StatusBadRequest) http.Error(w, "all fields are required", http.StatusBadRequest)
return return
} }
// Password must not exceed bcrypt's 72-byte limit
if len(req.Password) > 72 {
http.Error(w, "password must be 72 characters or less", http.StatusBadRequest)
return
}
// Validate name (unicode letters, spaces, hyphen, apostrophe, dot) // Validate name (unicode letters, spaces, hyphen, apostrophe, dot)
nameRegex := regexp.MustCompile(`^[\p{L}\p{M}\s\-'\.]+$`) nameRegex := regexp.MustCompile(`^[\p{L}\p{M}\s\-'\.]+$`)
+549
View File
@@ -2254,3 +2254,552 @@ func TestBookings_RequestEdit_AlreadyHasPending(t *testing.T) {
t.Errorf("expected notes 'Please change to a different day', got '%s'", notes) t.Errorf("expected notes 'Please change to a different day', got '%s'", notes)
} }
} }
// =============================================================================
// Patch Test Validation Tests
// =============================================================================
// TestBookings_Create_PatchTestRequired_NoRecord verifies that a user without a patch test record
// cannot book a service that requires a patch test. The booking should be rejected with 400.
func TestBookings_Create_PatchTestRequired_NoRecord(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
// Create user and service with patch test requirement
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
// Set deposits_required=0 to avoid 48h requirement
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, patchTestID, err := fixtures.CreateTestServiceWithPatchTest(db.DB)
if err != nil {
t.Fatalf("failed to create test service with patch test: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
_ = patchTestID // We don't delete patch tests, they cascade with service
token := jwt.GenerateUserToken(userID)
// Try to book service requiring patch test - user has no patch test record
futureTime := time.Now().Add(72 * time.Hour).Truncate(time.Second)
futureTime = time.Date(futureTime.Year(), futureTime.Month(), futureTime.Day(), 10, 0, 0, 0, futureTime.Location())
req := CreateBookingRequest{
StartTime: futureTime,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for missing patch test, got %d. body: %s", w.Code, w.Body.String())
}
if !bytes.Contains(w.Body.Bytes(), []byte("patch test")) {
t.Errorf("expected error message about patch test, got: %s", w.Body.String())
}
}
// TestBookings_Create_PatchTestRequired_WithinNoticePeriod verifies that a user
// cannot book within the notice period after completing a patch test (e.g., 24h wait).
func TestBookings_Create_PatchTestRequired_WithinNoticePeriod(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, patchTestID, err := fixtures.CreateTestServiceWithPatchTest(db.DB)
if err != nil {
t.Fatalf("failed to create test service with patch test: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
// Create patch test record with tested_at only 1 hour ago (notice is 24h)
testedAt := time.Now().Add(-1 * time.Hour).Format("2006-01-02 15:04:05")
err = fixtures.CreateUserPatchTest(db.DB, userID, patchTestID, testedAt)
if err != nil {
t.Fatalf("failed to create user patch test: %v", err)
}
token := jwt.GenerateUserToken(userID)
// Try to book within notice period (24h required, but only 1h passed)
futureTime := time.Now().Add(12 * time.Hour).Truncate(time.Second)
futureTime = time.Date(futureTime.Year(), futureTime.Month(), futureTime.Day(), 10, 0, 0, 0, futureTime.Location())
req := CreateBookingRequest{
StartTime: futureTime,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for within notice period, got %d. body: %s", w.Code, w.Body.String())
}
if !bytes.Contains(w.Body.Bytes(), []byte("wait")) {
t.Errorf("expected error message about waiting, got: %s", w.Body.String())
}
}
// TestBookings_Create_PatchTestRequired_Expired verifies that a user
// with an expired patch test cannot book services requiring patch test.
func TestBookings_Create_PatchTestRequired_Expired(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, patchTestID, err := fixtures.CreateTestServiceWithPatchTest(db.DB)
if err != nil {
t.Fatalf("failed to create test service with patch test: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
// Create patch test record from 7 months ago (expiry is 6 months)
testedAt := time.Now().AddDate(0, -7, 0).Format("2006-01-02 15:04:05")
err = fixtures.CreateUserPatchTest(db.DB, userID, patchTestID, testedAt)
if err != nil {
t.Fatalf("failed to create user patch test: %v", err)
}
token := jwt.GenerateUserToken(userID)
// Try to book with expired patch test
futureTime := time.Now().Add(72 * time.Hour).Truncate(time.Second)
futureTime = time.Date(futureTime.Year(), futureTime.Month(), futureTime.Day(), 10, 0, 0, 0, futureTime.Location())
req := CreateBookingRequest{
StartTime: futureTime,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for expired patch test, got %d. body: %s", w.Code, w.Body.String())
}
if !bytes.Contains(w.Body.Bytes(), []byte("expired")) {
t.Errorf("expected error message about expiry, got: %s", w.Body.String())
}
}
// TestBookings_Create_PatchTestRequired_ValidRecord verifies that a user
// with a valid patch test record can successfully book services requiring patch test.
func TestBookings_Create_PatchTestRequired_ValidRecord(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, patchTestID, err := fixtures.CreateTestServiceWithPatchTest(db.DB)
if err != nil {
t.Fatalf("failed to create test service with patch test: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
// Create patch test record from 48 hours ago (notice is 24h, so valid now)
testedAt := time.Now().Add(-48 * time.Hour).Format("2006-01-02 15:04:05")
err = fixtures.CreateUserPatchTest(db.DB, userID, patchTestID, testedAt)
if err != nil {
t.Fatalf("failed to create user patch test: %v", err)
}
token := jwt.GenerateUserToken(userID)
// Book with valid patch test record (after notice period)
futureTime := time.Now().Add(72 * time.Hour).Truncate(time.Second)
futureTime = time.Date(futureTime.Year(), futureTime.Month(), futureTime.Day(), 10, 0, 0, 0, futureTime.Location())
req := CreateBookingRequest{
StartTime: futureTime,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusCreated {
t.Errorf("expected status 201 for valid patch test, got %d. body: %s", w.Code, w.Body.String())
}
// Verify booking was created
var count int
err = db.DB.QueryRow(context.Background(),
"SELECT COUNT(*) FROM bookings WHERE user_id = $1", userID).Scan(&count)
if err != nil {
t.Errorf("failed to query bookings: %v", err)
}
if count != 1 {
t.Errorf("expected 1 booking, got %d", count)
}
}
// =============================================================================
// Deposit Requirement Tests
// =============================================================================
// TestBookings_Create_DepositRequired_Within48Hours verifies that a user with deposits_required > 0
// cannot book within 48 hours notice. They must complete more appointments to remove this restriction.
func TestBookings_Create_DepositRequired_Within48Hours(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
// Set deposits_required=3 to trigger 48h advance booking requirement
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 3 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, err := fixtures.CreateTestService(db.DB)
if err != nil {
t.Fatalf("failed to create test service: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
token := jwt.GenerateUserToken(userID)
// Try to book within 48 hours (should be blocked)
within48h := time.Now().Add(24 * time.Hour).Truncate(time.Second)
within48h = time.Date(within48h.Year(), within48h.Month(), within48h.Day(), 10, 0, 0, 0, within48h.Location())
req := CreateBookingRequest{
StartTime: within48h,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for within 48h booking with deposit requirement, got %d. body: %s", w.Code, w.Body.String())
}
if !bytes.Contains(w.Body.Bytes(), []byte("48 hours")) {
t.Errorf("expected error message about 48 hours, got: %s", w.Body.String())
}
}
// TestBookings_Create_DepositRequired_After48Hours verifies that a user with deposits_required > 0
// CAN book if the start time is at least 48 hours in the future.
func TestBookings_Create_DepositRequired_After48Hours(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
// Set deposits_required=3 to trigger 48h advance booking requirement
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 3 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, err := fixtures.CreateTestService(db.DB)
if err != nil {
t.Fatalf("failed to create test service: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
token := jwt.GenerateUserToken(userID)
// Book more than 48 hours in advance (should succeed)
after48h := time.Now().Add(72 * time.Hour).Truncate(time.Second)
after48h = time.Date(after48h.Year(), after48h.Month(), after48h.Day(), 10, 0, 0, 0, after48h.Location())
req := CreateBookingRequest{
StartTime: after48h,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusCreated {
t.Errorf("expected status 201 for booking after 48h, got %d. body: %s", w.Code, w.Body.String())
}
// Verify booking was created
var count int
err = db.DB.QueryRow(context.Background(),
"SELECT COUNT(*) FROM bookings WHERE user_id = $1", userID).Scan(&count)
if err != nil {
t.Errorf("failed to query bookings: %v", err)
}
if count != 1 {
t.Errorf("expected 1 booking, got %d", count)
}
}
// TestBookings_Create_NoDepositRequired_Within48Hours verifies that a user with deposits_required=0
// can book at any time (no 48h restriction).
func TestBookings_Create_NoDepositRequired_Within48Hours(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
// deposits_required=0 means no 48h restriction
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, err := fixtures.CreateTestService(db.DB)
if err != nil {
t.Fatalf("failed to create test service: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
token := jwt.GenerateUserToken(userID)
// Book within 48 hours (should succeed since no deposit required)
within48h := time.Now().Add(24 * time.Hour).Truncate(time.Second)
within48h = time.Date(within48h.Year(), within48h.Month(), within48h.Day(), 10, 0, 0, 0, within48h.Location())
req := CreateBookingRequest{
StartTime: within48h,
ServiceIDs: []string{serviceID},
}
handler := http.HandlerFunc(CreateBookingHandler)
w := makeRequest(handler, "POST", "/api/bookings", req, token)
if w.Code != http.StatusCreated {
t.Errorf("expected status 201 for booking within 48h with no deposit required, got %d. body: %s", w.Code, w.Body.String())
}
}
// =============================================================================
// Holiday/Closed Day Booking Tests
// =============================================================================
// TestBookings_Edit_ClosedDay_UserBlocked verifies that a regular user cannot edit a booking
// to fall on a closed day (exceptional hours marked as is_open=false).
func TestBookings_Edit_ClosedDay_UserBlocked(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, err := fixtures.CreateTestService(db.DB)
if err != nil {
t.Fatalf("failed to create test service: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
bookingID, err := fixtures.CreateTestBooking(db.DB, userID, serviceID)
if err != nil {
t.Fatalf("failed to create test booking: %v", err)
}
defer fixtures.DeleteBooking(db.DB, bookingID)
// Create exceptional hours group for holiday
var groupID string
err = db.DB.QueryRow(context.Background(),
"INSERT INTO exceptional_working_hours_groups (name, description) VALUES ($1, $2) RETURNING id",
"Holiday Closure", "Closed for holiday").Scan(&groupID)
if err != nil {
t.Fatalf("failed to create exceptional hours group: %v", err)
}
// Calculate week start for the booking target date
targetDate := time.Now().Add(96 * time.Hour)
weekday := int(targetDate.Weekday())
daysToMonday := weekday
if daysToMonday == 0 {
daysToMonday = 7
}
weekStart := targetDate.AddDate(0, 0, -daysToMonday+1).Truncate(24 * time.Hour)
// Apply group to this week
_, err = db.DB.Exec(context.Background(),
"INSERT INTO exceptional_group_applications (group_id, week_start) VALUES ($1, $2)",
groupID, weekStart)
if err != nil {
t.Fatalf("failed to apply exceptional hours group: %v", err)
}
// Create closed exceptional hours for that weekday
_, err = db.DB.Exec(context.Background(),
`INSERT INTO exceptional_working_hours (group_id, weekday, start_time, end_time, is_open)
VALUES ($1, $2, '08:00:00', '20:00:00', false)`,
groupID, weekday)
if err != nil {
t.Fatalf("failed to create closed exceptional hours: %v", err)
}
token := jwt.GenerateUserToken(userID)
// Try to edit booking to closed day
newStartTime := targetDate.Truncate(time.Second)
newStartTime = time.Date(newStartTime.Year(), newStartTime.Month(), newStartTime.Day(), 10, 0, 0, 0, newStartTime.Location())
req := EditBookingRequest{
StartTime: newStartTime,
}
handler := http.HandlerFunc(EditBookingHandler)
w := makeRequest(handler, "PUT", "/api/bookings/"+bookingID, req, token)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for closed day edit, got %d. body: %s", w.Code, w.Body.String())
}
if !bytes.Contains(w.Body.Bytes(), []byte("closed day")) {
t.Errorf("expected error message about closed day, got: %s", w.Body.String())
}
}
// TestBookings_Edit_OpenDay_UserAllowed verifies that a user CAN edit a booking
// to a day that is marked as open in exceptional hours.
func TestBookings_Edit_OpenDay_UserAllowed(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
seedDefaultWorkingHours(t)
userID, err := fixtures.CreateTestUser(db.DB)
if err != nil {
t.Fatalf("failed to create test user: %v", err)
}
defer fixtures.DeleteUser(db.DB, userID)
_, err = db.DB.Exec(context.Background(), "UPDATE users SET deposits_required = 0 WHERE id = $1", userID)
if err != nil {
t.Fatalf("failed to set deposits_required: %v", err)
}
serviceID, err := fixtures.CreateTestService(db.DB)
if err != nil {
t.Fatalf("failed to create test service: %v", err)
}
defer fixtures.DeleteService(db.DB, serviceID)
bookingID, err := fixtures.CreateTestBooking(db.DB, userID, serviceID)
if err != nil {
t.Fatalf("failed to create test booking: %v", err)
}
defer fixtures.DeleteBooking(db.DB, bookingID)
// Create exceptional hours group with OPEN hours (is_open=true)
var groupID string
err = db.DB.QueryRow(context.Background(),
"INSERT INTO exceptional_working_hours_groups (name, description) VALUES ($1, $2) RETURNING id",
"Special Opening", "Extended hours").Scan(&groupID)
if err != nil {
t.Fatalf("failed to create exceptional hours group: %v", err)
}
// Calculate week start for the booking target date
targetDate := time.Now().Add(96 * time.Hour)
weekday := int(targetDate.Weekday())
daysToMonday := weekday
if daysToMonday == 0 {
daysToMonday = 7
}
weekStart := targetDate.AddDate(0, 0, -daysToMonday+1).Truncate(24 * time.Hour)
// Apply group to this week
_, err = db.DB.Exec(context.Background(),
"INSERT INTO exceptional_group_applications (group_id, week_start) VALUES ($1, $2)",
groupID, weekStart)
if err != nil {
t.Fatalf("failed to apply exceptional hours group: %v", err)
}
// Create OPEN exceptional hours for that weekday
_, err = db.DB.Exec(context.Background(),
`INSERT INTO exceptional_working_hours (group_id, weekday, start_time, end_time, is_open)
VALUES ($1, $2, '08:00:00', '20:00:00', true)`,
groupID, weekday)
if err != nil {
t.Fatalf("failed to create open exceptional hours: %v", err)
}
token := jwt.GenerateUserToken(userID)
// Edit booking to open day (should succeed)
newStartTime := targetDate.Truncate(time.Second)
newStartTime = time.Date(newStartTime.Year(), newStartTime.Month(), newStartTime.Day(), 10, 0, 0, 0, newStartTime.Location())
req := EditBookingRequest{
StartTime: newStartTime,
}
handler := http.HandlerFunc(EditBookingHandler)
w := makeRequest(handler, "PUT", "/api/bookings/"+bookingID, req, token)
if w.Code != http.StatusOK {
t.Errorf("expected status 200 for open day edit, got %d. body: %s", w.Code, w.Body.String())
}
}
@@ -19,8 +19,8 @@ import (
type AdminNotification struct { type AdminNotification struct {
ID int `json:"id"` ID int `json:"id"`
Reason string `json:"reason"` Reason string `json:"reason"`
BookingID *int `json:"booking_id,omitempty"` BookingID *string `json:"booking_id,omitempty"`
UserID *int `json:"user_id,omitempty"` UserID *string `json:"user_id,omitempty"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
@@ -95,9 +95,9 @@ func GetNotifications(w http.ResponseWriter, r *http.Request) {
notifications := []AdminNotification{} notifications := []AdminNotification{}
for rows.Next() { for rows.Next() {
var n AdminNotification var n AdminNotification
var bookingID sql.NullInt32 var bookingID sql.NullString
var userID sql.NullInt32 var userID sql.NullString
err := rows.Scan( err := rows.Scan(
&n.ID, &n.ID,
@@ -113,12 +113,10 @@ func GetNotifications(w http.ResponseWriter, r *http.Request) {
} }
if bookingID.Valid { if bookingID.Valid {
id := int(bookingID.Int32) n.BookingID = &bookingID.String
n.BookingID = &id
} }
if userID.Valid { if userID.Valid {
id := int(userID.Int32) n.UserID = &userID.String
n.UserID = &id
} }
notifications = append(notifications, n) notifications = append(notifications, n)
@@ -0,0 +1,600 @@
//go:build test
// +build test
package notifications
// Package notifications contains tests for admin notification endpoints.
//
// Test Coverage:
// - GetNotifications: GET /api/admin/notifications - List unacknowledged notifications
// - AcknowledgeNotification: POST /api/admin/notifications/{id}/acknowledge - Acknowledge a notification
//
// Features tested:
// - Pagination (page, per_page)
// - Filtering by reason
// - Acknowledging notifications (idempotent, not found cases)
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"crussell/db"
"crussell/mw"
"crussell/testutils/jwt"
"crussell/testutils/testdb"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// setupTestDB replaces the global db.DB with a test pool and returns a cleanup function
func setupTestDB(t *testing.T) func() {
t.Helper()
pool := testdb.Pool(t)
testdb.Migrate(t, pool)
testdb.TruncateTables(t, pool)
originalDB := db.DB
db.DB = pool
jwt.Init()
return func() {
db.DB = originalDB
pool.Close()
}
}
// makeAdminRequest creates a request with admin context
func makeAdminRequest(handler http.Handler, method, path string, body interface{}) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "admin001", "admin")
}
// makeUserRequest creates a request with regular user context
func makeUserRequest(handler http.Handler, method, path string, body interface{}) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "user001", "verified_email")
}
// makeRequestWithContext creates a request with specific user context
func makeRequestWithContext(handler http.Handler, method, path string, body interface{}, userID, role string) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
bodyBytes, _ := json.Marshal(body)
req = httptest.NewRequest(method, path, bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
} else {
req = httptest.NewRequest(method, path, nil)
}
// Set up chi routing context for path params
rctx := chi.NewRouteContext()
if id, paramName := extractIDFromPath(path); id != "" {
rctx.URLParams.Add(paramName, id)
}
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, mw.UserIDKey, userID)
ctx = context.WithValue(ctx, mw.UserRoleKey, role)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
return w
}
// extractIDFromPath extracts the ID from URL paths
func extractIDFromPath(path string) (string, string) {
prefix := "/api/admin/notifications/"
if len(path) > len(prefix) && path[:len(prefix)] == prefix {
// Extract ID after prefix, up to next / or end
remainder := path[len(prefix):]
for i, c := range remainder {
if c == '/' {
return remainder[:i], "id"
}
}
return remainder, "id"
}
return "", ""
}
// =============================================================================
// GetNotifications Tests
// =============================================================================
// TestNotifications_List tests that an admin can list all unacknowledged notifications
func TestNotifications_List(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user for notification reference
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create a notification
var notificationID int
err = db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
RETURNING id
`, userID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(resp.Notifications) != 1 {
t.Errorf("expected 1 notification, got %d", len(resp.Notifications))
}
if len(resp.Notifications) > 0 {
if resp.Notifications[0].Reason != "pending_booking" {
t.Errorf("expected reason 'pending_booking', got %s", resp.Notifications[0].Reason)
}
if resp.Notifications[0].ID != notificationID {
t.Errorf("expected notification ID %d, got %d", notificationID, resp.Notifications[0].ID)
}
}
}
// TestNotifications_ListEmpty tests that an empty list is returned when no notifications exist
func TestNotifications_ListEmpty(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(resp.Notifications) != 0 {
t.Errorf("expected 0 notifications, got %d", len(resp.Notifications))
}
// Total should be 0
if resp.Total != 0 {
t.Errorf("expected total 0, got %d", resp.Total)
}
}
// TestNotifications_ListFilterByReason tests that notifications can be filtered by reason
func TestNotifications_ListFilterByReason(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create notifications with different reasons
reasons := []string{"pending_booking", "cancelled_booking", "edit_request"}
for _, reason := range reasons {
_, err := db.DB.Exec(context.Background(), `
INSERT INTO admin_notifications (reason, user_id)
VALUES ($1, $2)
`, reason, userID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
}
handler := http.HandlerFunc(GetNotifications)
// Filter by pending_booking
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?reason=pending_booking", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(resp.Notifications) != 1 {
t.Errorf("expected 1 notification with reason=pending_booking, got %d", len(resp.Notifications))
}
if len(resp.Notifications) > 0 && resp.Notifications[0].Reason != "pending_booking" {
t.Errorf("expected reason 'pending_booking', got %s", resp.Notifications[0].Reason)
}
}
// TestNotifications_ListPagination tests that pagination works correctly
func TestNotifications_ListPagination(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create 25 notifications
for i := 0; i < 25; i++ {
_, err := db.DB.Exec(context.Background(), `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
`, userID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
}
handler := http.HandlerFunc(GetNotifications)
// Get first page (default 20 items)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?page=1&per_page=10", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(resp.Notifications) != 10 {
t.Errorf("expected 10 notifications on page 1, got %d", len(resp.Notifications))
}
if resp.Total != 25 {
t.Errorf("expected total 25, got %d", resp.Total)
}
if resp.Page != 1 {
t.Errorf("expected page 1, got %d", resp.Page)
}
if resp.PerPage != 10 {
t.Errorf("expected per_page 10, got %d", resp.PerPage)
}
}
// TestNotifications_ListExcludesAcknowledged tests that acknowledged notifications are not returned
func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create acknowledged notification
_, err = db.DB.Exec(context.Background(), `
INSERT INTO admin_notifications (reason, user_id, acknowledged_at)
VALUES ('pending_booking', $1, NOW())
`, userID)
if err != nil {
t.Fatalf("failed to create acknowledged notification: %v", err)
}
// Create unacknowledged notification
var unackID int
err = db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('cancelled_booking', $1)
RETURNING id
`, userID).Scan(&unackID)
if err != nil {
t.Fatalf("failed to create unacknowledged notification: %v", err)
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
// Should only return the unacknowledged notification
if len(resp.Notifications) != 1 {
t.Errorf("expected 1 unacknowledged notification, got %d", len(resp.Notifications))
}
if len(resp.Notifications) > 0 && resp.Notifications[0].ID != unackID {
t.Errorf("expected unacknowledged notification ID %d, got %d", unackID, resp.Notifications[0].ID)
}
}
// =============================================================================
// AcknowledgeNotification Tests
// =============================================================================
// TestNotifications_Acknowledge tests that an admin can acknowledge a notification
func TestNotifications_Acknowledge(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create notification
var notificationID int
err = db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
RETURNING id
`, userID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%d/acknowledge", notificationID), nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
// Verify the notification is acknowledged
var acknowledgedAt *time.Time
err = db.DB.QueryRow(context.Background(), `
SELECT acknowledged_at FROM admin_notifications WHERE id = $1
`, notificationID).Scan(&acknowledgedAt)
if err != nil {
t.Fatalf("failed to query notification: %v", err)
}
if acknowledgedAt == nil {
t.Error("expected acknowledged_at to be set, got nil")
}
}
// TestNotifications_AcknowledgeNotFound tests that acknowledging a non-existent notification returns 404
func TestNotifications_AcknowledgeNotFound(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", "/api/admin/notifications/99999/acknowledge", nil)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404 for non-existent notification, got %d", w.Code)
}
}
// TestNotifications_AcknowledgeAlreadyAcknowledged tests that acknowledging an already-acknowledged notification returns 404
func TestNotifications_AcknowledgeAlreadyAcknowledged(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create already-acknowledged notification
var notificationID int
err = db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, user_id, acknowledged_at)
VALUES ('pending_booking', $1, NOW())
RETURNING id
`, userID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%d/acknowledge", notificationID), nil)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404 for already acknowledged notification, got %d", w.Code)
}
}
// TestNotifications_AcknowledgeInvalidID tests that invalid notification IDs are handled
func TestNotifications_AcknowledgeInvalidID(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
handler := http.HandlerFunc(AcknowledgeNotification)
tests := []struct {
name string
id string
expectCode int
}{
{"non_numeric_id", "abc", http.StatusBadRequest}, // Invalid format
{"negative_id", "-1", http.StatusNotFound}, // Valid int, not found
{"zero_id", "0", http.StatusNotFound}, // Valid int, not found
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a custom request to test invalid ID handling
req := httptest.NewRequest("POST", "/api/admin/notifications/"+tt.id+"/acknowledge", nil)
// Set up chi routing context with the invalid ID
rctx := chi.NewRouteContext()
rctx.URLParams.Add("id", tt.id)
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, mw.UserIDKey, "admin001")
ctx = context.WithValue(ctx, mw.UserRoleKey, "admin")
req = req.WithContext(ctx)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != tt.expectCode {
t.Errorf("expected status %d for ID '%s', got %d", tt.expectCode, tt.id, w.Code)
}
})
}
}
// TestNotifications_AcknowledgeMissingID tests that missing ID returns 400
func TestNotifications_AcknowledgeMissingID(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create a custom request with no ID in path
req := httptest.NewRequest("POST", "/api/admin/notifications//acknowledge", nil)
// Set up chi routing context without ID
rctx := chi.NewRouteContext()
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, mw.UserIDKey, "admin001")
ctx = context.WithValue(ctx, mw.UserRoleKey, "admin")
req = req.WithContext(ctx)
w := httptest.NewRecorder()
handler := http.HandlerFunc(AcknowledgeNotification)
handler.ServeHTTP(w, req)
// Should return 400 for missing ID
if w.Code != http.StatusBadRequest {
t.Errorf("expected status 400 for missing ID, got %d", w.Code)
}
}
// =============================================================================
// Notification with Booking Reference Tests
// =============================================================================
// TestNotifications_WithBookingReference tests that notifications include booking_id when applicable
func TestNotifications_WithBookingReference(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create a service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Test service', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create a booking
var bookingID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO bookings (user_id, start_time, status)
VALUES ($1, NOW() + INTERVAL '1 day', 'pending')
RETURNING id
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Create notification with booking reference
var notificationID int
err = db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, booking_id, user_id)
VALUES ('pending_booking', $1, $2)
RETURNING id
`, bookingID, userID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(resp.Notifications) != 1 {
t.Fatalf("expected 1 notification, got %d", len(resp.Notifications))
}
// Note: booking_id in DB is stored as bigint, but our struct uses int
// The booking_id should be present
if resp.Notifications[0].BookingID == nil {
t.Error("expected booking_id to be set, got nil")
}
}
// Ensure test compilation - import pgxpool to avoid unused import
var _ = func() *pgxpool.Pool { return nil }