853 lines
33 KiB
TypeScript
853 lines
33 KiB
TypeScript
import { useState, useRef } from 'react';
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { useParams, useNavigate, Link } from '@tanstack/react-router';
|
|
import {
|
|
ArrowLeft,
|
|
CalendarClock,
|
|
Check,
|
|
Copy,
|
|
Download,
|
|
FileSpreadsheet,
|
|
Loader2,
|
|
MessageCircle,
|
|
Plus,
|
|
RefreshCw,
|
|
Search,
|
|
Share2,
|
|
Trash2,
|
|
UploadCloud,
|
|
UserPlus,
|
|
Users,
|
|
} from 'lucide-react';
|
|
import type { CreateAttendee } from '@gruperly/shared';
|
|
import { Badge, Button, Input, Label, Modal, useToast } from '../components/ui';
|
|
import {
|
|
bulkCreateAttendees,
|
|
createAttendee,
|
|
getGroup,
|
|
getGroupAttendees,
|
|
getInviteToken,
|
|
} from '../lib/api';
|
|
import {
|
|
downloadAttendeeTemplateCsv,
|
|
normalizeRowsToContacts,
|
|
parseCsvContent,
|
|
parseXlsxContent,
|
|
type ParsedContactRow,
|
|
} from '../lib/file-parser';
|
|
import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format';
|
|
|
|
export function GroupDetailView() {
|
|
const { groupId } = useParams({ strict: false }) as { groupId: string };
|
|
const navigate = useNavigate();
|
|
const queryClient = useQueryClient();
|
|
const toast = useToast();
|
|
|
|
// Modals & Tabs
|
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false);
|
|
const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false);
|
|
const [activeTab, setActiveTab] = useState<'quick' | 'bulk'>('quick');
|
|
|
|
// Quick form state
|
|
const [firstName, setFirstName] = useState('');
|
|
const [lastName, setLastName] = useState('');
|
|
const [phone, setPhone] = useState('');
|
|
const [email, setEmail] = useState('');
|
|
const [notes, setNotes] = useState('');
|
|
|
|
// Bulk upload state
|
|
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([]);
|
|
const [fileName, setFileName] = useState<string | null>(null);
|
|
const [isParsingFile, setIsParsingFile] = useState(false);
|
|
const [isDragging, setIsDragging] = useState(false);
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
|
|
// Attendees search filter
|
|
const [searchFilter, setSearchFilter] = useState('');
|
|
|
|
// Queries
|
|
const groupQuery = useQuery({
|
|
queryKey: ['group', groupId],
|
|
queryFn: () => getGroup(groupId),
|
|
enabled: Boolean(groupId),
|
|
});
|
|
|
|
const inviteTokenQuery = useQuery({
|
|
queryKey: ['invite-token', groupId],
|
|
queryFn: () => getInviteToken(groupId),
|
|
enabled: Boolean(groupId) && isInviteModalOpen,
|
|
});
|
|
|
|
const attendeesQuery = useQuery({
|
|
queryKey: ['group-attendees', groupId],
|
|
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
|
enabled: Boolean(groupId),
|
|
});
|
|
|
|
// Regenerate invite token mutation
|
|
const regenerateTokenMutation = useMutation({
|
|
mutationFn: () => getInviteToken(groupId, true),
|
|
onSuccess: (data) => {
|
|
queryClient.setQueryData(['invite-token', groupId], data);
|
|
toast.success('Se generó un nuevo enlace de invitación.');
|
|
},
|
|
onError: () => {
|
|
toast.error('No se pudo regenerar el enlace de invitación.');
|
|
},
|
|
});
|
|
|
|
// Quick add attendee mutation
|
|
const createAttendeeMutation = useMutation({
|
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
|
onSuccess: (created) => {
|
|
toast.success(`Alumno ${created.fullName} agregado con éxito.`);
|
|
queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] });
|
|
setFirstName('');
|
|
setLastName('');
|
|
setPhone('');
|
|
setEmail('');
|
|
setNotes('');
|
|
setIsAddAttendeeModalOpen(false);
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'Error al agregar alumno.');
|
|
},
|
|
});
|
|
|
|
// Bulk import mutation
|
|
const bulkImportMutation = useMutation({
|
|
mutationFn: (attendees: Array<{ firstName: string; lastName: string; fullName: string; phone: string; email?: string; notes?: string }>) =>
|
|
bulkCreateAttendees(groupId, { attendees }),
|
|
onSuccess: (res) => {
|
|
toast.success(res.message);
|
|
queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] });
|
|
setParsedContacts([]);
|
|
setFileName(null);
|
|
setIsAddAttendeeModalOpen(false);
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'Error al importar alumnos.');
|
|
},
|
|
});
|
|
|
|
const handleCopyLink = async () => {
|
|
const url = inviteTokenQuery.data?.inviteUrl;
|
|
if (!url) return;
|
|
try {
|
|
await navigator.clipboard.writeText(url);
|
|
toast.success('¡Enlace de invitación copiado al portapapeles!');
|
|
} catch {
|
|
toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.');
|
|
}
|
|
};
|
|
|
|
const handleQuickSubmit = (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!firstName.trim() || !phone.trim()) {
|
|
toast.error('Nombre y teléfono son obligatorios.');
|
|
return;
|
|
}
|
|
createAttendeeMutation.mutate({
|
|
firstName: firstName.trim(),
|
|
lastName: lastName.trim(),
|
|
phone: phone.trim(),
|
|
email: email.trim() || undefined,
|
|
notes: notes.trim() || undefined,
|
|
});
|
|
};
|
|
|
|
const processFile = async (file: File) => {
|
|
setIsParsingFile(true);
|
|
setFileName(file.name);
|
|
try {
|
|
let rawRows: string[][] = [];
|
|
const lower = file.name.toLowerCase();
|
|
|
|
if (lower.endsWith('.csv') || lower.endsWith('.txt')) {
|
|
const text = await file.text();
|
|
rawRows = parseCsvContent(text);
|
|
} else if (lower.endsWith('.xlsx') || lower.endsWith('.xls')) {
|
|
const buffer = await file.arrayBuffer();
|
|
rawRows = await parseXlsxContent(buffer);
|
|
} else {
|
|
toast.error('Formato no compatible. Sube un archivo .csv o .xlsx');
|
|
setIsParsingFile(false);
|
|
return;
|
|
}
|
|
|
|
const contacts = normalizeRowsToContacts(rawRows);
|
|
if (contacts.length === 0) {
|
|
toast.error('No se detectaron contactos en el archivo.');
|
|
} else {
|
|
setParsedContacts(contacts);
|
|
const validCount = contacts.filter((c) => c.isValid).length;
|
|
toast.info(`Se detectaron ${contacts.length} filas (${validCount} válidas).`);
|
|
}
|
|
} catch (err: unknown) {
|
|
const message = err instanceof Error ? err.message : 'Error al procesar el archivo.';
|
|
toast.error(message);
|
|
} finally {
|
|
setIsParsingFile(false);
|
|
}
|
|
};
|
|
|
|
const handleFileDrop = (e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
setIsDragging(false);
|
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
|
void processFile(e.dataTransfer.files[0]);
|
|
}
|
|
};
|
|
|
|
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
if (e.target.files && e.target.files.length > 0) {
|
|
void processFile(e.target.files[0]);
|
|
}
|
|
};
|
|
|
|
const removeContactRow = (id: string) => {
|
|
setParsedContacts((prev) => prev.filter((c) => c.id !== id));
|
|
};
|
|
|
|
const handleConfirmBulkImport = () => {
|
|
const validRows = parsedContacts.filter((c) => c.isValid);
|
|
if (validRows.length === 0) {
|
|
toast.error('No hay alumnos válidos para importar.');
|
|
return;
|
|
}
|
|
bulkImportMutation.mutate(
|
|
validRows.map((c) => ({
|
|
firstName: c.firstName,
|
|
lastName: c.lastName,
|
|
fullName: c.fullName,
|
|
phone: c.phone,
|
|
email: c.email || undefined,
|
|
notes: c.notes || undefined,
|
|
})),
|
|
);
|
|
};
|
|
|
|
const group = groupQuery.data;
|
|
const attendees = attendeesQuery.data?.data ?? [];
|
|
const filteredAttendees = attendees.filter((a) => {
|
|
const q = searchFilter.toLowerCase();
|
|
return (
|
|
a.fullName.toLowerCase().includes(q) ||
|
|
(a.phone && a.phone.includes(q)) ||
|
|
(a.email && a.email.toLowerCase().includes(q))
|
|
);
|
|
});
|
|
|
|
const validRowsCount = parsedContacts.filter((c) => c.isValid).length;
|
|
const invalidRowsCount = parsedContacts.length - validRowsCount;
|
|
|
|
const whatsappShareUrl = group && inviteTokenQuery.data?.inviteUrl
|
|
? `https://wa.me/?text=${encodeURIComponent(
|
|
`¡Hola! Te invito a unirte a nuestro grupo "${group.name}". Completa tus datos de inscripción en el siguiente enlace: ${inviteTokenQuery.data.inviteUrl}`,
|
|
)}`
|
|
: '';
|
|
|
|
if (groupQuery.isPending) {
|
|
return (
|
|
<div className="flex items-center justify-center py-20">
|
|
<Loader2 className="size-8 animate-spin text-accent" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (groupQuery.isError || !group) {
|
|
return (
|
|
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
<h2 className="font-semibold text-lg">Grupo no encontrado</h2>
|
|
<p className="mt-2 text-sm">No se pudo cargar la información de este grupo.</p>
|
|
<Button variant="outline" className="mt-4" onClick={() => void navigate({ to: '/groups' })}>
|
|
Volver a Grupos
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<section className="space-y-6 animate-fade-in">
|
|
{/* Navigation & Header */}
|
|
<div>
|
|
<Link
|
|
to="/groups"
|
|
className="inline-flex items-center gap-1 text-sm text-foreground/60 hover:text-primary transition-colors mb-3"
|
|
>
|
|
<ArrowLeft className="size-4" />
|
|
<span>Volver a grupos</span>
|
|
</Link>
|
|
|
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
|
<div>
|
|
<div className="flex items-center gap-2.5">
|
|
<h1 className="text-2xl font-bold text-primary">{group.name}</h1>
|
|
<Badge variant="success">Activo</Badge>
|
|
</div>
|
|
{group.description ? (
|
|
<p className="mt-1 text-sm text-foreground/70">{group.description}</p>
|
|
) : null}
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center gap-2.5">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setIsInviteModalOpen(true)}
|
|
className="gap-2 border-border"
|
|
>
|
|
<Share2 className="size-4 text-accent" />
|
|
<span>Compartir Link</span>
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
onClick={() => setIsAddAttendeeModalOpen(true)}
|
|
className="gap-2"
|
|
>
|
|
<UserPlus className="size-4" />
|
|
<span>Agregar Miembros</span>
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Group Details Card */}
|
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 rounded-xl border border-border bg-surface p-4 text-sm">
|
|
<div className="flex items-center gap-3">
|
|
<CalendarClock className="size-5 text-accent shrink-0" />
|
|
<div>
|
|
<p className="text-xs font-medium text-foreground/50 uppercase">Horario</p>
|
|
<p className="font-medium text-primary">
|
|
{(group.days?.length ?? 0) > 0 ? formatSchedule(group.days ?? [], group.time) : 'Sin horario definido'}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3">
|
|
<Users className="size-5 text-accent shrink-0" />
|
|
<div>
|
|
<p className="text-xs font-medium text-foreground/50 uppercase">Alumnos & Cupo</p>
|
|
<p className="font-medium text-primary">
|
|
{attendees.length} inscritos {group.capacity ? `· Cupo de ${group.capacity}` : ''}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3">
|
|
<div className="size-5 flex items-center justify-center font-bold text-accent shrink-0">
|
|
$
|
|
</div>
|
|
<div>
|
|
<p className="text-xs font-medium text-foreground/50 uppercase">Cobro</p>
|
|
<p className="font-medium text-primary">
|
|
{group.price != null ? formatPrice(group.price) : 'Sin precio'}
|
|
{group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}
|
|
{group.dueDay ? ` · Vence día ${group.dueDay}` : ''}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Attendees Management Section */}
|
|
<div className="rounded-xl border border-border bg-surface p-5 space-y-4">
|
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
|
<div>
|
|
<h2 className="text-lg font-semibold text-primary">
|
|
Miembros del Grupo ({attendees.length})
|
|
</h2>
|
|
<p className="text-xs text-foreground/60">
|
|
Listado de todos los miembros incorporados al grupo.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="relative w-full sm:w-64">
|
|
<Search className="absolute left-3 top-2.5 size-4 text-foreground/40" />
|
|
<Input
|
|
placeholder="Buscar por nombre o teléfono..."
|
|
value={searchFilter}
|
|
onChange={(e) => setSearchFilter(e.target.value)}
|
|
className="pl-9 h-9 text-xs"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{attendeesQuery.isPending ? (
|
|
<div className="flex items-center justify-center py-12">
|
|
<Loader2 className="size-6 animate-spin text-accent" />
|
|
</div>
|
|
) : null}
|
|
|
|
{attendeesQuery.isSuccess && attendees.length === 0 ? (
|
|
<div className="rounded-xl border border-dashed border-border py-12 px-4 text-center">
|
|
<Users className="size-10 text-foreground/30 mx-auto mb-2" />
|
|
<p className="font-medium text-primary">Todavía no hay alumnos en este grupo</p>
|
|
<p className="text-sm text-foreground/60 mt-1 max-w-sm mx-auto">
|
|
Puedes compartir el enlace de invitación único o agregar alumnos de forma manual o masiva.
|
|
</p>
|
|
<div className="mt-4 flex items-center justify-center gap-3">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setIsInviteModalOpen(true)}
|
|
className="gap-2"
|
|
>
|
|
<Share2 className="size-4" />
|
|
Compartir Enlace
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
size="sm"
|
|
onClick={() => setIsAddAttendeeModalOpen(true)}
|
|
className="gap-2"
|
|
>
|
|
<Plus className="size-4" />
|
|
Agregar Alumnos
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
{attendeesQuery.isSuccess && attendees.length > 0 && filteredAttendees.length === 0 ? (
|
|
<div className="py-8 text-center text-sm text-foreground/60">
|
|
No se encontraron alumnos que coincidan con la búsqueda.
|
|
</div>
|
|
) : null}
|
|
|
|
{filteredAttendees.length > 0 ? (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-left text-sm">
|
|
<thead className="border-b border-border text-xs uppercase text-foreground/60 font-semibold">
|
|
<tr>
|
|
<th className="pb-3 px-3">Alumno</th>
|
|
<th className="pb-3 px-3">WhatsApp / Teléfono</th>
|
|
<th className="pb-3 px-3">Email</th>
|
|
<th className="pb-3 px-3">Notas</th>
|
|
<th className="pb-3 px-3 text-right">Incorporado</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-border">
|
|
{filteredAttendees.map((attendee) => {
|
|
const cleanPhone = attendee.phone?.replace(/\D/g, '') ?? '';
|
|
return (
|
|
<tr key={attendee.id} className="hover:bg-primary-soft/50 transition-colors">
|
|
<td className="py-3 px-3">
|
|
<div className="flex items-center gap-2.5">
|
|
<div className="size-8 rounded-full bg-accent/10 text-accent font-semibold flex items-center justify-center text-xs">
|
|
{attendee.fullName.charAt(0).toUpperCase()}
|
|
</div>
|
|
<span className="font-medium text-primary">{attendee.fullName}</span>
|
|
</div>
|
|
</td>
|
|
<td className="py-3 px-3">
|
|
{attendee.phone ? (
|
|
<a
|
|
href={`https://wa.me/${cleanPhone}`}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="inline-flex items-center gap-1.5 text-foreground hover:text-success transition-colors"
|
|
title="Abrir chat en WhatsApp"
|
|
>
|
|
<MessageCircle className="size-4 text-success" />
|
|
<span>{attendee.phone}</span>
|
|
</a>
|
|
) : (
|
|
<span className="text-foreground/40">—</span>
|
|
)}
|
|
</td>
|
|
<td className="py-3 px-3 text-foreground/70">
|
|
{attendee.email || <span className="text-foreground/40">—</span>}
|
|
</td>
|
|
<td className="py-3 px-3 text-foreground/70 text-xs">
|
|
{attendee.notes || <span className="text-foreground/40">—</span>}
|
|
</td>
|
|
<td className="py-3 px-3 text-right text-xs text-foreground/50">
|
|
{new Date(attendee.createdAt).toLocaleDateString('es-ES')}
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
|
|
{/* MODAL: COMPARTIR LINK DE INVITACION */}
|
|
<Modal
|
|
isOpen={isInviteModalOpen}
|
|
onClose={() => setIsInviteModalOpen(false)}
|
|
title="Compartir Link de Invitación"
|
|
description="Envía este enlace a tus alumnos para que completen sus datos e ingresen directamente al grupo."
|
|
maxWidth="md"
|
|
>
|
|
<div className="space-y-5">
|
|
{inviteTokenQuery.isPending ? (
|
|
<div className="flex items-center justify-center py-6">
|
|
<Loader2 className="size-6 animate-spin text-accent" />
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div>
|
|
<Label htmlFor="invite-link-input" className="mb-1.5 block">
|
|
Enlace único del grupo
|
|
</Label>
|
|
<div className="flex items-center gap-2">
|
|
<Input
|
|
id="invite-link-input"
|
|
readOnly
|
|
value={inviteTokenQuery.data?.inviteUrl ?? ''}
|
|
className="font-mono text-xs bg-primary-soft/50 selection:bg-accent selection:text-white"
|
|
/>
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => void handleCopyLink()}
|
|
className="shrink-0 gap-1.5 px-3"
|
|
title="Copiar al portapapeles"
|
|
>
|
|
<Copy className="size-4" />
|
|
<span>Copiar</span>
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="rounded-xl bg-accent-soft p-4 text-xs text-foreground/80 space-y-2 border border-accent/20">
|
|
<p className="font-semibold text-primary">Vista previa del mensaje para WhatsApp:</p>
|
|
<p className="italic">
|
|
“¡Hola! Te invito a unirte a nuestro grupo <strong>{group.name}</strong>. Completa tus datos de inscripción en el siguiente enlace: {inviteTokenQuery.data?.inviteUrl}”
|
|
</p>
|
|
</div>
|
|
|
|
<div className="flex flex-col sm:flex-row items-center gap-2.5 pt-2">
|
|
<a
|
|
href={whatsappShareUrl}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="w-full sm:flex-1"
|
|
>
|
|
<Button
|
|
variant="primary"
|
|
className="w-full gap-2 bg-[#25D366] hover:bg-[#1EBE5D] text-white border-0"
|
|
>
|
|
<MessageCircle className="size-4" />
|
|
<span>Abrir en WhatsApp</span>
|
|
</Button>
|
|
</a>
|
|
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => regenerateTokenMutation.mutate()}
|
|
disabled={regenerateTokenMutation.isPending}
|
|
className="w-full sm:w-auto text-xs text-foreground/60 hover:text-danger gap-1.5"
|
|
title="Invalida el enlace anterior y genera uno nuevo"
|
|
>
|
|
<RefreshCw
|
|
className={`size-3.5 ${regenerateTokenMutation.isPending ? 'animate-spin' : ''}`}
|
|
/>
|
|
<span>Regenerar enlace</span>
|
|
</Button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</Modal>
|
|
|
|
{/* MODAL: AGREGAR ALUMNOS (CARGA INDIVIDUAL / MASIVA) */}
|
|
<Modal
|
|
isOpen={isAddAttendeeModalOpen}
|
|
onClose={() => setIsAddAttendeeModalOpen(false)}
|
|
title="Agregar Miembros al Grupo"
|
|
description="Agrega miembros rápidamente completando sus datos o importa una lista de contactos."
|
|
maxWidth="lg"
|
|
>
|
|
<div>
|
|
{/* Tabs Selector */}
|
|
<div className="flex items-center rounded-xl bg-primary-soft p-1 mb-5">
|
|
<button
|
|
type="button"
|
|
onClick={() => setActiveTab('quick')}
|
|
className={`flex-1 py-2 text-xs font-semibold rounded-lg transition-all ${
|
|
activeTab === 'quick'
|
|
? 'bg-surface text-primary shadow-xs'
|
|
: 'text-foreground/60 hover:text-primary'
|
|
}`}
|
|
>
|
|
Carga Rápida (Individual)
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => setActiveTab('bulk')}
|
|
className={`flex-1 py-2 text-xs font-semibold rounded-lg transition-all ${
|
|
activeTab === 'bulk'
|
|
? 'bg-surface text-primary shadow-xs'
|
|
: 'text-foreground/60 hover:text-primary'
|
|
}`}
|
|
>
|
|
Carga Masiva (CSV / Excel)
|
|
</button>
|
|
</div>
|
|
|
|
{/* TAB 1: CARGA RAPIDA */}
|
|
{activeTab === 'quick' ? (
|
|
<form onSubmit={handleQuickSubmit} className="space-y-4">
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
|
<div>
|
|
<Label htmlFor="quick-first-name" className="mb-1 block text-xs">
|
|
Nombre <span className="text-danger">*</span>
|
|
</Label>
|
|
<Input
|
|
id="quick-first-name"
|
|
placeholder="Ej. Lucas"
|
|
value={firstName}
|
|
onChange={(e) => setFirstName(e.target.value)}
|
|
required
|
|
/>
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="quick-last-name" className="mb-1 block text-xs">
|
|
Apellido
|
|
</Label>
|
|
<Input
|
|
id="quick-last-name"
|
|
placeholder="Ej. González"
|
|
value={lastName}
|
|
onChange={(e) => setLastName(e.target.value)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="quick-phone" className="mb-1 block text-xs">
|
|
Teléfono / WhatsApp <span className="text-danger">*</span>
|
|
</Label>
|
|
<Input
|
|
id="quick-phone"
|
|
placeholder="Ej. +54 9 11 2345-6789"
|
|
value={phone}
|
|
onChange={(e) => setPhone(e.target.value)}
|
|
required
|
|
/>
|
|
<p className="mt-1 text-[11px] text-foreground/50">
|
|
Usado para contacto y validación de duplicados.
|
|
</p>
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="quick-email" className="mb-1 block text-xs">
|
|
Email (opcional)
|
|
</Label>
|
|
<Input
|
|
id="quick-email"
|
|
type="email"
|
|
placeholder="alumno@ejemplo.com"
|
|
value={email}
|
|
onChange={(e) => setEmail(e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="quick-notes" className="mb-1 block text-xs">
|
|
Notas u Observaciones (opcional)
|
|
</Label>
|
|
<Input
|
|
id="quick-notes"
|
|
placeholder="Ej. Nivel intermedio, trae materiales propios"
|
|
value={notes}
|
|
onChange={(e) => setNotes(e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-end gap-2.5 pt-3 border-t border-border">
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => setIsAddAttendeeModalOpen(false)}
|
|
>
|
|
Cancelar
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
type="submit"
|
|
disabled={createAttendeeMutation.isPending}
|
|
className="gap-2"
|
|
>
|
|
{createAttendeeMutation.isPending ? (
|
|
<Loader2 className="size-4 animate-spin" />
|
|
) : (
|
|
<Check className="size-4" />
|
|
)}
|
|
<span>Guardar Alumno</span>
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
) : null}
|
|
|
|
{/* TAB 2: CARGA MASIVA */}
|
|
{activeTab === 'bulk' ? (
|
|
<div className="space-y-4">
|
|
{/* Dropzone */}
|
|
<div
|
|
onDragOver={(e) => {
|
|
e.preventDefault();
|
|
setIsDragging(true);
|
|
}}
|
|
onDragLeave={() => setIsDragging(false)}
|
|
onDrop={handleFileDrop}
|
|
onClick={() => fileInputRef.current?.click()}
|
|
className={`relative flex flex-col items-center justify-center p-6 rounded-xl border-2 border-dashed cursor-pointer transition-all ${
|
|
isDragging
|
|
? 'border-accent bg-accent/5'
|
|
: 'border-border hover:border-accent/60 bg-primary-soft/30'
|
|
}`}
|
|
>
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept=".csv,.xlsx,.xls,.txt"
|
|
className="hidden"
|
|
onChange={handleFileSelect}
|
|
/>
|
|
<UploadCloud className="size-10 text-accent mb-2" />
|
|
<p className="font-semibold text-sm text-primary">
|
|
Arrastra tu archivo aquí o haz clic para seleccionarlo
|
|
</p>
|
|
<p className="text-xs text-foreground/60 mt-1">
|
|
Formatos soportados: CSV (.csv) o Excel (.xlsx)
|
|
</p>
|
|
|
|
{fileName ? (
|
|
<div className="mt-3 flex items-center gap-2 rounded-lg bg-surface border border-border px-3 py-1.5 text-xs text-primary font-medium">
|
|
<FileSpreadsheet className="size-4 text-accent" />
|
|
<span>{fileName}</span>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
|
|
{/* Template Download Link */}
|
|
<div className="flex items-center justify-between text-xs px-1">
|
|
<span className="text-foreground/60">
|
|
¿No tienes el archivo listo? Usa nuestra plantilla.
|
|
</span>
|
|
<button
|
|
type="button"
|
|
onClick={downloadAttendeeTemplateCsv}
|
|
className="inline-flex items-center gap-1 font-medium text-accent hover:text-accent-strong transition-colors"
|
|
>
|
|
<Download className="size-3.5" />
|
|
<span>Descargar plantilla CSV</span>
|
|
</button>
|
|
</div>
|
|
|
|
{isParsingFile ? (
|
|
<div className="flex items-center justify-center py-6 gap-2 text-sm text-foreground/60">
|
|
<Loader2 className="size-4 animate-spin text-accent" />
|
|
<span>Leyendo y analizando archivo...</span>
|
|
</div>
|
|
) : null}
|
|
|
|
{/* Interactive Preview Table */}
|
|
{parsedContacts.length > 0 ? (
|
|
<div className="space-y-3 pt-2">
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2 text-xs">
|
|
<span className="font-semibold text-primary">Vista Previa:</span>
|
|
<Badge variant="success">{validRowsCount} listos para importar</Badge>
|
|
{invalidRowsCount > 0 ? (
|
|
<Badge variant="danger">{invalidRowsCount} con errores</Badge>
|
|
) : null}
|
|
</div>
|
|
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => {
|
|
setParsedContacts([]);
|
|
setFileName(null);
|
|
}}
|
|
className="text-xs text-foreground/50 hover:text-danger h-7 px-2"
|
|
>
|
|
Limpiar lista
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="max-h-60 overflow-y-auto rounded-xl border border-border">
|
|
<table className="w-full text-left text-xs">
|
|
<thead className="sticky top-0 bg-surface border-b border-border font-semibold text-foreground/70">
|
|
<tr>
|
|
<th className="py-2 px-3">Nombre</th>
|
|
<th className="py-2 px-3">Teléfono</th>
|
|
<th className="py-2 px-3">Email</th>
|
|
<th className="py-2 px-3">Estado</th>
|
|
<th className="py-2 px-2 text-right"></th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-border">
|
|
{parsedContacts.map((c) => (
|
|
<tr
|
|
key={c.id}
|
|
className={!c.isValid ? 'bg-danger-soft/30' : 'hover:bg-primary-soft/30'}
|
|
>
|
|
<td className="py-2 px-3 font-medium text-primary">
|
|
{c.fullName || <span className="text-danger italic">Sin nombre</span>}
|
|
</td>
|
|
<td className="py-2 px-3 text-foreground/80">
|
|
{c.phone || <span className="text-danger italic">Sin teléfono</span>}
|
|
</td>
|
|
<td className="py-2 px-3 text-foreground/60">
|
|
{c.email || '—'}
|
|
</td>
|
|
<td className="py-2 px-3">
|
|
{c.isValid ? (
|
|
<Badge variant="success" className="text-[10px] py-0">Válido</Badge>
|
|
) : (
|
|
<Badge variant="danger" className="text-[10px] py-0" title={c.error}>
|
|
{c.error}
|
|
</Badge>
|
|
)}
|
|
</td>
|
|
<td className="py-2 px-2 text-right">
|
|
<button
|
|
type="button"
|
|
onClick={() => removeContactRow(c.id)}
|
|
className="p-1 text-foreground/40 hover:text-danger transition-colors rounded"
|
|
title="Eliminar fila"
|
|
>
|
|
<Trash2 className="size-3.5" />
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-end gap-2.5 pt-3 border-t border-border">
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => setIsAddAttendeeModalOpen(false)}
|
|
>
|
|
Cancelar
|
|
</Button>
|
|
<Button
|
|
variant="primary"
|
|
onClick={handleConfirmBulkImport}
|
|
disabled={bulkImportMutation.isPending || validRowsCount === 0}
|
|
className="gap-2"
|
|
>
|
|
{bulkImportMutation.isPending ? (
|
|
<Loader2 className="size-4 animate-spin" />
|
|
) : (
|
|
<Check className="size-4" />
|
|
)}
|
|
<span>Confirmar e Importar ({validRowsCount})</span>
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
</Modal>
|
|
</section>
|
|
);
|
|
}
|