feat(clients): add clients management page
Add comprehensive clients management interface including: - Client table with search, filtering, and pagination - Client form for creating and editing clients - Client detail dialog showing profile, membership, and stats - API endpoint for individual client operations (GET, PUT, DELETE) - Stats cards showing total clients, with membership, and new this month - Integration with membership assignment dialog Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
605
apps/web/app/(admin)/clients/page.tsx
Normal file
605
apps/web/app/(admin)/clients/page.tsx
Normal file
@@ -0,0 +1,605 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } 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 { 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";
|
||||||
|
|
||||||
|
interface Client {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
avatar?: string | null;
|
||||||
|
level: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
memberships?: Array<{
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
remainingHours: number | null;
|
||||||
|
plan: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
_count?: {
|
||||||
|
bookings: number;
|
||||||
|
};
|
||||||
|
stats?: {
|
||||||
|
totalBookings: number;
|
||||||
|
totalSpent: number;
|
||||||
|
balance: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientsResponse {
|
||||||
|
data: Client[];
|
||||||
|
pagination: {
|
||||||
|
total: number;
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MembershipPlan {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const membershipFilters = [
|
||||||
|
{ value: "", label: "Todos" },
|
||||||
|
{ value: "with", label: "Con membresia" },
|
||||||
|
{ value: "without", label: "Sin membresia" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ITEMS_PER_PAGE = 10;
|
||||||
|
|
||||||
|
export default function ClientsPage() {
|
||||||
|
// Clients state
|
||||||
|
const [clients, setClients] = useState<Client[]>([]);
|
||||||
|
const [loadingClients, setLoadingClients] = useState(true);
|
||||||
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
|
const [membershipFilter, setMembershipFilter] = useState("");
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [totalClients, setTotalClients] = useState(0);
|
||||||
|
|
||||||
|
// Modal state
|
||||||
|
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||||
|
const [editingClient, setEditingClient] = useState<Client | null>(null);
|
||||||
|
const [selectedClient, setSelectedClient] = useState<Client | null>(null);
|
||||||
|
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
|
||||||
|
const fetchClients = useCallback(async () => {
|
||||||
|
setLoadingClients(true);
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (searchQuery) params.append("search", searchQuery);
|
||||||
|
params.append("limit", ITEMS_PER_PAGE.toString());
|
||||||
|
params.append("offset", ((currentPage - 1) * ITEMS_PER_PAGE).toString());
|
||||||
|
|
||||||
|
const response = await fetch(`/api/clients?${params.toString()}`);
|
||||||
|
if (!response.ok) throw new Error("Error al cargar clientes");
|
||||||
|
|
||||||
|
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"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setClients(filteredData);
|
||||||
|
setTotalClients(data.pagination.total);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching clients:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
} finally {
|
||||||
|
setLoadingClients(false);
|
||||||
|
}
|
||||||
|
}, [searchQuery, currentPage, membershipFilter]);
|
||||||
|
|
||||||
|
// 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 al cargar estadisticas");
|
||||||
|
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching stats:", err);
|
||||||
|
} finally {
|
||||||
|
setLoadingStats(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Fetch membership plans
|
||||||
|
const fetchMembershipPlans = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/membership-plans");
|
||||||
|
if (!response.ok) throw new Error("Error al cargar planes");
|
||||||
|
const data = await response.json();
|
||||||
|
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 al cargar detalles del cliente");
|
||||||
|
const data = await response.json();
|
||||||
|
setSelectedClient(data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching client details:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchClients();
|
||||||
|
fetchStats();
|
||||||
|
fetchMembershipPlans();
|
||||||
|
}, [fetchClients, fetchStats, fetchMembershipPlans]);
|
||||||
|
|
||||||
|
// Debounce search
|
||||||
|
const [debouncedSearch, setDebouncedSearch] = useState(searchQuery);
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setDebouncedSearch(searchQuery);
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [searchQuery]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setCurrentPage(1);
|
||||||
|
}, [debouncedSearch, membershipFilter]);
|
||||||
|
|
||||||
|
// Handle create client
|
||||||
|
const handleCreateClient = async (data: {
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
avatar?: string;
|
||||||
|
}) => {
|
||||||
|
setFormLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/clients", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al crear cliente");
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowCreateForm(false);
|
||||||
|
await Promise.all([fetchClients(), fetchStats()]);
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setFormLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle update client
|
||||||
|
const handleUpdateClient = async (data: {
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
avatar?: string;
|
||||||
|
}) => {
|
||||||
|
if (!editingClient) return;
|
||||||
|
|
||||||
|
setFormLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/clients/${editingClient.id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al actualizar cliente");
|
||||||
|
}
|
||||||
|
|
||||||
|
setEditingClient(null);
|
||||||
|
await fetchClients();
|
||||||
|
|
||||||
|
// Update selected client if viewing details
|
||||||
|
if (selectedClient?.id === editingClient.id) {
|
||||||
|
await fetchClientDetails(editingClient.id);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setFormLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle delete client
|
||||||
|
const handleDeleteClient = async (client: Client) => {
|
||||||
|
if (
|
||||||
|
!confirm(
|
||||||
|
`¿Estas seguro de desactivar a ${client.firstName} ${client.lastName}?`
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
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 al desactivar cliente");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([fetchClients(), fetchStats()]);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error deleting client:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle assign membership
|
||||||
|
const handleAssignMembership = async (data: {
|
||||||
|
clientId: string;
|
||||||
|
planId: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
}) => {
|
||||||
|
setFormLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/memberships", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al asignar membresia");
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowAssignMembership(false);
|
||||||
|
await Promise.all([fetchClients(), fetchStats()]);
|
||||||
|
|
||||||
|
// Update selected client if viewing details
|
||||||
|
if (selectedClient) {
|
||||||
|
await fetchClientDetails(selectedClient.id);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setFormLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle row click to view details
|
||||||
|
const handleRowClick = (client: Client) => {
|
||||||
|
fetchClientDetails(client.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calculate pagination
|
||||||
|
const totalPages = Math.ceil(totalClients / ITEMS_PER_PAGE);
|
||||||
|
|
||||||
|
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">Clientes</h1>
|
||||||
|
<p className="mt-1 text-primary-600">
|
||||||
|
Gestiona los clientes de tu centro
|
||||||
|
</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>
|
||||||
|
Nuevo Cliente
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error Message */}
|
||||||
|
{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>
|
||||||
|
<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>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Stats Cards */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||||
|
{loadingStats ? (
|
||||||
|
<>
|
||||||
|
<StatCardSkeleton />
|
||||||
|
<StatCardSkeleton />
|
||||||
|
<StatCardSkeleton />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<StatCard
|
||||||
|
title="Total Clientes"
|
||||||
|
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>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="Con Membresia"
|
||||||
|
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>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="Nuevos Este Mes"
|
||||||
|
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>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-4">
|
||||||
|
<div className="flex flex-col sm:flex-row gap-4">
|
||||||
|
{/* Search */}
|
||||||
|
<div className="flex-1">
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar por nombre, email o telefono..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="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>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</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}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Create Client Form Modal */}
|
||||||
|
{showCreateForm && (
|
||||||
|
<ClientForm
|
||||||
|
onSubmit={handleCreateClient}
|
||||||
|
onCancel={() => setShowCreateForm(false)}
|
||||||
|
isLoading={formLoading}
|
||||||
|
mode="create"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Edit Client Form Modal */}
|
||||||
|
{editingClient && (
|
||||||
|
<ClientForm
|
||||||
|
initialData={{
|
||||||
|
firstName: editingClient.firstName,
|
||||||
|
lastName: editingClient.lastName,
|
||||||
|
email: editingClient.email || "",
|
||||||
|
phone: editingClient.phone || "",
|
||||||
|
avatar: editingClient.avatar || "",
|
||||||
|
}}
|
||||||
|
onSubmit={handleUpdateClient}
|
||||||
|
onCancel={() => setEditingClient(null)}
|
||||||
|
isLoading={formLoading}
|
||||||
|
mode="edit"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Client Detail Dialog */}
|
||||||
|
{selectedClient && !editingClient && (
|
||||||
|
<ClientDetailDialog
|
||||||
|
client={selectedClient}
|
||||||
|
onClose={() => setSelectedClient(null)}
|
||||||
|
onEdit={() => {
|
||||||
|
setEditingClient(selectedClient);
|
||||||
|
}}
|
||||||
|
onAssignMembership={() => {
|
||||||
|
setShowAssignMembership(true);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Assign Membership Dialog */}
|
||||||
|
{showAssignMembership && selectedClient && (
|
||||||
|
<AssignMembershipDialog
|
||||||
|
plans={membershipPlans}
|
||||||
|
preselectedClient={{
|
||||||
|
id: selectedClient.id,
|
||||||
|
firstName: selectedClient.firstName,
|
||||||
|
lastName: selectedClient.lastName,
|
||||||
|
email: selectedClient.email,
|
||||||
|
phone: selectedClient.phone,
|
||||||
|
}}
|
||||||
|
onClose={() => setShowAssignMembership(false)}
|
||||||
|
onAssign={handleAssignMembership}
|
||||||
|
isLoading={formLoading}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
377
apps/web/app/api/clients/[id]/route.ts
Normal file
377
apps/web/app/api/clients/[id]/route.ts
Normal file
@@ -0,0 +1,377 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { getServerSession } from 'next-auth';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
import { db } from '@/lib/db';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
interface RouteContext {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation schema for updating client
|
||||||
|
const updateClientSchema = z.object({
|
||||||
|
firstName: z.string().min(1, 'El nombre es requerido').optional(),
|
||||||
|
lastName: z.string().min(1, 'El apellido es requerido').optional(),
|
||||||
|
email: z.string().email('Email invalido').nullable().optional(),
|
||||||
|
phone: z.string().nullable().optional(),
|
||||||
|
avatar: z.string().url('URL invalida').nullable().optional(),
|
||||||
|
dateOfBirth: z.string().nullable().optional(),
|
||||||
|
address: z.string().nullable().optional(),
|
||||||
|
notes: z.string().nullable().optional(),
|
||||||
|
level: z.string().nullable().optional(),
|
||||||
|
tags: z.array(z.string()).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/clients/[id] - Get a single client with details
|
||||||
|
export async function GET(
|
||||||
|
request: NextRequest,
|
||||||
|
context: RouteContext
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'No autorizado' },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await context.params;
|
||||||
|
|
||||||
|
const client = await db.client.findFirst({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
organizationId: session.user.organizationId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
memberships: {
|
||||||
|
where: {
|
||||||
|
status: 'ACTIVE',
|
||||||
|
endDate: {
|
||||||
|
gte: new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
plan: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
price: true,
|
||||||
|
durationMonths: true,
|
||||||
|
courtHours: true,
|
||||||
|
discountPercent: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
endDate: 'desc',
|
||||||
|
},
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
bookings: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!client) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Cliente no encontrado' },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate total spent from payments
|
||||||
|
const totalSpentResult = await db.payment.aggregate({
|
||||||
|
where: {
|
||||||
|
clientId: client.id,
|
||||||
|
},
|
||||||
|
_sum: {
|
||||||
|
amount: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate total from sales
|
||||||
|
const totalSalesResult = await db.sale.aggregate({
|
||||||
|
where: {
|
||||||
|
clientId: client.id,
|
||||||
|
},
|
||||||
|
_sum: {
|
||||||
|
total: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalSpent =
|
||||||
|
Number(totalSpentResult._sum.amount || 0) +
|
||||||
|
Number(totalSalesResult._sum.total || 0);
|
||||||
|
|
||||||
|
// For now, balance is set to 0 (can be extended with a balance field in the future)
|
||||||
|
const balance = 0;
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
...client,
|
||||||
|
stats: {
|
||||||
|
totalBookings: client._count.bookings,
|
||||||
|
totalSpent,
|
||||||
|
balance,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching client:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Error al obtener el cliente' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PUT /api/clients/[id] - Update a client
|
||||||
|
export async function PUT(
|
||||||
|
request: NextRequest,
|
||||||
|
context: RouteContext
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'No autorizado' },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await context.params;
|
||||||
|
|
||||||
|
// Verify client exists and belongs to user's organization
|
||||||
|
const existingClient = await db.client.findFirst({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
organizationId: session.user.organizationId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existingClient) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Cliente no encontrado' },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
|
||||||
|
// Validate input
|
||||||
|
const validationResult = updateClientSchema.safeParse(body);
|
||||||
|
if (!validationResult.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: 'Datos de actualizacion invalidos',
|
||||||
|
details: validationResult.error.flatten().fieldErrors,
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
email,
|
||||||
|
phone,
|
||||||
|
avatar,
|
||||||
|
dateOfBirth,
|
||||||
|
address,
|
||||||
|
notes,
|
||||||
|
level,
|
||||||
|
tags,
|
||||||
|
} = validationResult.data;
|
||||||
|
|
||||||
|
// Check for email uniqueness if email is being changed
|
||||||
|
if (email && email !== existingClient.email) {
|
||||||
|
const emailExists = await db.client.findFirst({
|
||||||
|
where: {
|
||||||
|
organizationId: session.user.organizationId,
|
||||||
|
email,
|
||||||
|
id: {
|
||||||
|
not: id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (emailExists) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Ya existe un cliente con este email' },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build update data
|
||||||
|
const updateData: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
if (firstName !== undefined) updateData.firstName = firstName;
|
||||||
|
if (lastName !== undefined) updateData.lastName = lastName;
|
||||||
|
if (email !== undefined) updateData.email = email;
|
||||||
|
if (phone !== undefined) updateData.phone = phone;
|
||||||
|
if (avatar !== undefined) updateData.avatar = avatar;
|
||||||
|
if (dateOfBirth !== undefined) {
|
||||||
|
updateData.dateOfBirth = dateOfBirth ? new Date(dateOfBirth) : null;
|
||||||
|
}
|
||||||
|
if (address !== undefined) updateData.address = address;
|
||||||
|
if (notes !== undefined) updateData.notes = notes;
|
||||||
|
if (level !== undefined) updateData.level = level;
|
||||||
|
if (tags !== undefined) updateData.tags = tags;
|
||||||
|
|
||||||
|
const client = await db.client.update({
|
||||||
|
where: { id },
|
||||||
|
data: updateData,
|
||||||
|
include: {
|
||||||
|
memberships: {
|
||||||
|
where: {
|
||||||
|
status: 'ACTIVE',
|
||||||
|
endDate: {
|
||||||
|
gte: new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
plan: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
price: true,
|
||||||
|
durationMonths: true,
|
||||||
|
courtHours: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
bookings: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(client);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating client:', error);
|
||||||
|
|
||||||
|
// Check for unique constraint violation
|
||||||
|
if (error instanceof Error && error.message.includes('Unique constraint')) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Ya existe un cliente con este email o DNI' },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Error al actualizar el cliente' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/clients/[id] - Soft delete a client (set isActive = false)
|
||||||
|
export async function DELETE(
|
||||||
|
request: NextRequest,
|
||||||
|
context: RouteContext
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'No autorizado' },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await context.params;
|
||||||
|
|
||||||
|
// Verify client exists and belongs to user's organization
|
||||||
|
const existingClient = await db.client.findFirst({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
organizationId: session.user.organizationId,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
memberships: {
|
||||||
|
where: {
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
bookings: {
|
||||||
|
where: {
|
||||||
|
status: {
|
||||||
|
in: ['PENDING', 'CONFIRMED'],
|
||||||
|
},
|
||||||
|
startTime: {
|
||||||
|
gte: new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existingClient) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Cliente no encontrado' },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for active memberships
|
||||||
|
if (existingClient.memberships.length > 0) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: 'No se puede desactivar un cliente con membresia activa',
|
||||||
|
details: {
|
||||||
|
activeMemberships: existingClient.memberships.length,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for pending/future bookings
|
||||||
|
if (existingClient.bookings.length > 0) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: 'No se puede desactivar un cliente con reservas pendientes',
|
||||||
|
details: {
|
||||||
|
pendingBookings: existingClient.bookings.length,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Soft delete by setting isActive to false
|
||||||
|
const client = await db.client.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
isActive: false,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Cliente desactivado exitosamente',
|
||||||
|
client,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting client:', error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Error al desactivar el cliente' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
430
apps/web/components/clients/client-detail-dialog.tsx
Normal file
430
apps/web/components/clients/client-detail-dialog.tsx
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { formatCurrency, formatDate, cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface ClientMembership {
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
remainingHours: number | null;
|
||||||
|
plan: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientDetail {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
avatar?: string | null;
|
||||||
|
level: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
memberships?: ClientMembership[];
|
||||||
|
_count?: {
|
||||||
|
bookings: number;
|
||||||
|
};
|
||||||
|
stats?: {
|
||||||
|
totalBookings: number;
|
||||||
|
totalSpent: number;
|
||||||
|
balance: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientDetailDialogProps {
|
||||||
|
client: ClientDetail;
|
||||||
|
onClose: () => void;
|
||||||
|
onEdit?: () => void;
|
||||||
|
onAssignMembership?: () => void;
|
||||||
|
onAddBalance?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ClientDetailDialog({
|
||||||
|
client,
|
||||||
|
onClose,
|
||||||
|
onEdit,
|
||||||
|
onAssignMembership,
|
||||||
|
onAddBalance,
|
||||||
|
}: ClientDetailDialogProps) {
|
||||||
|
// Get initials for avatar fallback
|
||||||
|
const getInitials = (firstName: string, lastName: string) => {
|
||||||
|
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get active membership
|
||||||
|
const activeMembership = client.memberships?.find(
|
||||||
|
(m) => m.status === "ACTIVE"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calculate hours used if there's an active membership with hours
|
||||||
|
const hoursTotal = activeMembership?.plan.courtHours || 0;
|
||||||
|
const hoursRemaining = activeMembership?.remainingHours || 0;
|
||||||
|
const hoursUsed = hoursTotal - hoursRemaining;
|
||||||
|
|
||||||
|
// Handle click outside to close
|
||||||
|
const handleOverlayClick = (e: React.MouseEvent) => {
|
||||||
|
if (e.target === e.currentTarget) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto"
|
||||||
|
onClick={handleOverlayClick}
|
||||||
|
>
|
||||||
|
<Card className="w-full max-w-2xl my-8">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<CardTitle className="text-lg">Detalle del Cliente</CardTitle>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-full p-1 hover:bg-primary-100 transition-colors"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="h-5 w-5 text-primary-500"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M6 18L18 6M6 6l12 12"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="space-y-6">
|
||||||
|
{/* Profile Section */}
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
{client.avatar ? (
|
||||||
|
<img
|
||||||
|
src={client.avatar}
|
||||||
|
alt={`${client.firstName} ${client.lastName}`}
|
||||||
|
className="h-20 w-20 rounded-full object-cover border-4 border-primary-100"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-20 w-20 rounded-full bg-primary-100 flex items-center justify-center border-4 border-primary-50">
|
||||||
|
<span className="text-2xl font-bold text-primary-600">
|
||||||
|
{getInitials(client.firstName, client.lastName)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h2 className="text-xl font-bold text-primary-800">
|
||||||
|
{client.firstName} {client.lastName}
|
||||||
|
</h2>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",
|
||||||
|
client.isActive
|
||||||
|
? "bg-green-100 text-green-700"
|
||||||
|
: "bg-red-100 text-red-700"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{client.isActive ? "Activo" : "Inactivo"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{client.level && (
|
||||||
|
<p className="text-sm text-primary-500 mt-1">
|
||||||
|
Nivel: {client.level}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{client.email && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-primary-600">
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{client.email}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{client.phone && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-primary-600">
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{client.phone}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Membership Section */}
|
||||||
|
<div className="border border-primary-200 rounded-lg overflow-hidden">
|
||||||
|
<div className="bg-primary-50 px-4 py-2 border-b border-primary-200">
|
||||||
|
<h3 className="font-semibold text-primary-800">Membresia</h3>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
{activeMembership ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-primary-600">Plan:</span>
|
||||||
|
<span className="font-medium text-primary-800 bg-accent-100 px-2 py-0.5 rounded-full text-sm">
|
||||||
|
{activeMembership.plan.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-primary-600">Precio:</span>
|
||||||
|
<span className="font-medium text-primary-800">
|
||||||
|
{formatCurrency(Number(activeMembership.plan.price))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-primary-600">Inicio:</span>
|
||||||
|
<span className="text-primary-800">
|
||||||
|
{formatDate(activeMembership.startDate)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-primary-600">Vencimiento:</span>
|
||||||
|
<span className="text-primary-800">
|
||||||
|
{formatDate(activeMembership.endDate)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hoursTotal > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className="text-sm text-primary-600">
|
||||||
|
Horas usadas:
|
||||||
|
</span>
|
||||||
|
<span className="text-sm font-medium text-primary-800">
|
||||||
|
{hoursUsed} / {hoursTotal}h
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full h-2 bg-primary-100 rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-full rounded-full transition-all",
|
||||||
|
hoursUsed >= hoursTotal
|
||||||
|
? "bg-red-500"
|
||||||
|
: hoursUsed >= hoursTotal * 0.75
|
||||||
|
? "bg-yellow-500"
|
||||||
|
: "bg-accent-500"
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
width: `${Math.min(
|
||||||
|
(hoursUsed / hoursTotal) * 100,
|
||||||
|
100
|
||||||
|
)}%`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-4">
|
||||||
|
<svg
|
||||||
|
className="w-8 h-8 mx-auto mb-2 text-primary-300"
|
||||||
|
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>
|
||||||
|
<p className="text-sm text-primary-500">Sin membresia activa</p>
|
||||||
|
{onAssignMembership && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={onAssignMembership}
|
||||||
|
className="mt-2"
|
||||||
|
>
|
||||||
|
Asignar Membresia
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stats Section */}
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
<div className="text-center p-4 bg-primary-50 rounded-lg">
|
||||||
|
<p className="text-2xl font-bold text-primary-800">
|
||||||
|
{client.stats?.totalBookings || client._count?.bookings || 0}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-primary-500">Reservas</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-center p-4 bg-primary-50 rounded-lg">
|
||||||
|
<p className="text-2xl font-bold text-primary-800">
|
||||||
|
{formatCurrency(client.stats?.totalSpent || 0)}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-primary-500">Total Gastado</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-center p-4 bg-primary-50 rounded-lg">
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"text-2xl font-bold",
|
||||||
|
(client.stats?.balance || 0) >= 0
|
||||||
|
? "text-green-600"
|
||||||
|
: "text-red-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{formatCurrency(client.stats?.balance || 0)}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-primary-500">Saldo</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Notes Section */}
|
||||||
|
{client.notes && (
|
||||||
|
<div className="border border-primary-200 rounded-lg overflow-hidden">
|
||||||
|
<div className="bg-primary-50 px-4 py-2 border-b border-primary-200">
|
||||||
|
<h3 className="font-semibold text-primary-800">Notas</h3>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<p className="text-sm text-primary-600 whitespace-pre-wrap">
|
||||||
|
{client.notes}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Member Since */}
|
||||||
|
<div className="text-center text-sm text-primary-500">
|
||||||
|
Cliente desde {formatDate(client.createdAt)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action Buttons */}
|
||||||
|
<div className="flex gap-3 pt-4 border-t border-primary-200">
|
||||||
|
{onEdit && (
|
||||||
|
<Button variant="outline" onClick={onEdit} className="flex-1">
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-2"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Editar
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeMembership && onAssignMembership && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onAssignMembership}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-2"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Renovar
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!activeMembership && onAssignMembership && (
|
||||||
|
<Button
|
||||||
|
variant="accent"
|
||||||
|
onClick={onAssignMembership}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-2"
|
||||||
|
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>
|
||||||
|
Asignar Membresia
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{onAddBalance && (
|
||||||
|
<Button variant="outline" onClick={onAddBalance} className="flex-1">
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-2"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Agregar Saldo
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
313
apps/web/components/clients/client-form.tsx
Normal file
313
apps/web/components/clients/client-form.tsx
Normal file
@@ -0,0 +1,313 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
|
||||||
|
|
||||||
|
interface ClientFormData {
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
avatar?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientFormProps {
|
||||||
|
initialData?: Partial<ClientFormData>;
|
||||||
|
onSubmit: (data: ClientFormData) => Promise<void>;
|
||||||
|
onCancel: () => void;
|
||||||
|
isLoading?: boolean;
|
||||||
|
mode?: "create" | "edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ClientForm({
|
||||||
|
initialData,
|
||||||
|
onSubmit,
|
||||||
|
onCancel,
|
||||||
|
isLoading = false,
|
||||||
|
mode = "create",
|
||||||
|
}: ClientFormProps) {
|
||||||
|
const [formData, setFormData] = useState<ClientFormData>({
|
||||||
|
firstName: "",
|
||||||
|
lastName: "",
|
||||||
|
email: "",
|
||||||
|
phone: "",
|
||||||
|
avatar: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
// Initialize form with initial data
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialData) {
|
||||||
|
setFormData({
|
||||||
|
firstName: initialData.firstName || "",
|
||||||
|
lastName: initialData.lastName || "",
|
||||||
|
email: initialData.email || "",
|
||||||
|
phone: initialData.phone || "",
|
||||||
|
avatar: initialData.avatar || "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [initialData]);
|
||||||
|
|
||||||
|
// Validate email format
|
||||||
|
const isValidEmail = (email: string): boolean => {
|
||||||
|
if (!email) return true; // Email is optional
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
return emailRegex.test(email);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Validate form
|
||||||
|
const validateForm = (): boolean => {
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (!formData.firstName.trim()) {
|
||||||
|
newErrors.firstName = "El nombre es requerido";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!formData.lastName.trim()) {
|
||||||
|
newErrors.lastName = "El apellido es requerido";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.email && !isValidEmail(formData.email)) {
|
||||||
|
newErrors.email = "Formato de email invalido";
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle form submission
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (!validateForm()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await onSubmit(formData);
|
||||||
|
} catch (err) {
|
||||||
|
// Error handling is done in parent component
|
||||||
|
console.error("Error submitting form:", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle input change
|
||||||
|
const handleChange = (
|
||||||
|
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
|
||||||
|
) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[name]: value,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Clear error when user starts typing
|
||||||
|
if (errors[name]) {
|
||||||
|
setErrors((prev) => {
|
||||||
|
const newErrors = { ...prev };
|
||||||
|
delete newErrors[name];
|
||||||
|
return newErrors;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle click outside to close
|
||||||
|
const handleOverlayClick = (e: React.MouseEvent) => {
|
||||||
|
if (e.target === e.currentTarget) {
|
||||||
|
onCancel();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto"
|
||||||
|
onClick={handleOverlayClick}
|
||||||
|
>
|
||||||
|
<Card className="w-full max-w-md my-8">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<CardTitle className="text-lg">
|
||||||
|
{mode === "create" ? "Nuevo Cliente" : "Editar Cliente"}
|
||||||
|
</CardTitle>
|
||||||
|
<button
|
||||||
|
onClick={onCancel}
|
||||||
|
className="rounded-full p-1 hover:bg-primary-100 transition-colors"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="h-5 w-5 text-primary-500"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M6 18L18 6M6 6l12 12"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{/* First Name */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="firstName"
|
||||||
|
className="block text-sm font-medium text-primary-700 mb-1"
|
||||||
|
>
|
||||||
|
Nombre *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="firstName"
|
||||||
|
name="firstName"
|
||||||
|
type="text"
|
||||||
|
value={formData.firstName}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="Juan"
|
||||||
|
className={errors.firstName ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.firstName && (
|
||||||
|
<p className="mt-1 text-sm text-red-600">{errors.firstName}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Last Name */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="lastName"
|
||||||
|
className="block text-sm font-medium text-primary-700 mb-1"
|
||||||
|
>
|
||||||
|
Apellido *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="lastName"
|
||||||
|
name="lastName"
|
||||||
|
type="text"
|
||||||
|
value={formData.lastName}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="Garcia"
|
||||||
|
className={errors.lastName ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.lastName && (
|
||||||
|
<p className="mt-1 text-sm text-red-600">{errors.lastName}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Email */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="email"
|
||||||
|
className="block text-sm font-medium text-primary-700 mb-1"
|
||||||
|
>
|
||||||
|
Email
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="juan@ejemplo.com"
|
||||||
|
className={errors.email ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.email && (
|
||||||
|
<p className="mt-1 text-sm text-red-600">{errors.email}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Phone */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="phone"
|
||||||
|
className="block text-sm font-medium text-primary-700 mb-1"
|
||||||
|
>
|
||||||
|
Telefono
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="phone"
|
||||||
|
name="phone"
|
||||||
|
type="tel"
|
||||||
|
value={formData.phone}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="+34 600 123 456"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Avatar URL */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="avatar"
|
||||||
|
className="block text-sm font-medium text-primary-700 mb-1"
|
||||||
|
>
|
||||||
|
URL de Foto
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="avatar"
|
||||||
|
name="avatar"
|
||||||
|
type="url"
|
||||||
|
value={formData.avatar}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="https://ejemplo.com/foto.jpg"
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-primary-500">
|
||||||
|
URL de una imagen para el avatar del cliente
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Avatar Preview */}
|
||||||
|
{formData.avatar && (
|
||||||
|
<div className="flex items-center gap-3 p-3 bg-primary-50 rounded-md">
|
||||||
|
<img
|
||||||
|
src={formData.avatar}
|
||||||
|
alt="Vista previa"
|
||||||
|
className="h-12 w-12 rounded-full object-cover"
|
||||||
|
onError={(e) => {
|
||||||
|
(e.target as HTMLImageElement).style.display = "none";
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-primary-600">Vista previa</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<CardFooter className="border-t border-primary-200 bg-primary-50 pt-4">
|
||||||
|
<div className="flex w-full gap-3">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="flex-1"
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="accent"
|
||||||
|
disabled={isLoading}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
|
||||||
|
Guardando...
|
||||||
|
</span>
|
||||||
|
) : mode === "create" ? (
|
||||||
|
"Crear Cliente"
|
||||||
|
) : (
|
||||||
|
"Guardar Cambios"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardFooter>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
376
apps/web/components/clients/client-table.tsx
Normal file
376
apps/web/components/clients/client-table.tsx
Normal file
@@ -0,0 +1,376 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface Client {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
avatar?: string | null;
|
||||||
|
level: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
memberships?: Array<{
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
remainingHours: number | null;
|
||||||
|
endDate: string;
|
||||||
|
plan: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
_count?: {
|
||||||
|
bookings: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClientTableProps {
|
||||||
|
clients: Client[];
|
||||||
|
onRowClick?: (client: Client) => void;
|
||||||
|
onEdit?: (client: Client) => void;
|
||||||
|
onDelete?: (client: Client) => void;
|
||||||
|
isLoading?: boolean;
|
||||||
|
currentPage: number;
|
||||||
|
totalPages: number;
|
||||||
|
onPageChange: (page: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loading skeleton for table rows
|
||||||
|
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-10 w-10 rounded-full bg-primary-100" />
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="h-4 w-32 bg-primary-100 rounded" />
|
||||||
|
<div className="h-3 w-24 bg-primary-100 rounded" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div className="h-4 w-40 bg-primary-100 rounded" />
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div className="h-4 w-28 bg-primary-100 rounded" />
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div className="h-6 w-20 bg-primary-100 rounded-full" />
|
||||||
|
</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="flex justify-end gap-2">
|
||||||
|
<div className="h-8 w-16 bg-primary-100 rounded" />
|
||||||
|
<div className="h-8 w-16 bg-primary-100 rounded" />
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ClientTable({
|
||||||
|
clients,
|
||||||
|
onRowClick,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
isLoading = false,
|
||||||
|
currentPage,
|
||||||
|
totalPages,
|
||||||
|
onPageChange,
|
||||||
|
}: ClientTableProps) {
|
||||||
|
// Get initials for avatar fallback
|
||||||
|
const getInitials = (firstName: string, lastName: string) => {
|
||||||
|
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get membership badge info
|
||||||
|
const getMembershipBadge = (client: Client) => {
|
||||||
|
const activeMembership = client.memberships?.[0];
|
||||||
|
if (activeMembership && activeMembership.status === "ACTIVE") {
|
||||||
|
return {
|
||||||
|
label: activeMembership.plan.name,
|
||||||
|
className: "bg-accent-100 text-accent-700 border-accent-300",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
label: "Sin membresia",
|
||||||
|
className: "bg-gray-100 text-gray-600 border-gray-200",
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<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">
|
||||||
|
Cliente
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Email
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Telefono
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Membresia
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Reservas
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Acciones
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-primary-100">
|
||||||
|
<TableSkeleton />
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clients.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<div className="text-center text-primary-500">
|
||||||
|
<svg
|
||||||
|
className="w-12 h-12 mx-auto mb-3 text-primary-300"
|
||||||
|
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>
|
||||||
|
<p className="font-medium">No hay clientes</p>
|
||||||
|
<p className="text-sm mt-1">Agrega tu primer cliente para comenzar</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<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">
|
||||||
|
Cliente
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Email
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Telefono
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Membresia
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Reservas
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Acciones
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-primary-100">
|
||||||
|
{clients.map((client) => {
|
||||||
|
const membershipBadge = getMembershipBadge(client);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={client.id}
|
||||||
|
className="hover:bg-primary-50 transition-colors cursor-pointer"
|
||||||
|
onClick={() => onRowClick?.(client)}
|
||||||
|
>
|
||||||
|
{/* Client Name with Avatar */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{client.avatar ? (
|
||||||
|
<img
|
||||||
|
src={client.avatar}
|
||||||
|
alt={`${client.firstName} ${client.lastName}`}
|
||||||
|
className="h-10 w-10 rounded-full object-cover"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="h-10 w-10 rounded-full bg-primary-100 flex items-center justify-center">
|
||||||
|
<span className="text-sm font-medium text-primary-600">
|
||||||
|
{getInitials(client.firstName, client.lastName)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-primary-800">
|
||||||
|
{client.firstName} {client.lastName}
|
||||||
|
</p>
|
||||||
|
{client.level && (
|
||||||
|
<p className="text-xs text-primary-500">
|
||||||
|
Nivel: {client.level}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Email */}
|
||||||
|
<td className="px-4 py-4 text-sm text-primary-600">
|
||||||
|
{client.email || (
|
||||||
|
<span className="text-primary-400">-</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Phone */}
|
||||||
|
<td className="px-4 py-4 text-sm text-primary-600">
|
||||||
|
{client.phone || (
|
||||||
|
<span className="text-primary-400">-</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Membership Status */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border",
|
||||||
|
membershipBadge.className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{membershipBadge.label}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Bookings Count */}
|
||||||
|
<td className="px-4 py-4 text-sm text-primary-600">
|
||||||
|
{client._count?.bookings || 0}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<td className="px-4 py-4 text-right">
|
||||||
|
<div
|
||||||
|
className="flex items-center justify-end gap-2"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onEdit?.(client)}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-1"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Editar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onDelete?.(client)}
|
||||||
|
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</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">
|
||||||
|
Pagina {currentPage} de {totalPages}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onPageChange(currentPage - 1)}
|
||||||
|
disabled={currentPage <= 1}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 mr-1"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M15 19l-7-7 7-7"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
Anterior
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onPageChange(currentPage + 1)}
|
||||||
|
disabled={currentPage >= totalPages}
|
||||||
|
>
|
||||||
|
Siguiente
|
||||||
|
<svg
|
||||||
|
className="w-4 h-4 ml-1"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
strokeWidth={2}
|
||||||
|
d="M9 5l7 7-7 7"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user