Fix booking count filters, add admin notifications, and improve bookings

UI
This commit is contained in:
2026-01-06 16:45:36 +00:00
parent f536a7fd04
commit 67d812a9be
3 changed files with 847 additions and 0 deletions
+224
View File
@@ -0,0 +1,224 @@
package bookings
import (
"crussell/db"
"crussell/mw"
"database/sql"
"encoding/json"
"log"
"net/http"
"time"
"github.com/go-chi/chi/v5"
)
// UserCancelBookingHandler allows an authenticated user to cancel a booking they own.
// The update is performed in a single statement with appropriate conditions.
func UserCancelBookingHandler(w http.ResponseWriter, r *http.Request) {
bookingID := chi.URLParam(r, "id")
userID, ok := r.Context().Value(mw.UserIDKey).(string)
if !ok || userID == "" {
http.Error(w, "Authentication required", http.StatusUnauthorized)
return
}
res, err := db.DB.Exec(r.Context(), `
UPDATE bookings
SET status = 'client_cancelled', updated_at = $1
WHERE id = $2 AND user_id = $3 AND status IN ('pending', 'confirmed', 'in_progress')
`, time.Now(), bookingID, userID)
if err != nil {
log.Printf("Failed to cancel booking %s: %v", bookingID, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
rowsAffected := res.RowsAffected()
if rowsAffected == 0 {
http.Error(w, "Booking not cancellable", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
// AdminCancelBookingHandler allows an admin to cancel any booking.
// The update uses a status filter and checks RowsAffected for existence.
func AdminCancelBookingHandler(w http.ResponseWriter, r *http.Request) {
bookingID := chi.URLParam(r, "id")
res, err := db.DB.Exec(r.Context(), `
UPDATE bookings
SET status = 'we_cancelled', updated_at = $1
WHERE id = $2 AND status IN ('pending', 'confirmed', 'in_progress')
`, time.Now(), bookingID)
if err != nil {
log.Printf("Failed to admin cancel booking %s: %v", bookingID, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
rowsAffected := res.RowsAffected()
if rowsAffected == 0 {
http.Error(w, "Booking not cancellable", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
// AdminListPendingBookingsHandler returns all bookings with status `pending` by delegating to the existing admin list handler.
func AdminListPendingBookingsHandler(w http.ResponseWriter, r *http.Request) {
r = r.Clone(r.Context())
q := r.URL.Query()
q.Set("status", "pending")
r.URL.RawQuery = q.Encode()
GetAllAdminBookingsHandler(w, r)
}
// AdminGetInProgressBookingHandler returns the booking that is currently in progress.
// It joins the bookings table with users to populate the UserSummary in the returned Booking.
func AdminGetInProgressBookingHandler(w http.ResponseWriter, r *http.Request) {
var b Booking
var userID, fullName string
err := db.DB.QueryRow(r.Context(), `
SELECT
b.id,
b.start_time,
b.status,
b.notes,
b.created_at,
b.updated_at,
b.created_by,
u.id,
u.fn
FROM bookings b
LEFT JOIN users u ON b.user_id = u.id
WHERE b.status = 'in_progress'
ORDER BY b.start_time
LIMIT 1
`).Scan(
&b.ID,
&b.StartTime,
&b.Status,
&b.Notes,
&b.CreatedAt,
&b.UpdatedAt,
&b.CreatedBy,
&userID,
&fullName,
)
if err != nil {
if err == sql.ErrNoRows {
http.Error(w, "No in-progress booking found", http.StatusNotFound)
return
}
log.Printf("Failed to fetch in-progress booking: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Populate the UserSummary field
b.User = &UserSummary{
ID: userID,
FullName: fullName,
FirstName: "", // not available here
LastName: "", // not available here
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(b); err != nil {
log.Printf("Failed to encode booking response: %v", err)
}
}
// AdminEditBookingHandler allows an admin to modify the start time of any booking.
// It validates the new start time and returns 404 if the booking does not exist.
func AdminEditBookingHandler(w http.ResponseWriter, r *http.Request) {
bookingID := chi.URLParam(r, "id")
var req EditBookingRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Basic validation: ensure the new time is not in the past
if time.Now().After(req.StartTime) {
http.Error(w, "Start time must be in the future", http.StatusBadRequest)
return
}
res, err := db.DB.Exec(r.Context(), `
UPDATE bookings
SET start_time = $1, updated_at = $2
WHERE id = $3
`, req.StartTime, time.Now(), bookingID)
if err != nil {
log.Printf("Failed to edit booking %s: %v", bookingID, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
rowsAffected := res.RowsAffected()
if rowsAffected == 0 {
http.Error(w, "Booking not found", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}
// AdminCreateBookingForUserHandler creates a booking on behalf of a user.
func AdminCreateBookingForUserHandler(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "user_id")
var req CreateBookingRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
adminID, _ := r.Context().Value(mw.UserIDKey).(string)
tx, err := db.DB.Begin(r.Context())
if err != nil {
log.Printf("Failed to begin transaction: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
defer tx.Rollback(r.Context())
var bookingID string
err = tx.QueryRow(r.Context(), `
INSERT INTO bookings (id, user_id, start_time, status, created_by)
VALUES (generate_booking_id(), $1, $2, 'pending', $3)
RETURNING id
`, userID, req.StartTime, adminID).Scan(&bookingID)
if err != nil {
log.Printf("Failed to create booking: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
for _, svcID := range req.ServiceIDs {
if _, err := tx.Exec(r.Context(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, svcID); err != nil {
log.Printf("Failed to insert booking service: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
if err = tx.Commit(r.Context()); err != nil {
log.Printf("Failed to commit transaction: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(map[string]string{"id": bookingID}); err != nil {
log.Printf("Failed to encode response: %v", err)
}
}
@@ -0,0 +1,175 @@
package notifications
import (
"crussell/db"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
)
// 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",
})
}
+448
View File
@@ -0,0 +1,448 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { authStore } from '$lib/stores/auth.svelte';
import { browser } from '$app/environment';
// shadcn-svelte components
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Skeleton } from '$lib/components/ui/skeleton';
import { Separator } from '$lib/components/ui/separator';
// =============== Auth & Permissions ===============
let pageState = $state<'loading' | 'authorized' | 'unauthorized'>('loading');
// Check permissions immediately and on auth changes
$effect(() => {
if (!browser) return;
if (authStore.isLoading) {
pageState = 'loading';
return;
}
if (!authStore.isAuthenticated) {
pageState = 'unauthorized';
goto('/login', { replaceState: true });
return;
}
if (authStore.currentUser?.role !== 'admin') {
pageState = 'unauthorized';
goto('/', { replaceState: true });
return;
}
pageState = 'authorized';
});
// =============== Pending Bookings State ===============
type Booking = {
id: string;
start_time: string;
status:
| 'pending'
| 'confirmed'
| 'in_progress'
| 'completed'
| 'client_cancelled'
| 'we_cancelled'
| 're-schedule'
| 'no_show';
notes?: string;
created_at: string;
updated_at: string;
user?: {
id: string;
full_name: string;
email?: string;
phone?: string;
};
services: Array<{
service_name?: string;
price?: number;
duration_minutes?: number;
}>;
total_amount: number;
amount_paid: number;
amount_due: number;
duration_minutes: number;
};
let pendingBookings = $state<Booking[]>([]);
let loadingBookings = $state(true);
// Fetch pending bookings
async function fetchPendingBookings() {
if (pageState !== 'authorized') return;
loadingBookings = true;
try {
const response = await fetch('/api/admin/bookings?status=pending', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
}
});
if (response.ok) {
const data = await response.json();
if (data.bookings && data.bookings.length > 0) {
pendingBookings = data.bookings
.filter((b) => b.status === 'pending')
.map((b) => ({
id: b.id,
start_time: b.start_time,
status: b.status,
notes: b.notes,
created_at: b.created_at,
updated_at: b.updated_at,
user: b.user
? {
id: b.user.id,
full_name: b.user.full_name,
email: b.user.email,
phone: b.user.phone
}
: undefined,
services: b.services || [],
total_amount: b.total_amount || 0,
amount_paid: b.amount_paid || 0,
amount_due: b.amount_due || 0,
duration_minutes: b.duration_minutes || 0
}));
} else {
pendingBookings = [];
}
} else {
console.error('Failed to fetch pending bookings:', response.status);
}
} catch (err) {
console.error('Error fetching pending bookings:', err);
} finally {
loadingBookings = false;
}
}
// Fetch bookings when authorized
$effect(() => {
if (pageState === 'authorized') {
fetchPendingBookings();
}
});
</script>
{#if pageState === 'loading'}
<!-- Full page skeleton loading -->
<div class="mx-auto max-w-6xl space-y-6 p-6">
<!-- Header Skeleton -->
<div class="mb-8 flex items-center justify-center text-center">
<div class="space-y-2">
<Skeleton class="h-8 w-64" />
<Skeleton class="h-4 w-96" />
</div>
</div>
<!-- Card Grid Skeleton -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{#each Array(3) as _, i (i)}
<Card.Root>
<Card.Header>
<Skeleton class="h-6 w-32" />
<Skeleton class="h-4 w-48" />
</Card.Header>
<Card.Content class="space-y-4">
<Skeleton class="h-32 w-full" />
<div class="flex justify-end">
<Skeleton class="h-10 w-24" />
</div>
</Card.Content>
</Card.Root>
{/each}
</div>
<!-- Table Skeleton -->
<Card.Root>
<Card.Header>
<Skeleton class="h-6 w-32" />
<Skeleton class="h-4 w-64" />
</Card.Header>
<Card.Content class="space-y-4">
<div class="flex justify-between">
<Skeleton class="h-10 w-32" />
<Skeleton class="h-10 w-24" />
</div>
<div class="hidden w-full overflow-x-auto md:block">
<table class="w-full table-auto border-collapse text-sm">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
{#each Array(4) as _, i (i)}
<th class="py-3"><Skeleton class="h-4 w-20" /></th>
{/each}
</tr>
</thead>
<tbody>
{#each Array(5) as _, i (i)}
<tr class="border-b">
{#each Array(4) as _, j (j)}
<td class="py-3"><Skeleton class="h-4 w-24" /></td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
</Card.Content>
</Card.Root>
</div>
{:else if pageState === 'authorized'}
<!-- Main Dashboard Content -->
<div class="mx-auto max-w-6xl space-y-6 p-6">
<!-- Header -->
<div class="mb-8 flex items-center justify-center text-center">
<div>
<h1 class="text-3xl font-bold">Needs Attention</h1>
<p class="text-gray-600">Pending bookings requiring confirmation or action</p>
</div>
</div>
<!-- Stats Cards Example -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
<Card.Root>
<Card.Header>
<div class="flex items-start justify-between">
<div>
<Card.Title class="flex items-center gap-2">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
<line x1="16" y1="2" x2="16" y2="6" />
<line x1="8" y1="2" x2="8" y2="6" />
<line x1="3" y1="10" x2="21" y2="10" />
</svg>
Pending Bookings
</Card.Title>
<Card.Description>Awaiting confirmation</Card.Description>
</div>
<div class="rounded-full bg-amber-100 px-3 py-1">
<span class="text-lg font-bold text-amber-700">
{loadingBookings ? '...' : pendingBookings.length}
</span>
</div>
</div>
</Card.Header>
</Card.Root>
</div>
<!-- Main Content Cards -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<!-- Example Management Card 1 -->
<Card.Root class="h-full">
<Card.Header>
<div class="flex items-start justify-between">
<div>
<Card.Title>Recent Activity</Card.Title>
<Card.Description>Latest actions and updates</Card.Description>
</div>
<Button variant="outline" size="sm">View All</Button>
</div>
</Card.Header>
<Card.Content class="space-y-4">
<div class="space-y-2">
{#each Array(4) as _, i (i)}
<div class="flex items-center justify-between rounded bg-gray-50 p-3">
<div class="flex items-center gap-3">
<div class="h-10 w-10 rounded-full bg-gray-200"></div>
<div>
<div class="font-medium">Activity {i + 1}</div>
<div class="text-xs text-gray-500">2 hours ago</div>
</div>
</div>
<Button variant="ghost" size="sm">View</Button>
</div>
{/each}
</div>
</Card.Content>
</Card.Root>
<!-- Example Management Card 2 -->
<Card.Root class="h-full">
<Card.Header>
<div class="flex items-start justify-between">
<div>
<Card.Title>Quick Actions</Card.Title>
<Card.Description>Common administrative tasks</Card.Description>
</div>
</div>
</Card.Header>
<Card.Content class="space-y-3">
<Button class="w-full justify-start" variant="outline">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
Add New Item
</Button>
<Button class="w-full justify-start" variant="outline">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
Edit Settings
</Button>
<Button class="w-full justify-start" variant="outline">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 15 17 10" />
<line x1="12" y1="15" x2="12" y2="3" />
</svg>
Export Data
</Button>
<Button class="w-full justify-start" variant="outline">
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<circle cx="12" cy="12" r="3" />
<path
d="M12 1v6m0 6v6m5.2-13.2l-4.2 4.2m0 6l4.2 4.2M23 12h-6m-6 0H1m20.2-5.2l-4.2 4.2m0 6l4.2 4.2"
/>
</svg>
View Reports
</Button>
</Card.Content>
</Card.Root>
</div>
<!-- Data Table Example -->
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title>Data Management</Card.Title>
<Card.Description>View and manage your data</Card.Description>
</div>
<Button>
<svg
xmlns="http://www.w3.org/2000/svg"
class="mr-2 h-4 w-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
Add New
</Button>
</div>
</Card.Header>
<Card.Content class="space-y-4">
<!-- Desktop Table -->
<div class="hidden w-full overflow-x-auto md:block">
<table class="w-full table-auto border-collapse text-sm">
<thead>
<tr class="border-b text-left text-xs text-gray-500">
<th class="py-3 font-medium">Name</th>
<th class="py-3 font-medium">Status</th>
<th class="py-3 font-medium">Date</th>
<th class="py-3 text-center font-medium">Actions</th>
</tr>
</thead>
<tbody>
{#each Array(5) as _, i (i)}
<tr class="border-b hover:bg-gray-50">
<td class="py-3 font-medium">Item {i + 1}</td>
<td class="py-3">
<span
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {i %
2 ===
0
? 'bg-emerald-100 text-emerald-800'
: 'bg-amber-100 text-amber-800'}"
>
{i % 2 === 0 ? 'Active' : 'Pending'}
</span>
</td>
<td class="py-3 text-gray-600">2024-01-{String(i + 1).padStart(2, '0')}</td>
<td class="py-3">
<div class="flex justify-center gap-2">
<Button variant="outline" size="sm">Edit</Button>
<Button variant="destructive" size="sm">Delete</Button>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<!-- Mobile Cards -->
<div class="space-y-4 md:hidden">
{#each Array(5) as _, i (i)}
<div class="rounded-lg border p-4 hover:bg-gray-50">
<div class="space-y-3">
<div class="flex items-start justify-between">
<h3 class="font-medium">Item {i + 1}</h3>
<span
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {i %
2 ===
0
? 'bg-emerald-100 text-emerald-800'
: 'bg-amber-100 text-amber-800'}"
>
{i % 2 === 0 ? 'Active' : 'Pending'}
</span>
</div>
<div class="text-sm text-gray-600">
Date: 2024-01-{String(i + 1).padStart(2, '0')}
</div>
<div class="flex gap-2 pt-2">
<Button variant="outline" size="sm" class="flex-1">Edit</Button>
<Button variant="destructive" size="sm" class="flex-1">Delete</Button>
</div>
</div>
</div>
{/each}
</div>
</Card.Content>
</Card.Root>
</div>
{/if}