Compare commits

..

6 Commits

Author SHA1 Message Date
Ivan
a882c8698d feat: update sidebar nav, add open play toggle, mark courts 5-6 as open play
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:55:13 +00:00
Ivan
0753edb275 feat: redesign clients page as CRM with membership tracking
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:55:02 +00:00
Ivan
e87b1a5df4 feat: add Live Courts page with real-time court status
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:54:45 +00:00
Ivan
09518c5335 feat: add court session and live courts API routes
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:54:38 +00:00
Ivan
f521eeb698 feat: add CourtSession model and isOpenPlay field to Court
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:44:54 +00:00
Ivan
08cdad3a4e docs: add Live Courts + CRM Clients design document
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:41:49 +00:00
10 changed files with 1588 additions and 215 deletions

View File

@@ -1,14 +1,33 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { ClientTable } from "@/components/clients/client-table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ClientForm } from "@/components/clients/client-form";
import { ClientDetailDialog } from "@/components/clients/client-detail-dialog";
import { AssignMembershipDialog } from "@/components/memberships/assign-membership-dialog";
import { StatCard, StatCardSkeleton } from "@/components/dashboard/stat-card";
import { StatCardSkeleton } from "@/components/dashboard/stat-card";
import { cn, formatDate } from "@/lib/utils";
import {
Users,
CreditCard,
AlertTriangle,
UserX,
Search,
Eye,
Phone,
Mail,
Calendar,
Plus,
ChevronLeft,
ChevronRight,
X,
} from "lucide-react";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface Client {
id: string;
@@ -44,6 +63,7 @@ interface Client {
totalSpent: number;
balance: number;
};
lastBookingDate?: string | null;
}
interface ClientsResponse {
@@ -65,23 +85,107 @@ interface MembershipPlan {
discountPercent: number | string | null;
}
const membershipFilters = [
{ value: "", label: "All" },
{ value: "with", label: "With membership" },
{ value: "without", label: "Without membership" },
];
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
type MembershipStatus = "active" | "expiring" | "expired" | "none";
function getMembershipStatus(client: Client): MembershipStatus {
const membership = client.memberships?.[0];
if (!membership) return "none";
if (membership.status !== "ACTIVE") {
// Check if it truly expired vs just inactive
const end = new Date(membership.endDate);
if (end < new Date()) return "expired";
return "none";
}
const end = new Date(membership.endDate);
const now = new Date();
if (end < now) return "expired";
const daysUntilExpiry = Math.ceil(
(end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
);
if (daysUntilExpiry <= 30) return "expiring";
return "active";
}
function getStatusBadge(status: MembershipStatus) {
switch (status) {
case "active":
return {
label: "Active",
className: "bg-green-100 text-green-700 border-green-300",
};
case "expiring":
return {
label: "Expiring Soon",
className: "bg-amber-100 text-amber-700 border-amber-300",
};
case "expired":
return {
label: "Expired",
className: "bg-red-100 text-red-700 border-red-300",
};
case "none":
default:
return {
label: "None",
className: "bg-gray-100 text-gray-600 border-gray-200",
};
}
}
function getInitials(firstName: string, lastName: string) {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}
function formatShortDate(dateStr: string): string {
const d = new Date(dateStr);
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
});
}
// ---------------------------------------------------------------------------
// Filter options
// ---------------------------------------------------------------------------
const FILTER_OPTIONS = [
{ value: "all", label: "All" },
{ value: "active", label: "Active Members" },
{ value: "expiring", label: "Expiring Soon" },
{ value: "expired", label: "Expired" },
{ value: "none", label: "No Membership" },
] as const;
type FilterValue = (typeof FILTER_OPTIONS)[number]["value"];
const ITEMS_PER_PAGE = 10;
// ---------------------------------------------------------------------------
// Page Component
// ---------------------------------------------------------------------------
export default function ClientsPage() {
// Clients state
// Data state
const [clients, setClients] = useState<Client[]>([]);
const [loadingClients, setLoadingClients] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [membershipFilter, setMembershipFilter] = useState("");
const [filterValue, setFilterValue] = useState<FilterValue>("all");
const [currentPage, setCurrentPage] = useState(1);
const [totalClients, setTotalClients] = useState(0);
// Stats state
const [allClientsForStats, setAllClientsForStats] = useState<Client[]>([]);
const [loadingStats, setLoadingStats] = useState(true);
// Modal state
const [showCreateForm, setShowCreateForm] = useState(false);
const [editingClient, setEditingClient] = useState<Client | null>(null);
@@ -89,20 +193,36 @@ export default function ClientsPage() {
const [showAssignMembership, setShowAssignMembership] = useState(false);
const [formLoading, setFormLoading] = useState(false);
// Stats state
const [stats, setStats] = useState({
totalClients: 0,
withMembership: 0,
newThisMonth: 0,
});
const [loadingStats, setLoadingStats] = useState(true);
// Membership plans for assignment dialog
const [membershipPlans, setMembershipPlans] = useState<MembershipPlan[]>([]);
const [error, setError] = useState<string | null>(null);
// Fetch clients
// ---------------------------------------------------------------------------
// Derived stats
// ---------------------------------------------------------------------------
const stats = useMemo(() => {
const total = allClientsForStats.length;
let activeMemberships = 0;
let expiringThisMonth = 0;
let noMembership = 0;
for (const c of allClientsForStats) {
const status = getMembershipStatus(c);
if (status === "active") activeMemberships++;
if (status === "expiring") expiringThisMonth++;
if (status === "none") noMembership++;
}
return { total, activeMemberships, expiringThisMonth, noMembership };
}, [allClientsForStats]);
// ---------------------------------------------------------------------------
// Fetchers
// ---------------------------------------------------------------------------
const fetchClients = useCallback(async () => {
setLoadingClients(true);
try {
@@ -112,29 +232,19 @@ export default function ClientsPage() {
params.append("offset", ((currentPage - 1) * ITEMS_PER_PAGE).toString());
const response = await fetch(`/api/clients?${params.toString()}`);
if (!response.ok) throw new Error("Error loading players");
if (!response.ok) throw new Error("Error loading clients");
const data: ClientsResponse = await response.json();
// Filter by membership status client-side for simplicity
let filteredData = data.data;
if (membershipFilter === "with") {
filteredData = data.data.filter(
(c) =>
c.memberships &&
c.memberships.length > 0 &&
c.memberships[0].status === "ACTIVE"
);
} else if (membershipFilter === "without") {
filteredData = data.data.filter(
(c) =>
!c.memberships ||
c.memberships.length === 0 ||
c.memberships[0].status !== "ACTIVE"
// Apply membership filter client-side
let filtered = data.data;
if (filterValue !== "all") {
filtered = data.data.filter(
(c) => getMembershipStatus(c) === filterValue
);
}
setClients(filteredData);
setClients(filtered);
setTotalClients(data.pagination.total);
} catch (err) {
console.error("Error fetching clients:", err);
@@ -142,39 +252,15 @@ export default function ClientsPage() {
} finally {
setLoadingClients(false);
}
}, [searchQuery, currentPage, membershipFilter]);
}, [searchQuery, currentPage, filterValue]);
// Fetch stats
const fetchStats = useCallback(async () => {
setLoadingStats(true);
try {
// Fetch all clients to calculate stats
const response = await fetch("/api/clients?limit=1000");
if (!response.ok) throw new Error("Error loading statistics");
const data: ClientsResponse = await response.json();
const allClients = data.data;
// Calculate stats
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const withMembership = allClients.filter(
(c) =>
c.memberships &&
c.memberships.length > 0 &&
c.memberships[0].status === "ACTIVE"
).length;
const newThisMonth = allClients.filter(
(c) => new Date(c.createdAt) >= startOfMonth
).length;
setStats({
totalClients: data.pagination.total,
withMembership,
newThisMonth,
});
setAllClientsForStats(data.data);
} catch (err) {
console.error("Error fetching stats:", err);
} finally {
@@ -182,23 +268,25 @@ export default function ClientsPage() {
}
}, []);
// Fetch membership plans
const fetchMembershipPlans = useCallback(async () => {
try {
const response = await fetch("/api/membership-plans");
if (!response.ok) throw new Error("Error loading plans");
const data = await response.json();
setMembershipPlans(data.filter((p: MembershipPlan & { isActive?: boolean }) => p.isActive !== false));
setMembershipPlans(
data.filter(
(p: MembershipPlan & { isActive?: boolean }) => p.isActive !== false
)
);
} catch (err) {
console.error("Error fetching membership plans:", err);
}
}, []);
// Fetch client details
const fetchClientDetails = async (clientId: string) => {
try {
const response = await fetch(`/api/clients/${clientId}`);
if (!response.ok) throw new Error("Error loading player details");
if (!response.ok) throw new Error("Error loading client details");
const data = await response.json();
setSelectedClient(data);
} catch (err) {
@@ -207,6 +295,10 @@ export default function ClientsPage() {
}
};
// ---------------------------------------------------------------------------
// Effects
// ---------------------------------------------------------------------------
useEffect(() => {
fetchClients();
fetchStats();
@@ -224,9 +316,12 @@ export default function ClientsPage() {
useEffect(() => {
setCurrentPage(1);
}, [debouncedSearch, membershipFilter]);
}, [debouncedSearch, filterValue]);
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
// Handle create client
const handleCreateClient = async (data: {
firstName: string;
lastName: string;
@@ -241,12 +336,10 @@ export default function ClientsPage() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Error creating player");
throw new Error(errorData.error || "Error creating client");
}
setShowCreateForm(false);
await Promise.all([fetchClients(), fetchStats()]);
} catch (err) {
@@ -256,7 +349,6 @@ export default function ClientsPage() {
}
};
// Handle update client
const handleUpdateClient = async (data: {
firstName: string;
lastName: string;
@@ -265,7 +357,6 @@ export default function ClientsPage() {
avatar?: string;
}) => {
if (!editingClient) return;
setFormLoading(true);
try {
const response = await fetch(`/api/clients/${editingClient.id}`, {
@@ -273,16 +364,12 @@ export default function ClientsPage() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Error updating player");
throw new Error(errorData.error || "Error updating client");
}
setEditingClient(null);
await fetchClients();
// Update selected client if viewing details
if (selectedClient?.id === editingClient.id) {
await fetchClientDetails(editingClient.id);
}
@@ -293,7 +380,6 @@ export default function ClientsPage() {
}
};
// Handle delete client
const handleDeleteClient = async (client: Client) => {
if (
!confirm(
@@ -302,17 +388,14 @@ export default function ClientsPage() {
) {
return;
}
try {
const response = await fetch(`/api/clients/${client.id}`, {
method: "DELETE",
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Error deactivating player");
throw new Error(errorData.error || "Error deactivating client");
}
await Promise.all([fetchClients(), fetchStats()]);
} catch (err) {
console.error("Error deleting client:", err);
@@ -320,7 +403,6 @@ export default function ClientsPage() {
}
};
// Handle assign membership
const handleAssignMembership = async (data: {
clientId: string;
planId: string;
@@ -334,16 +416,12 @@ export default function ClientsPage() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Error assigning membership");
}
setShowAssignMembership(false);
await Promise.all([fetchClients(), fetchStats()]);
// Update selected client if viewing details
if (selectedClient) {
await fetchClientDetails(selectedClient.id);
}
@@ -354,39 +432,112 @@ export default function ClientsPage() {
}
};
// Handle row click to view details
const handleRowClick = (client: Client) => {
fetchClientDetails(client.id);
};
// Calculate pagination
// Pagination
const totalPages = Math.ceil(totalClients / ITEMS_PER_PAGE);
// ---------------------------------------------------------------------------
// Render: Stat Card (inline for CRM style)
// ---------------------------------------------------------------------------
function CRMStatCard({
title,
value,
icon,
iconBg,
iconColor,
}: {
title: string;
value: number;
icon: React.ReactNode;
iconBg: string;
iconColor: string;
}) {
return (
<Card className="hover:shadow-md transition-shadow">
<CardContent className="p-5">
<div className="flex items-center gap-4">
<div
className={cn(
"flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center",
iconBg,
iconColor
)}
>
{icon}
</div>
<div>
<p className="text-sm font-medium text-primary-500">{title}</p>
<p className="text-2xl font-bold text-primary-800">{value}</p>
</div>
</div>
</CardContent>
</Card>
);
}
// ---------------------------------------------------------------------------
// Render: Table skeleton
// ---------------------------------------------------------------------------
function TableSkeleton() {
return (
<>
{[...Array(5)].map((_, i) => (
<tr key={i} className="animate-pulse">
<td className="px-4 py-4">
<div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-full bg-primary-100" />
<div className="h-4 w-28 bg-primary-100 rounded" />
</div>
</td>
<td className="px-4 py-4">
<div className="space-y-1.5">
<div className="h-3 w-28 bg-primary-100 rounded" />
<div className="h-3 w-36 bg-primary-100 rounded" />
</div>
</td>
<td className="px-4 py-4">
<div className="h-4 w-20 bg-primary-100 rounded" />
</td>
<td className="px-4 py-4">
<div className="h-6 w-24 bg-primary-100 rounded-full" />
</td>
<td className="px-4 py-4">
<div className="h-4 w-24 bg-primary-100 rounded" />
</td>
<td className="px-4 py-4">
<div className="h-4 w-16 bg-primary-100 rounded" />
</td>
<td className="px-4 py-4">
<div className="h-8 w-16 bg-primary-100 rounded" />
</td>
</tr>
))}
</>
);
}
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-primary-800">Players</h1>
<h1 className="text-2xl font-bold text-primary-800">Clients</h1>
<p className="mt-1 text-primary-600">
Manage your club's players
Manage your club members and memberships
</p>
</div>
<Button onClick={() => setShowCreateForm(true)}>
<svg
className="w-5 h-5 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
/>
</svg>
New Player
<Plus className="w-5 h-5 mr-2" />
New Client
</Button>
</div>
@@ -394,103 +545,56 @@ export default function ClientsPage() {
{error && (
<div className="rounded-md bg-red-50 border border-red-200 p-4">
<div className="flex items-center">
<svg
className="h-5 w-5 text-red-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
clipRule="evenodd"
/>
</svg>
<AlertTriangle className="h-5 w-5 text-red-400" />
<p className="ml-3 text-sm text-red-700">{error}</p>
<button
onClick={() => setError(null)}
className="ml-auto text-red-500 hover:text-red-700"
>
<svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
<X className="h-5 w-5" />
</button>
</div>
</div>
)}
{/* Stats Cards */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{/* Stats Row */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{loadingStats ? (
<>
<StatCardSkeleton />
<StatCardSkeleton />
<StatCardSkeleton />
<StatCardSkeleton />
</>
) : (
<>
<StatCard
title="Total Players"
value={stats.totalClients}
color="primary"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
/>
</svg>
}
<CRMStatCard
title="Total Clients"
value={stats.total}
icon={<Users className="w-6 h-6" />}
iconBg="bg-primary-100"
iconColor="text-primary-600"
/>
<StatCard
title="With Membership"
value={stats.withMembership}
color="accent"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"
/>
</svg>
}
<CRMStatCard
title="Active Memberships"
value={stats.activeMemberships}
icon={<CreditCard className="w-6 h-6" />}
iconBg="bg-green-100"
iconColor="text-green-600"
/>
<StatCard
title="New This Month"
value={stats.newThisMonth}
color="green"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
/>
</svg>
}
<CRMStatCard
title="Expiring This Month"
value={stats.expiringThisMonth}
icon={<AlertTriangle className="w-6 h-6" />}
iconBg="bg-amber-100"
iconColor="text-amber-600"
/>
<CRMStatCard
title="No Membership"
value={stats.noMembership}
icon={<UserX className="w-6 h-6" />}
iconBg="bg-gray-100"
iconColor="text-gray-500"
/>
</>
)}
@@ -501,46 +605,237 @@ export default function ClientsPage() {
<CardContent className="pt-4">
<div className="flex flex-col sm:flex-row gap-4">
{/* Search */}
<div className="flex-1">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-primary-400" />
<Input
type="text"
placeholder="Search by name, email or phone..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full"
className="pl-9 w-full"
/>
</div>
{/* Membership Filter */}
<div className="flex gap-2 overflow-x-auto pb-2 sm:pb-0">
{membershipFilters.map((filter) => (
<Button
key={filter.value}
variant={membershipFilter === filter.value ? "default" : "outline"}
size="sm"
onClick={() => setMembershipFilter(filter.value)}
className="whitespace-nowrap"
>
{filter.label}
</Button>
{/* Membership Filter Dropdown */}
<select
value={filterValue}
onChange={(e) => setFilterValue(e.target.value as FilterValue)}
className="flex h-10 rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 min-w-[180px]"
>
{FILTER_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</div>
</select>
</div>
</CardContent>
</Card>
{/* Clients Table */}
<Card>
<ClientTable
clients={clients}
onRowClick={handleRowClick}
onEdit={(client) => setEditingClient(client)}
onDelete={handleDeleteClient}
isLoading={loadingClients}
currentPage={currentPage}
totalPages={totalPages}
onPageChange={setCurrentPage}
/>
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-primary-200 bg-primary-50">
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Name
</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Contact
</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Membership
</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Status
</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Expires
</th>
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
Last Visit
</th>
<th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="divide-y divide-primary-100">
{loadingClients ? (
<TableSkeleton />
) : clients.length === 0 ? (
<tr>
<td colSpan={7}>
<div className="flex flex-col items-center justify-center py-16 text-primary-500">
<Users className="w-12 h-12 mb-3 text-primary-300" />
<p className="font-medium">No clients found</p>
<p className="text-sm mt-1">
{searchQuery || filterValue !== "all"
? "Try adjusting your search or filters"
: "Add your first client to get started"}
</p>
</div>
</td>
</tr>
) : (
clients.map((client) => {
const membership = client.memberships?.[0];
const mStatus = getMembershipStatus(client);
const badge = getStatusBadge(mStatus);
// Determine last visit from lastBookingDate or fallback
const lastVisit = client.lastBookingDate || null;
return (
<tr
key={client.id}
className="hover:bg-primary-50 transition-colors cursor-pointer"
onClick={() => handleRowClick(client)}
>
{/* Name */}
<td className="px-4 py-3">
<div className="flex items-center gap-3">
{client.avatar ? (
<img
src={client.avatar}
alt={`${client.firstName} ${client.lastName}`}
className="h-9 w-9 rounded-full object-cover flex-shrink-0"
/>
) : (
<div className="h-9 w-9 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0">
<span className="text-sm font-semibold text-primary-600">
{getInitials(client.firstName, client.lastName)}
</span>
</div>
)}
<span className="font-medium text-primary-800 whitespace-nowrap">
{client.firstName} {client.lastName}
</span>
</div>
</td>
{/* Contact */}
<td className="px-4 py-3">
<div className="space-y-0.5">
{client.phone && (
<div className="flex items-center gap-1.5 text-sm text-primary-600">
<Phone className="w-3.5 h-3.5 text-primary-400" />
{client.phone}
</div>
)}
{client.email && (
<div className="flex items-center gap-1.5 text-sm text-primary-500">
<Mail className="w-3.5 h-3.5 text-primary-400" />
<span className="truncate max-w-[180px]">
{client.email}
</span>
</div>
)}
{!client.phone && !client.email && (
<span className="text-sm text-primary-400">
</span>
)}
</div>
</td>
{/* Membership Plan */}
<td className="px-4 py-3 text-sm text-primary-700">
{membership && membership.status === "ACTIVE"
? membership.plan.name
: membership && mStatus === "expired"
? membership.plan.name
: "None"}
</td>
{/* Status Badge */}
<td className="px-4 py-3">
<span
className={cn(
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border",
badge.className
)}
>
{badge.label}
</span>
</td>
{/* Expires */}
<td className="px-4 py-3 text-sm text-primary-600">
{membership &&
(membership.status === "ACTIVE" ||
mStatus === "expired") ? (
<div className="flex items-center gap-1.5">
<Calendar className="w-3.5 h-3.5 text-primary-400" />
{formatShortDate(membership.endDate)}
</div>
) : (
<span className="text-primary-400"></span>
)}
</td>
{/* Last Visit */}
<td className="px-4 py-3 text-sm text-primary-600">
{lastVisit ? (
formatShortDate(lastVisit)
) : (
<span className="text-primary-400">Never</span>
)}
</td>
{/* Actions */}
<td className="px-4 py-3 text-right">
<div
className="flex items-center justify-end gap-2"
onClick={(e) => e.stopPropagation()}
>
<Button
variant="outline"
size="sm"
onClick={() => handleRowClick(client)}
>
<Eye className="w-4 h-4 mr-1" />
View
</Button>
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between px-4 py-3 border-t border-primary-200 bg-primary-50">
<div className="text-sm text-primary-600">
Page {currentPage} of {totalPages}
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage <= 1}
>
<ChevronLeft className="w-4 h-4 mr-1" />
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(currentPage + 1)}
disabled={currentPage >= totalPages}
>
Next
<ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
</div>
)}
</Card>
{/* Create Client Form Modal */}

View File

@@ -0,0 +1,589 @@
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useSite } from "@/contexts/site-context";
import {
Users,
UserPlus,
Clock,
RefreshCw,
MapPin,
X,
Search,
} from "lucide-react";
// --- Types ---
interface Player {
id: string;
firstName?: string;
lastName?: string;
walkInName?: string;
checkedInAt: string;
sessionId: string;
}
interface Court {
id: string;
name: string;
type: "INDOOR" | "OUTDOOR";
isOpenPlay: boolean;
status: "available" | "active" | "booked" | "open_play";
players: Player[];
upcomingBooking?: {
startTime: string;
clientName: string;
};
}
interface ClientResult {
id: string;
firstName: string;
lastName: string;
}
// --- Helpers ---
function getStatusConfig(court: Court) {
if (court.status === "active") {
return {
dotColor: "bg-primary-500",
text: `Active (${court.players.length} player${court.players.length !== 1 ? "s" : ""})`,
bgColor: "bg-primary-50",
borderColor: "border-primary-200",
textColor: "text-primary-500",
};
}
if (court.status === "open_play" && court.players.length === 0) {
return {
dotColor: "bg-amber-500",
text: "Open Play",
bgColor: "bg-amber-50",
borderColor: "border-amber-200",
textColor: "text-amber-500",
};
}
if (court.status === "open_play" && court.players.length > 0) {
return {
dotColor: "bg-amber-500",
text: `Open Play (${court.players.length} player${court.players.length !== 1 ? "s" : ""})`,
bgColor: "bg-amber-50",
borderColor: "border-amber-200",
textColor: "text-amber-500",
};
}
if (court.status === "booked") {
return {
dotColor: "bg-purple-500",
text: "Booked",
bgColor: "bg-purple-50",
borderColor: "border-purple-200",
textColor: "text-purple-500",
};
}
return {
dotColor: "bg-green-500",
text: "Available",
bgColor: "bg-green-50",
borderColor: "border-green-200",
textColor: "text-green-500",
};
}
function formatTime(dateStr: string) {
return new Date(dateStr).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
}
function playerName(player: Player) {
if (player.walkInName) return player.walkInName;
return [player.firstName, player.lastName].filter(Boolean).join(" ") || "Unknown";
}
function playerInitials(player: Player) {
const name = playerName(player);
const parts = name.split(" ");
if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
return name.slice(0, 2).toUpperCase();
}
// --- Main Page ---
export default function LiveCourtsPage() {
const { selectedSiteId } = useSite();
const [courts, setCourts] = useState<Court[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const [checkInCourtId, setCheckInCourtId] = useState<string | null>(null);
const [endSessionCourtId, setEndSessionCourtId] = useState<string | null>(null);
const intervalRef = useRef<NodeJS.Timeout | null>(null);
// --- Data fetching ---
const fetchCourts = useCallback(async () => {
try {
setError(null);
const url = selectedSiteId
? `/api/live?siteId=${selectedSiteId}`
: "/api/live";
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to load court data");
const data = await response.json();
setCourts(data.courts ?? data.data ?? []);
setLastUpdated(new Date());
} catch (err) {
console.error("Live courts fetch error:", err);
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setIsLoading(false);
}
}, [selectedSiteId]);
useEffect(() => {
fetchCourts();
intervalRef.current = setInterval(fetchCourts, 30000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [fetchCourts]);
// --- End session handler ---
const handleEndSession = async (court: Court) => {
try {
await Promise.all(
court.players.map((p) =>
fetch(`/api/court-sessions/${p.sessionId}`, { method: "PUT" })
)
);
setEndSessionCourtId(null);
fetchCourts();
} catch (err) {
console.error("End session error:", err);
}
};
// --- Render ---
const checkInCourt = courts.find((c) => c.id === checkInCourtId) ?? null;
const endSessionCourt = courts.find((c) => c.id === endSessionCourtId) ?? null;
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-primary-800">Live Courts</h1>
<p className="text-primary-500 mt-1">
{lastUpdated
? `Last updated: ${lastUpdated.toLocaleTimeString()}`
: "Loading..."}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => fetchCourts()}
disabled={isLoading}
>
<RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
Refresh
</Button>
</div>
{/* Error */}
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">
{error}
</div>
)}
{/* Loading skeleton */}
{isLoading && courts.length === 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i}>
<CardHeader className="pb-3">
<div className="animate-pulse space-y-2">
<div className="h-5 bg-primary-100 rounded w-32" />
<div className="h-4 bg-primary-100 rounded w-20" />
</div>
</CardHeader>
<CardContent>
<div className="animate-pulse space-y-3">
<div className="h-4 bg-primary-100 rounded w-full" />
<div className="h-8 bg-primary-100 rounded w-24" />
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Court grid */}
{!isLoading && courts.length === 0 && !error && (
<div className="text-center py-12 text-primary-500">
<MapPin className="w-12 h-12 mx-auto mb-4 opacity-40" />
<p className="text-lg font-medium">No courts found</p>
<p className="text-sm mt-1">Courts will appear here once configured.</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{courts.map((court) => {
const cfg = getStatusConfig(court);
const earliestCheckIn = court.players.length > 0
? court.players.reduce((earliest, p) =>
new Date(p.checkedInAt) < new Date(earliest.checkedInAt) ? p : earliest
)
: null;
return (
<Card key={court.id} className={`${cfg.borderColor} border`}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-semibold">
{court.name}
</CardTitle>
<div className="flex items-center gap-1.5">
<span className="text-xs font-medium px-2 py-0.5 rounded-full bg-primary-100 text-primary-600">
{court.type}
</span>
{court.isOpenPlay && (
<span className="text-xs font-medium px-2 py-0.5 rounded-full bg-amber-100 text-amber-700">
Open Play
</span>
)}
</div>
</div>
{/* Status indicator */}
<div className="flex items-center gap-2 mt-1">
<span className={`inline-block w-2.5 h-2.5 rounded-full ${cfg.dotColor}`} />
<span className={`text-sm font-medium ${cfg.textColor}`}>
{cfg.text}
</span>
</div>
</CardHeader>
<CardContent className="space-y-3">
{/* Upcoming booking info for booked courts */}
{court.status === "booked" && court.upcomingBooking && (
<div className="text-sm text-purple-600 bg-purple-50 rounded-md px-3 py-2">
<Clock className="w-3.5 h-3.5 inline mr-1" />
{court.upcomingBooking.clientName} at{" "}
{formatTime(court.upcomingBooking.startTime)}
</div>
)}
{/* Player list */}
{court.players.length > 0 && (
<div className="space-y-2">
{court.players.map((player) => (
<div
key={player.id}
className="flex items-center gap-2 text-sm"
>
<div className="w-7 h-7 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-xs font-semibold shrink-0">
{playerInitials(player)}
</div>
<span className="text-primary-700 truncate">
{playerName(player)}
</span>
</div>
))}
</div>
)}
{/* Time since first check-in */}
{earliestCheckIn && (
<div className="flex items-center gap-1.5 text-xs text-primary-400">
<Clock className="w-3.5 h-3.5" />
Since {formatTime(earliestCheckIn.checkedInAt)}
</div>
)}
{/* Actions */}
<div className="flex flex-wrap gap-2 pt-1">
{(court.status === "available" ||
court.status === "active" ||
court.status === "open_play") && (
<Button
variant="outline"
size="sm"
onClick={() => setCheckInCourtId(court.id)}
>
<UserPlus className="w-4 h-4 mr-1" />
Check In
</Button>
)}
{(court.status === "active" || (court.status === "open_play" && court.players.length > 0)) && (
<Button
variant="outline"
size="sm"
className="text-red-600 border-red-200 hover:bg-red-50"
onClick={() => setEndSessionCourtId(court.id)}
>
<X className="w-4 h-4 mr-1" />
End Session
</Button>
)}
{court.isOpenPlay && (
<Button variant="outline" size="sm">
<Users className="w-4 h-4 mr-1" />
Schedule Group
</Button>
)}
</div>
</CardContent>
</Card>
);
})}
</div>
{/* Check In Modal */}
{checkInCourt && (
<CheckInModal
court={checkInCourt}
onClose={() => setCheckInCourtId(null)}
onSuccess={() => {
setCheckInCourtId(null);
fetchCourts();
}}
/>
)}
{/* End Session Confirm Dialog */}
{endSessionCourt && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
<div className="bg-white rounded-lg shadow-xl max-w-sm w-full mx-4 p-6 space-y-4">
<h2 className="text-lg font-semibold text-primary-800">
End Session
</h2>
<p className="text-sm text-primary-600">
End session on <strong>{endSessionCourt.name}</strong>? This will
check out all players.
</p>
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setEndSessionCourtId(null)}
>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => handleEndSession(endSessionCourt)}
>
End Session
</Button>
</div>
</div>
</div>
)}
</div>
);
}
// --- Check In Modal Component ---
function CheckInModal({
court,
onClose,
onSuccess,
}: {
court: Court;
onClose: () => void;
onSuccess: () => void;
}) {
const [mode, setMode] = useState<"search" | "walkin">("search");
const [searchQuery, setSearchQuery] = useState("");
const [walkInName, setWalkInName] = useState("");
const [clients, setClients] = useState<ClientResult[]>([]);
const [selectedClient, setSelectedClient] = useState<ClientResult | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
// Debounced client search
useEffect(() => {
if (searchQuery.length < 2) {
setClients([]);
return;
}
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(async () => {
setIsSearching(true);
try {
const res = await fetch(
`/api/clients?search=${encodeURIComponent(searchQuery)}`
);
if (res.ok) {
const data = await res.json();
setClients(data.data ?? data ?? []);
}
} catch {
console.error("Client search failed");
} finally {
setIsSearching(false);
}
}, 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [searchQuery]);
const handleSubmit = async () => {
setIsSubmitting(true);
try {
const body: Record<string, string> = { courtId: court.id };
if (mode === "search" && selectedClient) {
body.clientId = selectedClient.id;
} else if (mode === "walkin" && walkInName.trim()) {
body.walkInName = walkInName.trim();
} else {
return;
}
const res = await fetch("/api/court-sessions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error("Check-in failed");
onSuccess();
} catch (err) {
console.error("Check-in error:", err);
} finally {
setIsSubmitting(false);
}
};
const canSubmit =
(mode === "search" && selectedClient !== null) ||
(mode === "walkin" && walkInName.trim().length > 0);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
<div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 p-6 space-y-4">
{/* Modal header */}
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-primary-800">
Check In &mdash; {court.name}
</h2>
<button
onClick={onClose}
className="text-primary-400 hover:text-primary-600"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Mode toggle */}
<div className="flex rounded-lg border border-primary-200 overflow-hidden">
<button
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
mode === "search"
? "bg-primary-100 text-primary-800"
: "text-primary-500 hover:bg-primary-50"
}`}
onClick={() => setMode("search")}
>
<Search className="w-4 h-4 inline mr-1" />
Find Client
</button>
<button
className={`flex-1 px-4 py-2 text-sm font-medium transition-colors ${
mode === "walkin"
? "bg-primary-100 text-primary-800"
: "text-primary-500 hover:bg-primary-50"
}`}
onClick={() => setMode("walkin")}
>
<UserPlus className="w-4 h-4 inline mr-1" />
Walk-in
</button>
</div>
{/* Search mode */}
{mode === "search" && (
<div className="space-y-3">
<Input
placeholder="Search by name..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setSelectedClient(null);
}}
autoFocus
/>
{isSearching && (
<p className="text-sm text-primary-400">Searching...</p>
)}
{clients.length > 0 && (
<div className="max-h-40 overflow-y-auto border border-primary-200 rounded-md divide-y divide-primary-100">
{clients.map((client) => (
<button
key={client.id}
className={`w-full text-left px-3 py-2 text-sm hover:bg-primary-50 transition-colors ${
selectedClient?.id === client.id
? "bg-primary-100 font-medium"
: ""
}`}
onClick={() => setSelectedClient(client)}
>
{client.firstName} {client.lastName}
</button>
))}
</div>
)}
{searchQuery.length >= 2 &&
!isSearching &&
clients.length === 0 && (
<p className="text-sm text-primary-400">No clients found.</p>
)}
{selectedClient && (
<div className="flex items-center gap-2 text-sm bg-primary-50 rounded-md px-3 py-2">
<span className="font-medium text-primary-700">
Selected: {selectedClient.firstName} {selectedClient.lastName}
</span>
</div>
)}
</div>
)}
{/* Walk-in mode */}
{mode === "walkin" && (
<Input
placeholder="Enter walk-in name..."
value={walkInName}
onChange={(e) => setWalkInName(e.target.value)}
autoFocus
/>
)}
{/* Submit */}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" size="sm" onClick={onClose}>
Cancel
</Button>
<Button
size="sm"
disabled={!canSubmit || isSubmitting}
onClick={handleSubmit}
>
{isSubmitting ? "Checking in..." : "Check In"}
</Button>
</div>
</div>
</div>
);
}

View File

@@ -37,6 +37,7 @@ interface Court {
status: string;
siteId: string;
site?: { name: string };
isOpenPlay?: boolean;
}
interface User {
@@ -479,7 +480,14 @@ export default function SettingsPage() {
<tbody>
{courts.map((court) => (
<tr key={court.id} className="border-b border-primary-50 hover:bg-primary-50/50">
<td className="px-4 py-3 font-medium text-primary-800">{court.name}</td>
<td className="px-4 py-3 font-medium text-primary-800">
{court.name}
{court.isOpenPlay && (
<span className="ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">
Open Play
</span>
)}
</td>
<td className="px-4 py-3 text-primary-600">{court.site?.name || "-"}</td>
<td className="px-4 py-3 text-primary-600 capitalize">{court.type}</td>
<td className="px-4 py-3 text-primary-600">${court.hourlyRate}</td>
@@ -709,6 +717,7 @@ function CourtFormModal({
const [hourlyRate, setHourlyRate] = useState(court?.hourlyRate?.toString() || "300");
const [peakHourlyRate, setPeakHourlyRate] = useState(court?.peakHourlyRate?.toString() || "");
const [status, setStatus] = useState(court?.status || "active");
const [isOpenPlay, setIsOpenPlay] = useState(court?.isOpenPlay ?? false);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
@@ -719,6 +728,7 @@ function CourtFormModal({
hourlyRate: parseFloat(hourlyRate),
peakHourlyRate: peakHourlyRate ? parseFloat(peakHourlyRate) : null,
status,
isOpenPlay,
});
};
@@ -797,6 +807,18 @@ function CourtFormModal({
<option value="inactive">Inactive</option>
</select>
</div>
<div className="flex items-center gap-2">
<input
type="checkbox"
id="isOpenPlay"
checked={isOpenPlay}
onChange={(e) => setIsOpenPlay(e.target.checked)}
className="rounded border-primary-300"
/>
<label htmlFor="isOpenPlay" className="text-sm text-primary-700">
Open Play Court (free, for group scheduling)
</label>
</div>
<div className="flex gap-3 pt-4">
<Button type="button" variant="outline" onClick={onClose} className="flex-1">
Cancel

View File

@@ -0,0 +1,124 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
interface RouteContext {
params: Promise<{ id: string }>;
}
// PUT /api/court-sessions/[id] - End a court session
export async function PUT(
request: NextRequest,
context: RouteContext
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { id } = await context.params;
// Verify session exists and belongs to user's organization
const existingSession = await db.courtSession.findFirst({
where: {
id,
court: {
site: {
organizationId: session.user.organizationId,
},
},
},
});
if (!existingSession) {
return NextResponse.json(
{ error: 'Court session not found' },
{ status: 404 }
);
}
if (!existingSession.isActive) {
return NextResponse.json(
{ error: 'Court session is already ended' },
{ status: 400 }
);
}
// End the session
const updatedSession = await db.courtSession.update({
where: { id },
data: {
isActive: false,
endTime: new Date(),
},
include: {
court: { select: { id: true, name: true, type: true, isOpenPlay: true, siteId: true } },
client: { select: { id: true, firstName: true, lastName: true, phone: true } },
},
});
return NextResponse.json(updatedSession);
} catch (error) {
console.error('Error ending court session:', error);
return NextResponse.json(
{ error: 'Error ending court session' },
{ status: 500 }
);
}
}
// DELETE /api/court-sessions/[id] - Remove a court session entirely
export async function DELETE(
request: NextRequest,
context: RouteContext
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { id } = await context.params;
// Verify session exists and belongs to user's organization
const existingSession = await db.courtSession.findFirst({
where: {
id,
court: {
site: {
organizationId: session.user.organizationId,
},
},
},
});
if (!existingSession) {
return NextResponse.json(
{ error: 'Court session not found' },
{ status: 404 }
);
}
await db.courtSession.delete({
where: { id },
});
return NextResponse.json({ message: 'Court session deleted successfully' });
} catch (error) {
console.error('Error deleting court session:', error);
return NextResponse.json(
{ error: 'Error deleting court session' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,159 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
// GET /api/court-sessions - List all active court sessions
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const courtId = searchParams.get('courtId');
const siteId = searchParams.get('siteId');
// Build where clause
const whereClause: {
isActive: boolean;
courtId?: string;
court?: { siteId?: string; site: { organizationId: string } };
} = {
isActive: true,
court: {
site: {
organizationId: session.user.organizationId,
},
},
};
if (courtId) {
whereClause.courtId = courtId;
}
if (siteId) {
whereClause.court = {
...whereClause.court!,
siteId,
};
} else if (session.user.siteId) {
whereClause.court = {
...whereClause.court!,
siteId: session.user.siteId,
};
}
const sessions = await db.courtSession.findMany({
where: whereClause,
include: {
court: { select: { id: true, name: true, type: true, isOpenPlay: true, siteId: true } },
client: { select: { id: true, firstName: true, lastName: true, phone: true } },
},
orderBy: { startTime: 'desc' },
});
return NextResponse.json(sessions);
} catch (error) {
console.error('Error fetching court sessions:', error);
return NextResponse.json(
{ error: 'Error fetching court sessions' },
{ status: 500 }
);
}
}
// POST /api/court-sessions - Check in a player to a court
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const body = await request.json();
const { courtId, clientId, walkInName, notes } = body;
// Validate required fields
if (!courtId) {
return NextResponse.json(
{ error: 'courtId is required' },
{ status: 400 }
);
}
// Must have either clientId or walkInName
if (!clientId && !walkInName) {
return NextResponse.json(
{ error: 'Either clientId or walkInName is required' },
{ status: 400 }
);
}
// Verify court exists and belongs to user's organization
const court = await db.court.findFirst({
where: {
id: courtId,
site: {
organizationId: session.user.organizationId,
},
},
});
if (!court) {
return NextResponse.json(
{ error: 'Court not found or does not belong to your organization' },
{ status: 404 }
);
}
// If clientId is provided, verify client exists
if (clientId) {
const client = await db.client.findFirst({
where: {
id: clientId,
organizationId: session.user.organizationId,
},
});
if (!client) {
return NextResponse.json(
{ error: 'Client not found or does not belong to your organization' },
{ status: 404 }
);
}
}
// Create the court session
const courtSession = await db.courtSession.create({
data: {
courtId,
clientId: clientId || null,
walkInName: walkInName || null,
notes: notes || null,
isActive: true,
},
include: {
court: { select: { id: true, name: true, type: true, isOpenPlay: true, siteId: true } },
client: { select: { id: true, firstName: true, lastName: true, phone: true } },
},
});
return NextResponse.json(courtSession, { status: 201 });
} catch (error) {
console.error('Error creating court session:', error);
return NextResponse.json(
{ error: 'Error creating court session' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,97 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
// GET /api/live - Get complete live court status
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const siteId = searchParams.get('siteId');
// Build where clause for courts
const courtWhere: {
isActive: boolean;
site: { organizationId: string; id?: string };
} = {
isActive: true,
site: {
organizationId: session.user.organizationId,
},
};
if (siteId) {
courtWhere.site.id = siteId;
} else if (session.user.siteId) {
courtWhere.site.id = session.user.siteId;
}
const now = new Date();
const endOfHour = new Date(now.getTime() + 30 * 60 * 1000); // 30 minutes from now
// Get all courts with their active sessions AND current bookings
const courts = await db.court.findMany({
where: courtWhere,
include: {
sessions: {
where: { isActive: true },
include: {
client: { select: { id: true, firstName: true, lastName: true, phone: true } },
},
},
bookings: {
where: {
startTime: { lte: endOfHour },
endTime: { gte: now },
status: { in: ['CONFIRMED', 'PENDING'] },
},
include: {
client: { select: { id: true, firstName: true, lastName: true } },
},
},
site: { select: { id: true, name: true } },
},
orderBy: { displayOrder: 'asc' },
});
// Compute status for each court
const courtsWithStatus = courts.map((court) => {
let status: 'available' | 'active' | 'open-play' | 'booked';
if (court.sessions.length > 0) {
// Court has active sessions
if (court.isOpenPlay) {
status = 'open-play';
} else {
status = 'active';
}
} else if (court.bookings.length > 0) {
status = 'booked';
} else {
status = 'available';
}
return {
...court,
status,
};
});
return NextResponse.json(courtsWithStatus);
} catch (error) {
console.error('Error fetching live court status:', error);
return NextResponse.json(
{ error: 'Error fetching live court status' },
{ status: 500 }
);
}
}

View File

@@ -4,8 +4,8 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
LayoutDashboard,
Calendar,
Users,
Radio,
UserCircle,
CreditCard,
BarChart3,
Settings,
@@ -20,8 +20,8 @@ interface NavItem {
const navItems: NavItem[] = [
{ label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard },
{ label: 'Bookings', href: '/bookings', icon: Calendar },
{ label: 'Players', href: '/clients', icon: Users },
{ label: 'Live Courts', href: '/live', icon: Radio },
{ label: 'Clients', href: '/clients', icon: UserCircle },
{ label: 'Memberships', href: '/memberships', icon: CreditCard },
{ label: 'Reports', href: '/reports', icon: BarChart3 },
{ label: 'Settings', href: '/settings', icon: Settings },

View File

@@ -144,13 +144,15 @@ model Court {
description String?
features String[] @default([])
displayOrder Int @default(0)
isOpenPlay Boolean @default(false)
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
site Site @relation(fields: [siteId], references: [id], onDelete: Cascade)
site Site @relation(fields: [siteId], references: [id], onDelete: Cascade)
bookings Booking[]
matches Match[]
sessions CourtSession[]
@@index([siteId])
@@index([status])
@@ -215,6 +217,7 @@ model Client {
payments Payment[]
sales Sale[]
inscriptions TournamentInscription[]
courtSessions CourtSession[]
@@unique([organizationId, email])
@@unique([organizationId, dni])
@@ -544,3 +547,28 @@ model Match {
@@index([round, position])
@@index([scheduledAt])
}
// =============================================================================
// COURT SESSIONS (Live Player Tracking)
// =============================================================================
model CourtSession {
id String @id @default(cuid())
courtId String
clientId String?
walkInName String?
startTime DateTime @default(now())
endTime DateTime?
isActive Boolean @default(true)
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
court Court @relation(fields: [courtId], references: [id], onDelete: Cascade)
client Client? @relation(fields: [clientId], references: [id], onDelete: SetNull)
@@index([courtId])
@@index([clientId])
@@index([isActive])
@@index([startTime])
}

View File

@@ -101,6 +101,7 @@ async function main() {
type: CourtType.OUTDOOR,
status: CourtStatus.AVAILABLE,
pricePerHour: 300,
isOpenPlay: i >= 5,
description: 'Outdoor court with night lighting',
features: ['Night lighting', 'Court dividers'],
displayOrder: i,

View File

@@ -0,0 +1,58 @@
# Live Courts + CRM Clients - Design Document
## Overview
Consolidate Bookings + Players into a "Live Courts" real-time status board. Replace the current Players page with a CRM-style Clients page focused on memberships, expirations, and visit history.
## Navigation
Before: Dashboard | Bookings | Players | Memberships | Reports | Settings
After: Dashboard | Live Courts | Clients | Memberships | Reports | Settings
## Live Courts Page (/live)
Real-time dashboard showing all 6 courts. 3x2 grid of court cards.
### Court States
- Available (green) — empty, can check in players
- Active (blue) — players on court, shows player list
- Open Play (amber) — dedicated free courts, group scheduling
- Booked (purple) — upcoming booking in next 30 min
### Actions
- Check In — add player (search existing or walk-in name)
- End Session — clear all players
- Schedule Group (open play only) — name/note + time, no cost
### Auto-populate
Bookings for current time auto-show as active players.
## Open Play Courts
Settings > Courts toggle: "Open Play Court" (boolean).
- Amber badge on Live Courts
- No pricing on bookings
- Group scheduling: name/note + time slot, no client/payment
## Clients CRM Page (/clients)
### Stats Row
Total Clients | Active Memberships | Expiring This Month | No Membership
### Table Columns
Name | Phone | Email | Membership | Status | Expires | Last Visit | Actions
### Features
- Membership status badges (Active=green, Expiring=amber, Expired=red, None=gray)
- Filters: All / Active Members / Expiring Soon / Expired / No Membership
- Search by name, email, phone
- Client detail modal with membership + visit history
## Schema Changes
Court model: add `isOpenPlay Boolean @default(false)`
New CourtSession model:
- id, courtId, clientId (optional), walkInName (optional)
- startTime, endTime, isActive
- Relations to Court and Client