feat(memberships): add membership management UI
- Add PlanCard component to display plan details with benefits - Add PlanForm for creating/editing membership plans - Add MembershipTable with status badges and actions - Add AssignMembershipDialog for assigning memberships to clients - Add memberships admin page with plans and memberships sections - Include stats cards for active memberships and expiring soon - Support renewal and cancellation workflows Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
597
apps/web/app/(admin)/memberships/page.tsx
Normal file
597
apps/web/app/(admin)/memberships/page.tsx
Normal file
@@ -0,0 +1,597 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { PlanCard } from "@/components/memberships/plan-card";
|
||||||
|
import { PlanForm } from "@/components/memberships/plan-form";
|
||||||
|
import { MembershipTable } from "@/components/memberships/membership-table";
|
||||||
|
import { AssignMembershipDialog } from "@/components/memberships/assign-membership-dialog";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface MembershipPlan {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
benefits: string[] | null;
|
||||||
|
isActive: boolean;
|
||||||
|
subscriberCount: number;
|
||||||
|
benefitsSummary?: {
|
||||||
|
freeHours: number;
|
||||||
|
bookingDiscount: number;
|
||||||
|
extraBenefits: string[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Membership {
|
||||||
|
id: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
status: "ACTIVE" | "EXPIRED" | "CANCELLED" | "SUSPENDED";
|
||||||
|
remainingHours: number | null;
|
||||||
|
autoRenew: boolean;
|
||||||
|
isExpiring?: boolean;
|
||||||
|
daysUntilExpiry?: number | null;
|
||||||
|
plan: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
};
|
||||||
|
client: {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
};
|
||||||
|
benefitsSummary?: {
|
||||||
|
freeHours: number;
|
||||||
|
hoursRemaining: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MembershipsResponse {
|
||||||
|
data: Membership[];
|
||||||
|
pagination: {
|
||||||
|
total: number;
|
||||||
|
limit: number;
|
||||||
|
offset: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusFilters = [
|
||||||
|
{ value: "", label: "Todos" },
|
||||||
|
{ value: "ACTIVE", label: "Activas" },
|
||||||
|
{ value: "EXPIRED", label: "Expiradas" },
|
||||||
|
{ value: "CANCELLED", label: "Canceladas" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function MembershipsPage() {
|
||||||
|
// Plans state
|
||||||
|
const [plans, setPlans] = useState<MembershipPlan[]>([]);
|
||||||
|
const [loadingPlans, setLoadingPlans] = useState(true);
|
||||||
|
const [showPlanForm, setShowPlanForm] = useState(false);
|
||||||
|
const [editingPlan, setEditingPlan] = useState<MembershipPlan | null>(null);
|
||||||
|
const [planFormLoading, setPlanFormLoading] = useState(false);
|
||||||
|
|
||||||
|
// Memberships state
|
||||||
|
const [memberships, setMemberships] = useState<Membership[]>([]);
|
||||||
|
const [loadingMemberships, setLoadingMemberships] = useState(true);
|
||||||
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
|
const [planFilter, setPlanFilter] = useState("");
|
||||||
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
|
const [showAssignDialog, setShowAssignDialog] = useState(false);
|
||||||
|
const [assignLoading, setAssignLoading] = useState(false);
|
||||||
|
|
||||||
|
// Stats
|
||||||
|
const [stats, setStats] = useState({
|
||||||
|
totalActive: 0,
|
||||||
|
expiringSoon: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Fetch plans
|
||||||
|
const fetchPlans = useCallback(async () => {
|
||||||
|
setLoadingPlans(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/membership-plans?includeInactive=true");
|
||||||
|
if (!response.ok) throw new Error("Error al cargar planes");
|
||||||
|
const data = await response.json();
|
||||||
|
setPlans(data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching plans:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
} finally {
|
||||||
|
setLoadingPlans(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Fetch memberships
|
||||||
|
const fetchMemberships = useCallback(async () => {
|
||||||
|
setLoadingMemberships(true);
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (statusFilter) params.append("status", statusFilter);
|
||||||
|
if (planFilter) params.append("planId", planFilter);
|
||||||
|
if (searchQuery) params.append("search", searchQuery);
|
||||||
|
|
||||||
|
const response = await fetch(`/api/memberships?${params.toString()}`);
|
||||||
|
if (!response.ok) throw new Error("Error al cargar membresias");
|
||||||
|
const data: MembershipsResponse = await response.json();
|
||||||
|
setMemberships(data.data);
|
||||||
|
|
||||||
|
// Calculate stats
|
||||||
|
const active = data.data.filter(m => m.status === "ACTIVE");
|
||||||
|
const expiring = data.data.filter(m => m.isExpiring);
|
||||||
|
setStats({
|
||||||
|
totalActive: active.length,
|
||||||
|
expiringSoon: expiring.length,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching memberships:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
} finally {
|
||||||
|
setLoadingMemberships(false);
|
||||||
|
}
|
||||||
|
}, [statusFilter, planFilter, searchQuery]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchPlans();
|
||||||
|
}, [fetchPlans]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchMemberships();
|
||||||
|
}, [fetchMemberships]);
|
||||||
|
|
||||||
|
// Debounce search
|
||||||
|
const [debouncedSearch, setDebouncedSearch] = useState(searchQuery);
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setDebouncedSearch(searchQuery);
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [searchQuery]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (debouncedSearch !== undefined) {
|
||||||
|
fetchMemberships();
|
||||||
|
}
|
||||||
|
}, [debouncedSearch]);
|
||||||
|
|
||||||
|
// Handle plan creation/update
|
||||||
|
const handlePlanSubmit = async (data: {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
price: number;
|
||||||
|
durationMonths: number;
|
||||||
|
freeHours: number;
|
||||||
|
bookingDiscount: number;
|
||||||
|
storeDiscount: number;
|
||||||
|
extraBenefits: string;
|
||||||
|
}) => {
|
||||||
|
setPlanFormLoading(true);
|
||||||
|
try {
|
||||||
|
const extraBenefitsArray = data.extraBenefits
|
||||||
|
.split("\n")
|
||||||
|
.map(b => b.trim())
|
||||||
|
.filter(b => b.length > 0);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
name: data.name,
|
||||||
|
description: data.description || undefined,
|
||||||
|
price: data.price,
|
||||||
|
durationMonths: data.durationMonths,
|
||||||
|
freeHours: data.freeHours || undefined,
|
||||||
|
bookingDiscount: data.bookingDiscount || undefined,
|
||||||
|
storeDiscount: data.storeDiscount || undefined,
|
||||||
|
extraBenefits: extraBenefitsArray.length > 0 ? extraBenefitsArray : undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
const url = editingPlan
|
||||||
|
? `/api/membership-plans/${editingPlan.id}`
|
||||||
|
: "/api/membership-plans";
|
||||||
|
const method = editingPlan ? "PUT" : "POST";
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al guardar plan");
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowPlanForm(false);
|
||||||
|
setEditingPlan(null);
|
||||||
|
await fetchPlans();
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setPlanFormLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle plan deletion
|
||||||
|
const handleDeletePlan = async (plan: MembershipPlan) => {
|
||||||
|
if (!confirm(`¿Estas seguro de eliminar el plan "${plan.name}"? Esta accion lo desactivara.`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/membership-plans/${plan.id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al eliminar plan");
|
||||||
|
}
|
||||||
|
|
||||||
|
await fetchPlans();
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error deleting plan:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle membership assignment
|
||||||
|
const handleAssignMembership = async (data: {
|
||||||
|
clientId: string;
|
||||||
|
planId: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
}) => {
|
||||||
|
setAssignLoading(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");
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowAssignDialog(false);
|
||||||
|
await Promise.all([fetchMemberships(), fetchPlans()]);
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setAssignLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle membership renewal
|
||||||
|
const handleRenewMembership = async (membership: Membership) => {
|
||||||
|
// For renewal, we create a new membership with the same plan
|
||||||
|
const startDate = new Date();
|
||||||
|
const endDate = new Date();
|
||||||
|
endDate.setMonth(endDate.getMonth() + membership.plan.durationMonths);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/memberships", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
clientId: membership.client.id,
|
||||||
|
planId: membership.plan.id,
|
||||||
|
startDate: startDate.toISOString(),
|
||||||
|
endDate: endDate.toISOString(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al renovar membresia");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([fetchMemberships(), fetchPlans()]);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error renewing membership:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle membership cancellation
|
||||||
|
const handleCancelMembership = async (membership: Membership) => {
|
||||||
|
if (!confirm(`¿Estas seguro de cancelar la membresia de ${membership.client.firstName} ${membership.client.lastName}?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/memberships/${membership.id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || "Error al cancelar membresia");
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([fetchMemberships(), fetchPlans()]);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error cancelling membership:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter active plans for assignment dialog
|
||||||
|
const activePlans = plans.filter(p => p.isActive);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
{/* 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">Membresias</h1>
|
||||||
|
<p className="mt-1 text-primary-600">
|
||||||
|
Gestiona planes y membresias de tus clientes
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</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-2 lg:grid-cols-4 gap-4">
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="p-3 rounded-full bg-accent-100">
|
||||||
|
<svg className="w-6 h-6 text-accent-600" 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 0z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-500">Membresias Activas</p>
|
||||||
|
<p className="text-2xl font-bold text-primary-800">{stats.totalActive}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className={cn(stats.expiringSoon > 0 && "border-yellow-300 bg-yellow-50")}>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className={cn(
|
||||||
|
"p-3 rounded-full",
|
||||||
|
stats.expiringSoon > 0 ? "bg-yellow-100" : "bg-primary-100"
|
||||||
|
)}>
|
||||||
|
<svg className={cn(
|
||||||
|
"w-6 h-6",
|
||||||
|
stats.expiringSoon > 0 ? "text-yellow-600" : "text-primary-600"
|
||||||
|
)} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-500">Por Expirar</p>
|
||||||
|
<p className="text-2xl font-bold text-primary-800">{stats.expiringSoon}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="p-3 rounded-full bg-purple-100">
|
||||||
|
<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-500">Planes Activos</p>
|
||||||
|
<p className="text-2xl font-bold text-primary-800">{activePlans.length}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="p-3 rounded-full bg-green-100">
|
||||||
|
<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-500">Total Suscriptores</p>
|
||||||
|
<p className="text-2xl font-bold text-primary-800">
|
||||||
|
{plans.reduce((sum, p) => sum + p.subscriberCount, 0)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Plans Section */}
|
||||||
|
<section>
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-xl font-semibold text-primary-800">Planes de Membresia</h2>
|
||||||
|
<Button onClick={() => setShowPlanForm(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="M12 4v16m8-8H4" />
|
||||||
|
</svg>
|
||||||
|
Nuevo Plan
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loadingPlans ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
|
||||||
|
<p className="text-primary-500">Cargando planes...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : plans.length === 0 ? (
|
||||||
|
<Card className="py-12">
|
||||||
|
<CardContent className="text-center">
|
||||||
|
<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="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
|
||||||
|
</svg>
|
||||||
|
<p className="font-medium text-primary-600">No hay planes</p>
|
||||||
|
<p className="text-sm text-primary-500 mt-1">Crea tu primer plan de membresia</p>
|
||||||
|
<Button className="mt-4" onClick={() => setShowPlanForm(true)}>
|
||||||
|
Crear Plan
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{plans.map((plan) => (
|
||||||
|
<PlanCard
|
||||||
|
key={plan.id}
|
||||||
|
plan={plan}
|
||||||
|
isAdmin={true}
|
||||||
|
onEdit={(p) => {
|
||||||
|
setEditingPlan(p);
|
||||||
|
setShowPlanForm(true);
|
||||||
|
}}
|
||||||
|
onDelete={handleDeletePlan}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Memberships Section */}
|
||||||
|
<section>
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
|
||||||
|
<h2 className="text-xl font-semibold text-primary-800">Membresias</h2>
|
||||||
|
<Button variant="accent" onClick={() => setShowAssignDialog(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>
|
||||||
|
Asignar Membresia
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<Card className="mb-4">
|
||||||
|
<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 de cliente..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Plan Filter */}
|
||||||
|
<div className="sm:w-48">
|
||||||
|
<select
|
||||||
|
value={planFilter}
|
||||||
|
onChange={(e) => setPlanFilter(e.target.value)}
|
||||||
|
className="flex h-10 w-full 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"
|
||||||
|
>
|
||||||
|
<option value="">Todos los planes</option>
|
||||||
|
{activePlans.map((plan) => (
|
||||||
|
<option key={plan.id} value={plan.id}>
|
||||||
|
{plan.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Status Filter */}
|
||||||
|
<div className="flex gap-2 overflow-x-auto pb-2 sm:pb-0">
|
||||||
|
{statusFilters.map((filter) => (
|
||||||
|
<Button
|
||||||
|
key={filter.value}
|
||||||
|
variant={statusFilter === filter.value ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setStatusFilter(filter.value)}
|
||||||
|
className="whitespace-nowrap"
|
||||||
|
>
|
||||||
|
{filter.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Memberships Table */}
|
||||||
|
<Card>
|
||||||
|
<MembershipTable
|
||||||
|
memberships={memberships}
|
||||||
|
onRenew={handleRenewMembership}
|
||||||
|
onCancel={handleCancelMembership}
|
||||||
|
isLoading={loadingMemberships}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Plan Form Modal */}
|
||||||
|
{showPlanForm && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto">
|
||||||
|
<div className="my-8">
|
||||||
|
<PlanForm
|
||||||
|
initialData={editingPlan || undefined}
|
||||||
|
onSubmit={handlePlanSubmit}
|
||||||
|
onCancel={() => {
|
||||||
|
setShowPlanForm(false);
|
||||||
|
setEditingPlan(null);
|
||||||
|
}}
|
||||||
|
isLoading={planFormLoading}
|
||||||
|
mode={editingPlan ? "edit" : "create"}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Assign Membership Dialog */}
|
||||||
|
{showAssignDialog && (
|
||||||
|
<AssignMembershipDialog
|
||||||
|
plans={activePlans}
|
||||||
|
onClose={() => setShowAssignDialog(false)}
|
||||||
|
onAssign={handleAssignMembership}
|
||||||
|
isLoading={assignLoading}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
386
apps/web/components/memberships/assign-membership-dialog.tsx
Normal file
386
apps/web/components/memberships/assign-membership-dialog.tsx
Normal file
@@ -0,0 +1,386 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
|
||||||
|
import { cn, formatCurrency, formatDate } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface Client {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AssignMembershipDialogProps {
|
||||||
|
plans: MembershipPlan[];
|
||||||
|
onClose: () => void;
|
||||||
|
onAssign: (data: {
|
||||||
|
clientId: string;
|
||||||
|
planId: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
}) => Promise<void>;
|
||||||
|
isLoading?: boolean;
|
||||||
|
preselectedClient?: Client;
|
||||||
|
}
|
||||||
|
|
||||||
|
const durationOptions = [
|
||||||
|
{ value: 1, label: "1 mes" },
|
||||||
|
{ value: 3, label: "3 meses" },
|
||||||
|
{ value: 6, label: "6 meses" },
|
||||||
|
{ value: 12, label: "12 meses" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AssignMembershipDialog({
|
||||||
|
plans,
|
||||||
|
onClose,
|
||||||
|
onAssign,
|
||||||
|
isLoading = false,
|
||||||
|
preselectedClient,
|
||||||
|
}: AssignMembershipDialogProps) {
|
||||||
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
|
const [clients, setClients] = useState<Client[]>([]);
|
||||||
|
const [selectedClient, setSelectedClient] = useState<Client | null>(preselectedClient || null);
|
||||||
|
const [loadingClients, setLoadingClients] = useState(false);
|
||||||
|
const [selectedPlanId, setSelectedPlanId] = useState<string>(plans[0]?.id || "");
|
||||||
|
const [startDate, setStartDate] = useState<string>(() => {
|
||||||
|
const today = new Date();
|
||||||
|
return today.toISOString().split("T")[0];
|
||||||
|
});
|
||||||
|
const [duration, setDuration] = useState<number>(1);
|
||||||
|
const [endDate, setEndDate] = useState<string>("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Calculate end date based on start date and duration
|
||||||
|
useEffect(() => {
|
||||||
|
if (startDate && duration) {
|
||||||
|
const start = new Date(startDate);
|
||||||
|
start.setMonth(start.getMonth() + duration);
|
||||||
|
setEndDate(start.toISOString().split("T")[0]);
|
||||||
|
}
|
||||||
|
}, [startDate, duration]);
|
||||||
|
|
||||||
|
// Fetch clients based on search
|
||||||
|
const fetchClients = useCallback(async (search: string) => {
|
||||||
|
if (!search || search.trim().length < 2) {
|
||||||
|
setClients([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoadingClients(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/clients?search=${encodeURIComponent(search)}&limit=10`
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Error al buscar clientes");
|
||||||
|
}
|
||||||
|
const data: ClientsResponse = await response.json();
|
||||||
|
setClients(data.data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching clients:", err);
|
||||||
|
setClients([]);
|
||||||
|
} finally {
|
||||||
|
setLoadingClients(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Debounce client search
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
fetchClients(searchQuery);
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [searchQuery, fetchClients]);
|
||||||
|
|
||||||
|
// Get selected plan details
|
||||||
|
const selectedPlan = plans.find(p => p.id === selectedPlanId);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!selectedClient) {
|
||||||
|
setError("Selecciona un cliente");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!selectedPlanId) {
|
||||||
|
setError("Selecciona un plan");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!startDate || !endDate) {
|
||||||
|
setError("Selecciona las fechas");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setError(null);
|
||||||
|
await onAssign({
|
||||||
|
clientId: selectedClient.id,
|
||||||
|
planId: selectedPlanId,
|
||||||
|
startDate: new Date(startDate).toISOString(),
|
||||||
|
endDate: new Date(endDate).toISOString(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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-lg max-h-[90vh] overflow-hidden flex flex-col my-8">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<CardTitle className="text-lg">Asignar Membresia</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="flex-1 overflow-y-auto space-y-4">
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Client Selection */}
|
||||||
|
{!preselectedClient && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="block text-sm font-medium text-primary-700">
|
||||||
|
Buscar Cliente *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder="Nombre, email o telefono..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Client search results */}
|
||||||
|
<div className="space-y-2 max-h-40 overflow-y-auto">
|
||||||
|
{loadingClients && (
|
||||||
|
<div className="flex items-center justify-center py-4">
|
||||||
|
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loadingClients && searchQuery.length >= 2 && clients.length === 0 && (
|
||||||
|
<p className="text-sm text-primary-500 text-center py-4">
|
||||||
|
No se encontraron clientes.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loadingClients &&
|
||||||
|
clients.map((client) => (
|
||||||
|
<button
|
||||||
|
key={client.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSelectedClient(client)}
|
||||||
|
className={cn(
|
||||||
|
"w-full rounded-md border p-3 text-left transition-all",
|
||||||
|
"hover:border-primary-400 hover:bg-primary-50",
|
||||||
|
selectedClient?.id === client.id
|
||||||
|
? "border-primary-500 bg-primary-50 ring-2 ring-primary-500"
|
||||||
|
: "border-primary-200 bg-white"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<p className="font-medium text-primary-800">
|
||||||
|
{client.firstName} {client.lastName}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-primary-500">
|
||||||
|
{client.email || client.phone || "Sin contacto"}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Selected client summary */}
|
||||||
|
{selectedClient && (
|
||||||
|
<div className="rounded-md border border-accent-200 bg-accent-50 p-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-accent-600">Cliente seleccionado:</p>
|
||||||
|
<p className="font-medium text-accent-800">
|
||||||
|
{selectedClient.firstName} {selectedClient.lastName}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{!preselectedClient && (
|
||||||
|
<button
|
||||||
|
onClick={() => setSelectedClient(null)}
|
||||||
|
className="text-accent-500 hover:text-accent-700"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" 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>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Plan Selection */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-2">
|
||||||
|
Plan de Membresia *
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={selectedPlanId}
|
||||||
|
onChange={(e) => setSelectedPlanId(e.target.value)}
|
||||||
|
className="flex h-10 w-full 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"
|
||||||
|
>
|
||||||
|
<option value="">Selecciona un plan</option>
|
||||||
|
{plans.map((plan) => (
|
||||||
|
<option key={plan.id} value={plan.id}>
|
||||||
|
{plan.name} - {formatCurrency(Number(plan.price))}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
{/* Selected plan details */}
|
||||||
|
{selectedPlan && (
|
||||||
|
<div className="mt-2 p-3 rounded-md bg-primary-50 border border-primary-100">
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-primary-600">Precio:</span>
|
||||||
|
<span className="font-medium text-primary-800">
|
||||||
|
{formatCurrency(Number(selectedPlan.price))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{selectedPlan.courtHours && (
|
||||||
|
<div className="flex justify-between text-sm mt-1">
|
||||||
|
<span className="text-primary-600">Horas incluidas:</span>
|
||||||
|
<span className="font-medium text-primary-800">
|
||||||
|
{selectedPlan.courtHours}h
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{selectedPlan.discountPercent && Number(selectedPlan.discountPercent) > 0 && (
|
||||||
|
<div className="flex justify-between text-sm mt-1">
|
||||||
|
<span className="text-primary-600">Descuento:</span>
|
||||||
|
<span className="font-medium text-primary-800">
|
||||||
|
{Number(selectedPlan.discountPercent)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Date Selection */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Fecha de Inicio
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="date"
|
||||||
|
value={startDate}
|
||||||
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
|
min={new Date().toISOString().split("T")[0]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Duracion
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={duration}
|
||||||
|
onChange={(e) => setDuration(Number(e.target.value))}
|
||||||
|
className="flex h-10 w-full 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"
|
||||||
|
>
|
||||||
|
{durationOptions.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Calculated End Date */}
|
||||||
|
{endDate && (
|
||||||
|
<div className="rounded-md bg-primary-50 border border-primary-100 p-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<svg className="w-5 h-5 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||||
|
</svg>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-primary-500">La membresia expirara el:</p>
|
||||||
|
<p className="font-medium text-primary-800">{formatDate(endDate)}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<CardFooter className="border-t border-primary-200 bg-primary-50 pt-4">
|
||||||
|
<div className="flex w-full gap-3">
|
||||||
|
<Button variant="outline" onClick={onClose} className="flex-1">
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="accent"
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!selectedClient || !selectedPlanId || 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" />
|
||||||
|
Asignando...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
"Asignar Membresia"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
278
apps/web/components/memberships/membership-table.tsx
Normal file
278
apps/web/components/memberships/membership-table.tsx
Normal file
@@ -0,0 +1,278 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { formatCurrency, formatDate, cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface Membership {
|
||||||
|
id: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
status: "ACTIVE" | "EXPIRED" | "CANCELLED" | "SUSPENDED";
|
||||||
|
remainingHours: number | null;
|
||||||
|
autoRenew: boolean;
|
||||||
|
isExpiring?: boolean;
|
||||||
|
daysUntilExpiry?: number | null;
|
||||||
|
plan: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
};
|
||||||
|
client: {
|
||||||
|
id: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string | null;
|
||||||
|
phone: string | null;
|
||||||
|
};
|
||||||
|
benefitsSummary?: {
|
||||||
|
freeHours: number;
|
||||||
|
hoursRemaining: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MembershipTableProps {
|
||||||
|
memberships: Membership[];
|
||||||
|
onRenew?: (membership: Membership) => void;
|
||||||
|
onCancel?: (membership: Membership) => void;
|
||||||
|
onViewDetails?: (membership: Membership) => void;
|
||||||
|
isLoading?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusConfig: Record<string, { label: string; className: string }> = {
|
||||||
|
ACTIVE: {
|
||||||
|
label: "Activa",
|
||||||
|
className: "bg-green-100 text-green-700 border-green-300",
|
||||||
|
},
|
||||||
|
EXPIRED: {
|
||||||
|
label: "Expirada",
|
||||||
|
className: "bg-red-100 text-red-700 border-red-300",
|
||||||
|
},
|
||||||
|
CANCELLED: {
|
||||||
|
label: "Cancelada",
|
||||||
|
className: "bg-gray-100 text-gray-700 border-gray-300",
|
||||||
|
},
|
||||||
|
SUSPENDED: {
|
||||||
|
label: "Suspendida",
|
||||||
|
className: "bg-yellow-100 text-yellow-700 border-yellow-300",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function MembershipTable({
|
||||||
|
memberships,
|
||||||
|
onRenew,
|
||||||
|
onCancel,
|
||||||
|
onViewDetails,
|
||||||
|
isLoading = false,
|
||||||
|
}: MembershipTableProps) {
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
|
||||||
|
<p className="text-primary-500">Cargando membresias...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memberships.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="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="font-medium">No hay membresias</p>
|
||||||
|
<p className="text-sm mt-1">Asigna una membresia a un cliente para comenzar</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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">
|
||||||
|
Plan
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Inicio
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Fin
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Horas Usadas
|
||||||
|
</th>
|
||||||
|
<th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
|
||||||
|
Estado
|
||||||
|
</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">
|
||||||
|
{memberships.map((membership) => {
|
||||||
|
const status = statusConfig[membership.status] || statusConfig.ACTIVE;
|
||||||
|
const hoursTotal = membership.plan.courtHours || membership.benefitsSummary?.freeHours || 0;
|
||||||
|
const hoursRemaining = membership.remainingHours ?? membership.benefitsSummary?.hoursRemaining ?? 0;
|
||||||
|
const hoursUsed = hoursTotal - hoursRemaining;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={membership.id}
|
||||||
|
className={cn(
|
||||||
|
"hover:bg-primary-50 transition-colors",
|
||||||
|
membership.isExpiring && membership.status === "ACTIVE" && "bg-yellow-50"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{/* Client */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-primary-800">
|
||||||
|
{membership.client.firstName} {membership.client.lastName}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-primary-500">
|
||||||
|
{membership.client.email || membership.client.phone || "Sin contacto"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Plan */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-100 text-primary-700">
|
||||||
|
{membership.plan.name}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Start Date */}
|
||||||
|
<td className="px-4 py-4 text-sm text-primary-600">
|
||||||
|
{formatDate(membership.startDate)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* End Date */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-600">
|
||||||
|
{formatDate(membership.endDate)}
|
||||||
|
</p>
|
||||||
|
{membership.isExpiring && membership.status === "ACTIVE" && (
|
||||||
|
<p className="text-xs text-yellow-600 font-medium flex items-center gap-1">
|
||||||
|
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
Expira en {membership.daysUntilExpiry} dias
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Hours Used */}
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
{hoursTotal > 0 ? (
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-primary-700">
|
||||||
|
{hoursUsed} / {hoursTotal}h
|
||||||
|
</p>
|
||||||
|
<div className="mt-1 w-20 h-1.5 bg-primary-100 rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-full rounded-full",
|
||||||
|
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>
|
||||||
|
) : (
|
||||||
|
<span className="text-sm text-primary-400">-</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* 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",
|
||||||
|
status.className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{status.label}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<td className="px-4 py-4 text-right">
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
{membership.status === "ACTIVE" && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onRenew?.(membership)}
|
||||||
|
className="text-accent-600 hover:text-accent-700 hover:bg-accent-50"
|
||||||
|
>
|
||||||
|
<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="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>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onCancel?.(membership)}
|
||||||
|
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<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="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(membership.status === "EXPIRED" || membership.status === "CANCELLED") && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onRenew?.(membership)}
|
||||||
|
className="text-accent-600 hover:text-accent-700 hover:bg-accent-50"
|
||||||
|
>
|
||||||
|
<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="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>
|
||||||
|
Reactivar
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
173
apps/web/components/memberships/plan-card.tsx
Normal file
173
apps/web/components/memberships/plan-card.tsx
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { formatCurrency, cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface MembershipPlan {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
benefits: string[] | null;
|
||||||
|
isActive: boolean;
|
||||||
|
subscriberCount: number;
|
||||||
|
benefitsSummary?: {
|
||||||
|
freeHours: number;
|
||||||
|
bookingDiscount: number;
|
||||||
|
extraBenefits: string[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlanCardProps {
|
||||||
|
plan: MembershipPlan;
|
||||||
|
onEdit?: (plan: MembershipPlan) => void;
|
||||||
|
onDelete?: (plan: MembershipPlan) => void;
|
||||||
|
isAdmin?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PlanCard({ plan, onEdit, onDelete, isAdmin = false }: PlanCardProps) {
|
||||||
|
const price = typeof plan.price === "string" ? parseFloat(plan.price) : plan.price;
|
||||||
|
const discountPercent = plan.benefitsSummary?.bookingDiscount ??
|
||||||
|
(plan.discountPercent ? Number(plan.discountPercent) : 0);
|
||||||
|
const freeHours = plan.benefitsSummary?.freeHours ?? plan.courtHours ?? 0;
|
||||||
|
const extraBenefits = plan.benefitsSummary?.extraBenefits ?? plan.benefits ?? [];
|
||||||
|
|
||||||
|
// Extract store discount from benefits array if present
|
||||||
|
const storeDiscountBenefit = extraBenefits.find(b => b.includes("store discount"));
|
||||||
|
const storeDiscount = storeDiscountBenefit
|
||||||
|
? parseInt(storeDiscountBenefit.match(/(\d+)%/)?.[1] || "0", 10)
|
||||||
|
: 0;
|
||||||
|
const otherBenefits = extraBenefits.filter(b => !b.includes("store discount"));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className={cn(
|
||||||
|
"flex flex-col h-full transition-all hover:shadow-lg",
|
||||||
|
!plan.isActive && "opacity-60"
|
||||||
|
)}>
|
||||||
|
<CardHeader className="pb-2">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<CardTitle className="text-lg">{plan.name}</CardTitle>
|
||||||
|
<span className={cn(
|
||||||
|
"px-2 py-1 text-xs font-medium rounded-full",
|
||||||
|
plan.subscriberCount > 0
|
||||||
|
? "bg-accent-100 text-accent-700"
|
||||||
|
: "bg-primary-100 text-primary-600"
|
||||||
|
)}>
|
||||||
|
{plan.subscriberCount} {plan.subscriberCount === 1 ? "suscriptor" : "suscriptores"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{plan.description && (
|
||||||
|
<p className="text-sm text-primary-500 mt-1">{plan.description}</p>
|
||||||
|
)}
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="flex-1 space-y-4">
|
||||||
|
{/* Price */}
|
||||||
|
<div className="text-center py-3 border-y border-primary-100">
|
||||||
|
<div className="text-3xl font-bold text-primary-800">
|
||||||
|
{formatCurrency(price)}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-primary-500">
|
||||||
|
/{plan.durationMonths} {plan.durationMonths === 1 ? "mes" : "meses"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Key Benefits */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* Free Hours */}
|
||||||
|
{freeHours > 0 && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent-100 flex items-center justify-center">
|
||||||
|
<svg className="w-4 h-4 text-accent-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-primary-800">{freeHours} horas gratis</p>
|
||||||
|
<p className="text-xs text-primary-500">de cancha al mes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Booking Discount */}
|
||||||
|
{discountPercent > 0 && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
|
||||||
|
<svg className="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-primary-800">{discountPercent}% descuento</p>
|
||||||
|
<p className="text-xs text-primary-500">en reservas adicionales</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Store Discount */}
|
||||||
|
{storeDiscount > 0 && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-purple-100 flex items-center justify-center">
|
||||||
|
<svg className="w-4 h-4 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-primary-800">{storeDiscount}% descuento</p>
|
||||||
|
<p className="text-xs text-primary-500">en tienda</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Other Benefits */}
|
||||||
|
{otherBenefits.length > 0 && (
|
||||||
|
<div className="pt-2 border-t border-primary-100">
|
||||||
|
<p className="text-xs font-medium text-primary-600 mb-2">Beneficios adicionales:</p>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{otherBenefits.map((benefit, index) => (
|
||||||
|
<li key={index} className="flex items-start gap-2 text-sm text-primary-700">
|
||||||
|
<svg className="w-4 h-4 text-accent-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||||
|
</svg>
|
||||||
|
<span>{benefit}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
{isAdmin && (
|
||||||
|
<CardFooter className="border-t border-primary-100 pt-4 gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="flex-1"
|
||||||
|
onClick={() => onEdit?.(plan)}
|
||||||
|
>
|
||||||
|
<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"
|
||||||
|
className="flex-1 text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
onClick={() => onDelete?.(plan)}
|
||||||
|
>
|
||||||
|
<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="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>
|
||||||
|
Eliminar
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
314
apps/web/components/memberships/plan-form.tsx
Normal file
314
apps/web/components/memberships/plan-form.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
"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 PlanFormData {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
price: number;
|
||||||
|
durationMonths: number;
|
||||||
|
freeHours: number;
|
||||||
|
bookingDiscount: number;
|
||||||
|
storeDiscount: number;
|
||||||
|
extraBenefits: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MembershipPlan {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
price: number | string;
|
||||||
|
durationMonths: number;
|
||||||
|
courtHours: number | null;
|
||||||
|
discountPercent: number | string | null;
|
||||||
|
benefits: string[] | null;
|
||||||
|
benefitsSummary?: {
|
||||||
|
freeHours: number;
|
||||||
|
bookingDiscount: number;
|
||||||
|
extraBenefits: string[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlanFormProps {
|
||||||
|
initialData?: MembershipPlan;
|
||||||
|
onSubmit: (data: PlanFormData) => Promise<void>;
|
||||||
|
onCancel: () => void;
|
||||||
|
isLoading?: boolean;
|
||||||
|
mode?: "create" | "edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
const durationOptions = [
|
||||||
|
{ value: 1, label: "1 mes" },
|
||||||
|
{ value: 3, label: "3 meses" },
|
||||||
|
{ value: 6, label: "6 meses" },
|
||||||
|
{ value: 12, label: "12 meses" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function PlanForm({
|
||||||
|
initialData,
|
||||||
|
onSubmit,
|
||||||
|
onCancel,
|
||||||
|
isLoading = false,
|
||||||
|
mode = "create",
|
||||||
|
}: PlanFormProps) {
|
||||||
|
// Extract store discount from benefits if present
|
||||||
|
const extractStoreDiscount = (benefits: string[] | null): number => {
|
||||||
|
if (!benefits) return 0;
|
||||||
|
const storeDiscountBenefit = benefits.find(b => b.includes("store discount"));
|
||||||
|
if (storeDiscountBenefit) {
|
||||||
|
const match = storeDiscountBenefit.match(/(\d+)%/);
|
||||||
|
return match ? parseInt(match[1], 10) : 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getOtherBenefits = (benefits: string[] | null): string => {
|
||||||
|
if (!benefits) return "";
|
||||||
|
return benefits
|
||||||
|
.filter(b => !b.includes("store discount"))
|
||||||
|
.join("\n");
|
||||||
|
};
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<PlanFormData>({
|
||||||
|
name: initialData?.name || "",
|
||||||
|
description: initialData?.description || "",
|
||||||
|
price: initialData?.price ? Number(initialData.price) : 0,
|
||||||
|
durationMonths: initialData?.durationMonths || 1,
|
||||||
|
freeHours: initialData?.benefitsSummary?.freeHours ?? initialData?.courtHours ?? 0,
|
||||||
|
bookingDiscount: initialData?.benefitsSummary?.bookingDiscount ??
|
||||||
|
(initialData?.discountPercent ? Number(initialData.discountPercent) : 0),
|
||||||
|
storeDiscount: extractStoreDiscount(initialData?.benefits || null),
|
||||||
|
extraBenefits: getOtherBenefits(initialData?.benefitsSummary?.extraBenefits || initialData?.benefits || null),
|
||||||
|
});
|
||||||
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
const handleChange = (
|
||||||
|
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
|
||||||
|
) => {
|
||||||
|
const { name, value, type } = e.target;
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[name]: type === "number" ? parseFloat(value) || 0 : value,
|
||||||
|
}));
|
||||||
|
// Clear error when field is modified
|
||||||
|
if (errors[name]) {
|
||||||
|
setErrors((prev) => {
|
||||||
|
const newErrors = { ...prev };
|
||||||
|
delete newErrors[name];
|
||||||
|
return newErrors;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validate = (): boolean => {
|
||||||
|
const newErrors: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
newErrors.name = "El nombre es requerido";
|
||||||
|
}
|
||||||
|
if (formData.price <= 0) {
|
||||||
|
newErrors.price = "El precio debe ser mayor a 0";
|
||||||
|
}
|
||||||
|
if (formData.bookingDiscount < 0 || formData.bookingDiscount > 100) {
|
||||||
|
newErrors.bookingDiscount = "El descuento debe estar entre 0 y 100";
|
||||||
|
}
|
||||||
|
if (formData.storeDiscount < 0 || formData.storeDiscount > 100) {
|
||||||
|
newErrors.storeDiscount = "El descuento debe estar entre 0 y 100";
|
||||||
|
}
|
||||||
|
if (formData.freeHours < 0) {
|
||||||
|
newErrors.freeHours = "Las horas gratis no pueden ser negativas";
|
||||||
|
}
|
||||||
|
|
||||||
|
setErrors(newErrors);
|
||||||
|
return Object.keys(newErrors).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!validate()) return;
|
||||||
|
await onSubmit(formData);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="w-full max-w-2xl mx-auto">
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>
|
||||||
|
{mode === "create" ? "Nuevo Plan de Membresia" : "Editar Plan"}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{/* Name */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Nombre del Plan *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
name="name"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="Ej: Plan Premium"
|
||||||
|
className={errors.name ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.name && (
|
||||||
|
<p className="text-red-500 text-xs mt-1">{errors.name}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Descripcion
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
name="description"
|
||||||
|
value={formData.description}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="Descripcion del plan..."
|
||||||
|
rows={2}
|
||||||
|
className="flex w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-primary-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Price and Duration */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Precio *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
name="price"
|
||||||
|
value={formData.price}
|
||||||
|
onChange={handleChange}
|
||||||
|
min={0}
|
||||||
|
step={50}
|
||||||
|
className={errors.price ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.price && (
|
||||||
|
<p className="text-red-500 text-xs mt-1">{errors.price}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Duracion
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
name="durationMonths"
|
||||||
|
value={formData.durationMonths}
|
||||||
|
onChange={handleChange}
|
||||||
|
className="flex h-10 w-full 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"
|
||||||
|
>
|
||||||
|
{durationOptions.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Benefits Section */}
|
||||||
|
<div className="border-t border-primary-200 pt-4 mt-4">
|
||||||
|
<h4 className="text-sm font-semibold text-primary-800 mb-3">Beneficios</h4>
|
||||||
|
|
||||||
|
{/* Free Hours */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Horas Gratis de Cancha (por mes)
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
name="freeHours"
|
||||||
|
value={formData.freeHours}
|
||||||
|
onChange={handleChange}
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
className={errors.freeHours ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.freeHours && (
|
||||||
|
<p className="text-red-500 text-xs mt-1">{errors.freeHours}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Discounts */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Descuento en Reservas (%)
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
name="bookingDiscount"
|
||||||
|
value={formData.bookingDiscount}
|
||||||
|
onChange={handleChange}
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
className={errors.bookingDiscount ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.bookingDiscount && (
|
||||||
|
<p className="text-red-500 text-xs mt-1">{errors.bookingDiscount}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Descuento en Tienda (%)
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
name="storeDiscount"
|
||||||
|
value={formData.storeDiscount}
|
||||||
|
onChange={handleChange}
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
className={errors.storeDiscount ? "border-red-500" : ""}
|
||||||
|
/>
|
||||||
|
{errors.storeDiscount && (
|
||||||
|
<p className="text-red-500 text-xs mt-1">{errors.storeDiscount}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Extra Benefits */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-primary-700 mb-1">
|
||||||
|
Beneficios Adicionales
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
name="extraBenefits"
|
||||||
|
value={formData.extraBenefits}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="Un beneficio por linea Ej: Acceso a vestidores VIP Invitacion a eventos exclusivos"
|
||||||
|
rows={4}
|
||||||
|
className="flex w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-primary-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-primary-500 mt-1">
|
||||||
|
Escribe un beneficio por linea
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
<CardFooter className="flex justify-end gap-3 border-t border-primary-200 bg-primary-50 pt-4">
|
||||||
|
<Button type="button" variant="outline" onClick={onCancel}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isLoading}>
|
||||||
|
{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 Plan"
|
||||||
|
) : (
|
||||||
|
"Guardar Cambios"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user