Initial attendee management
This commit is contained in:
@@ -3,3 +3,6 @@ export { Button, type ButtonProps, type ButtonVariant, type ButtonSize } from '.
|
||||
export { Badge, type BadgeProps, type BadgeVariant } from './badge'
|
||||
export { Input, type InputProps } from './input'
|
||||
export { Label, type LabelProps } from './label'
|
||||
export { Modal, type ModalProps } from './modal'
|
||||
export { ToastProvider, useToast, type ToastType, type Toast } from './toast'
|
||||
|
||||
|
||||
91
apps/web/src/components/ui/modal.tsx
Normal file
91
apps/web/src/components/ui/modal.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { useEffect, type ReactNode } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
export type ModalProps = {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
description?: string;
|
||||
children: ReactNode;
|
||||
maxWidth?: 'sm' | 'md' | 'lg' | 'xl' | '2xl';
|
||||
};
|
||||
|
||||
const maxWidthClasses = {
|
||||
sm: 'max-w-sm',
|
||||
md: 'max-w-md',
|
||||
lg: 'max-w-lg',
|
||||
xl: 'max-w-xl',
|
||||
'2xl': 'max-w-2xl',
|
||||
};
|
||||
|
||||
export function Modal({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
maxWidth = 'lg',
|
||||
}: ModalProps) {
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'hidden';
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'unset';
|
||||
};
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
className="fixed inset-0 z-50 flex items-center justify-center p-4 overflow-y-auto"
|
||||
>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/60 backdrop-blur-xs transition-opacity animate-fade-in"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
{/* Modal Dialog */}
|
||||
<div
|
||||
className={cn(
|
||||
'relative w-full rounded-2xl border border-border bg-surface p-6 shadow-2xl transition-all animate-step-enter my-8',
|
||||
maxWidthClasses[maxWidth],
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-lg font-bold text-primary">{title}</h2>
|
||||
{description ? (
|
||||
<p className="mt-1 text-sm text-foreground/70">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="shrink-0 -mr-2 -mt-2 p-2 rounded-xl text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
|
||||
aria-label="Cerrar modal"
|
||||
>
|
||||
<X className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-5">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
146
apps/web/src/components/ui/toast.tsx
Normal file
146
apps/web/src/components/ui/toast.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
export type ToastType = 'success' | 'error' | 'info';
|
||||
|
||||
export type Toast = {
|
||||
id: string;
|
||||
type: ToastType;
|
||||
title?: string;
|
||||
message: string;
|
||||
duration?: number;
|
||||
};
|
||||
|
||||
type ToastContextValue = {
|
||||
toasts: Toast[];
|
||||
showToast: (toast: Omit<Toast, 'id'>) => string;
|
||||
removeToast: (id: string) => void;
|
||||
success: (message: string, title?: string) => string;
|
||||
error: (message: string, title?: string) => string;
|
||||
info: (message: string, title?: string) => string;
|
||||
};
|
||||
|
||||
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
|
||||
const showToast = useCallback(
|
||||
({ type, title, message, duration = 4000 }: Omit<Toast, 'id'>) => {
|
||||
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
|
||||
const newToast: Toast = { id, type, title, message, duration };
|
||||
|
||||
setToasts((prev) => [...prev, newToast]);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
removeToast(id);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
return id;
|
||||
},
|
||||
[removeToast],
|
||||
);
|
||||
|
||||
const success = useCallback(
|
||||
(message: string, title?: string) => showToast({ type: 'success', title, message }),
|
||||
[showToast],
|
||||
);
|
||||
|
||||
const error = useCallback(
|
||||
(message: string, title?: string) => showToast({ type: 'error', title, message }),
|
||||
[showToast],
|
||||
);
|
||||
|
||||
const info = useCallback(
|
||||
(message: string, title?: string) => showToast({ type: 'info', title, message }),
|
||||
[showToast],
|
||||
);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
toasts,
|
||||
showToast,
|
||||
removeToast,
|
||||
success,
|
||||
error,
|
||||
info,
|
||||
}),
|
||||
[toasts, showToast, removeToast, success, error, info],
|
||||
);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={value}>
|
||||
{children}
|
||||
{/* Toast Container */}
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="fixed bottom-4 right-4 z-50 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
|
||||
>
|
||||
{toasts.map((toast) => (
|
||||
<div
|
||||
key={toast.id}
|
||||
role="alert"
|
||||
className={cn(
|
||||
'pointer-events-auto flex items-start gap-3 rounded-xl border p-4 shadow-lg backdrop-blur-sm transition-all animate-fade-in bg-surface',
|
||||
toast.type === 'success' && 'border-success/30 text-primary',
|
||||
toast.type === 'error' && 'border-danger/30 text-primary',
|
||||
toast.type === 'info' && 'border-border text-primary',
|
||||
)}
|
||||
>
|
||||
<div className="shrink-0 mt-0.5">
|
||||
{toast.type === 'success' && (
|
||||
<CheckCircle2 className="size-5 text-success" />
|
||||
)}
|
||||
{toast.type === 'error' && (
|
||||
<AlertCircle className="size-5 text-danger" />
|
||||
)}
|
||||
{toast.type === 'info' && (
|
||||
<Info className="size-5 text-accent" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
{toast.title ? (
|
||||
<p className="font-semibold text-sm text-primary">{toast.title}</p>
|
||||
) : null}
|
||||
<p className="text-sm text-foreground/80 leading-relaxed break-words">
|
||||
{toast.message}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeToast(toast.id)}
|
||||
className="shrink-0 -mr-1 -mt-1 p-1 rounded-lg text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
|
||||
aria-label="Cerrar notificación"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useToast debe utilizarse dentro de un <ToastProvider>');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -1,9 +1,18 @@
|
||||
import type {
|
||||
AttendeeDto,
|
||||
AttendeeList,
|
||||
BulkCreateAttendees,
|
||||
BulkCreateAttendeesResult,
|
||||
ConnectPayment,
|
||||
ConnectPaymentResult,
|
||||
CreateAttendee,
|
||||
CreateFirstGroup,
|
||||
CreateFirstGroupResult,
|
||||
GroupDto,
|
||||
GroupInviteInfoDto,
|
||||
GroupList,
|
||||
InviteTokenResult,
|
||||
JoinGroupViaInvite,
|
||||
OnboardingStatusDto,
|
||||
ProblemDetails,
|
||||
} from '@gruperly/shared'
|
||||
@@ -15,7 +24,7 @@ export class ApiError extends Error {
|
||||
readonly status: number,
|
||||
readonly problem: ProblemDetails | null,
|
||||
) {
|
||||
super(problem?.title ?? `Error ${status}`)
|
||||
super(problem?.detail ?? problem?.title ?? `Error ${status}`)
|
||||
this.name = 'ApiError'
|
||||
}
|
||||
}
|
||||
@@ -62,4 +71,38 @@ export const createFirstGroup = (payload: CreateFirstGroup) =>
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const getGroups = () => apiFetch<GroupList>('/api/v1/groups')
|
||||
export const getGroups = () => apiFetch<GroupList>('/api/v1/groups')
|
||||
|
||||
export const getGroup = (groupId: string) =>
|
||||
apiFetch<GroupDto>(`/api/v1/groups/${groupId}`)
|
||||
|
||||
export const getInviteToken = (groupId: string, regenerate = false) =>
|
||||
regenerate
|
||||
? apiFetch<InviteTokenResult>(`/api/v1/groups/${groupId}/invite-token?regenerate=true`, {
|
||||
method: 'POST',
|
||||
})
|
||||
: apiFetch<InviteTokenResult>(`/api/v1/groups/${groupId}/invite-token`)
|
||||
|
||||
export const getInviteInfo = (token: string) =>
|
||||
apiFetch<GroupInviteInfoDto>(`/api/v1/invitations/${token}`)
|
||||
|
||||
export const joinViaInvite = (token: string, payload: JoinGroupViaInvite) =>
|
||||
apiFetch<{ attendee: AttendeeDto; message: string }>(`/api/v1/invitations/${token}/join`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const createAttendee = (groupId: string, payload: CreateAttendee) =>
|
||||
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const bulkCreateAttendees = (groupId: string, payload: BulkCreateAttendees) =>
|
||||
apiFetch<BulkCreateAttendeesResult>(`/api/v1/groups/${groupId}/attendees/bulk`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) =>
|
||||
apiFetch<AttendeeList>(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`)
|
||||
314
apps/web/src/lib/file-parser.ts
Normal file
314
apps/web/src/lib/file-parser.ts
Normal file
@@ -0,0 +1,314 @@
|
||||
export type ParsedContactRow = {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
notes: string;
|
||||
isValid: boolean;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
const hasPlus = trimmed.startsWith('+');
|
||||
const digitsOnly = trimmed.replace(/\D/g, '');
|
||||
return hasPlus ? `+${digitsOnly}` : digitsOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea texto CSV con soporte para:
|
||||
* - Delimitadores automáticos (coma, punto y coma, tabulador)
|
||||
* - Comillas y comillas escapadas ("")
|
||||
* - UTF-8 BOM
|
||||
* - Saltos de línea CRLF o LF
|
||||
*/
|
||||
export function parseCsvContent(content: string): string[][] {
|
||||
const cleanContent = content.replace(/^\uFEFF/, '');
|
||||
const lines = cleanContent.split(/\r\n|\n|\r/).filter((l) => l.trim().length > 0);
|
||||
|
||||
if (lines.length === 0) return [];
|
||||
|
||||
// Detectar delimitador basado en la primera línea
|
||||
const firstLine = lines[0];
|
||||
const commaCount = (firstLine.match(/,/g) || []).length;
|
||||
const semicolonCount = (firstLine.match(/;/g) || []).length;
|
||||
const tabCount = (firstLine.match(/\t/g) || []).length;
|
||||
|
||||
let delimiter = ',';
|
||||
if (semicolonCount > commaCount && semicolonCount >= tabCount) {
|
||||
delimiter = ';';
|
||||
} else if (tabCount > commaCount && tabCount > semicolonCount) {
|
||||
delimiter = '\t';
|
||||
}
|
||||
|
||||
const rows: string[][] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
const row: string[] = [];
|
||||
let insideQuote = false;
|
||||
let currentCell = '';
|
||||
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
|
||||
if (char === '"') {
|
||||
if (insideQuote && line[i + 1] === '"') {
|
||||
currentCell += '"';
|
||||
i++; // Saltear comilla escapada
|
||||
} else {
|
||||
insideQuote = !insideQuote;
|
||||
}
|
||||
} else if (char === delimiter && !insideQuote) {
|
||||
row.push(currentCell.trim());
|
||||
currentCell = '';
|
||||
} else {
|
||||
currentCell += char;
|
||||
}
|
||||
}
|
||||
row.push(currentCell.trim());
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea un archivo XLSX de Excel extrayendo sharedStrings y sheet1.xml
|
||||
* utilizando DecompressionStream nativo del navegador sin dependencias externas.
|
||||
*/
|
||||
export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]> {
|
||||
const view = new DataView(buffer);
|
||||
const entries = new Map<string, Uint8Array>();
|
||||
let offset = 0;
|
||||
|
||||
while (offset < buffer.byteLength - 30) {
|
||||
const sig = view.getUint32(offset, true);
|
||||
if (sig !== 0x04034b50) break;
|
||||
|
||||
const compression = view.getUint16(offset + 8, true);
|
||||
const compressedSize = view.getUint32(offset + 18, true);
|
||||
const fileNameLen = view.getUint16(offset + 26, true);
|
||||
const extraLen = view.getUint16(offset + 28, true);
|
||||
|
||||
const nameBytes = new Uint8Array(buffer, offset + 30, fileNameLen);
|
||||
const fileName = new TextDecoder().decode(nameBytes);
|
||||
|
||||
const dataStart = offset + 30 + fileNameLen + extraLen;
|
||||
|
||||
if (compressedSize > 0 && dataStart + compressedSize <= buffer.byteLength) {
|
||||
const compressedData = new Uint8Array(buffer, dataStart, compressedSize);
|
||||
|
||||
if (compression === 0) {
|
||||
entries.set(fileName, compressedData);
|
||||
} else if (compression === 8 && typeof DecompressionStream !== 'undefined') {
|
||||
try {
|
||||
const stream = new Response(compressedData).body?.pipeThrough(
|
||||
new DecompressionStream('deflate-raw'),
|
||||
);
|
||||
if (stream) {
|
||||
const decompressed = await new Response(stream).arrayBuffer();
|
||||
entries.set(fileName, new Uint8Array(decompressed));
|
||||
}
|
||||
} catch {
|
||||
// Ignorar archivos que no se puedan descomprimir
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
offset = dataStart + compressedSize;
|
||||
}
|
||||
|
||||
// Parsear strings compartidos
|
||||
const sharedStringsData = entries.get('xl/sharedStrings.xml');
|
||||
const sharedStrings: string[] = [];
|
||||
if (sharedStringsData) {
|
||||
const xmlText = new TextDecoder().decode(sharedStringsData);
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(xmlText, 'application/xml');
|
||||
const siNodes = doc.getElementsByTagName('si');
|
||||
for (let i = 0; i < siNodes.length; i++) {
|
||||
const tNodes = siNodes[i].getElementsByTagName('t');
|
||||
let str = '';
|
||||
for (let j = 0; j < tNodes.length; j++) {
|
||||
str += tNodes[j].textContent ?? '';
|
||||
}
|
||||
sharedStrings.push(str);
|
||||
}
|
||||
}
|
||||
|
||||
// Parsear sheet1.xml
|
||||
const sheetData = entries.get('xl/worksheets/sheet1.xml');
|
||||
if (!sheetData) {
|
||||
throw new Error('No se pudo encontrar la hoja de cálculo principal en el archivo Excel.');
|
||||
}
|
||||
|
||||
const sheetXml = new TextDecoder().decode(sheetData);
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(sheetXml, 'application/xml');
|
||||
const rowNodes = doc.getElementsByTagName('row');
|
||||
|
||||
const rows: string[][] = [];
|
||||
for (let i = 0; i < rowNodes.length; i++) {
|
||||
const rowEl = rowNodes[i];
|
||||
const cNodes = rowEl.getElementsByTagName('c');
|
||||
const rowValues: string[] = [];
|
||||
|
||||
for (let j = 0; j < cNodes.length; j++) {
|
||||
const c = cNodes[j];
|
||||
const isString = c.getAttribute('t') === 's';
|
||||
const v = c.getElementsByTagName('v')[0]?.textContent ?? '';
|
||||
|
||||
if (isString) {
|
||||
const index = parseInt(v, 10);
|
||||
rowValues.push(sharedStrings[index] ?? '');
|
||||
} else {
|
||||
rowValues.push(v);
|
||||
}
|
||||
}
|
||||
rows.push(rowValues);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza una matriz 2D en objetos de contactos con detección inteligente de columnas.
|
||||
*/
|
||||
export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] {
|
||||
if (rawRows.length === 0) return [];
|
||||
|
||||
const headerRow = rawRows[0].map((h) => h.toLowerCase().trim());
|
||||
let hasHeader = false;
|
||||
|
||||
let nameCol = -1;
|
||||
let firstNameCol = -1;
|
||||
let lastNameCol = -1;
|
||||
let phoneCol = -1;
|
||||
let emailCol = -1;
|
||||
let notesCol = -1;
|
||||
|
||||
for (let i = 0; i < headerRow.length; i++) {
|
||||
const col = headerRow[i];
|
||||
if (col === 'nombre' || col === 'first name' || col === 'firstname') {
|
||||
firstNameCol = i;
|
||||
hasHeader = true;
|
||||
} else if (col === 'apellido' || col === 'last name' || col === 'lastname') {
|
||||
lastNameCol = i;
|
||||
hasHeader = true;
|
||||
} else if (col === 'nombre completo' || col === 'full name' || col === 'fullname' || col === 'alumno') {
|
||||
nameCol = i;
|
||||
hasHeader = true;
|
||||
} else if (
|
||||
col.includes('tel') ||
|
||||
col.includes('cel') ||
|
||||
col.includes('phone') ||
|
||||
col.includes('whatsapp') ||
|
||||
col.includes('movil') ||
|
||||
col.includes('móvil')
|
||||
) {
|
||||
phoneCol = i;
|
||||
hasHeader = true;
|
||||
} else if (col.includes('email') || col.includes('correo')) {
|
||||
emailCol = i;
|
||||
hasHeader = true;
|
||||
} else if (col.includes('nota') || col.includes('obs')) {
|
||||
notesCol = i;
|
||||
hasHeader = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallbacks posicionales si no se detectaron encabezados explícitos
|
||||
if (!hasHeader) {
|
||||
firstNameCol = 0;
|
||||
lastNameCol = 1;
|
||||
phoneCol = 2;
|
||||
emailCol = 3;
|
||||
} else if (firstNameCol === -1 && nameCol === -1) {
|
||||
firstNameCol = 0;
|
||||
}
|
||||
|
||||
if (phoneCol === -1) {
|
||||
// Buscar la primera columna que parezca un número telefónico
|
||||
for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) {
|
||||
const sample = rawRows[1][c];
|
||||
if (/^[\d\s+\-()]{6,}$/.test(sample)) {
|
||||
phoneCol = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (phoneCol === -1) phoneCol = 1;
|
||||
}
|
||||
|
||||
const dataRows = hasHeader ? rawRows.slice(1) : rawRows;
|
||||
const contacts: ParsedContactRow[] = [];
|
||||
|
||||
for (let idx = 0; idx < dataRows.length; idx++) {
|
||||
const row = dataRows[idx];
|
||||
if (row.every((c) => c.trim().length === 0)) continue;
|
||||
|
||||
let firstName = '';
|
||||
let lastName = '';
|
||||
let fullName = '';
|
||||
|
||||
if (nameCol !== -1 && row[nameCol]) {
|
||||
fullName = row[nameCol].trim();
|
||||
const parts = fullName.split(/\s+/);
|
||||
firstName = parts[0] || '';
|
||||
lastName = parts.slice(1).join(' ') || '';
|
||||
} else {
|
||||
firstName = (firstNameCol !== -1 ? row[firstNameCol] : '') || '';
|
||||
lastName = (lastNameCol !== -1 ? row[lastNameCol] : '') || '';
|
||||
fullName = `${firstName} ${lastName}`.trim();
|
||||
}
|
||||
|
||||
const rawPhone = (phoneCol !== -1 ? row[phoneCol] : '') || '';
|
||||
const phone = normalizePhone(rawPhone);
|
||||
const email = (emailCol !== -1 ? row[emailCol] : '') || '';
|
||||
const notes = (notesCol !== -1 ? row[notesCol] : '') || '';
|
||||
|
||||
const errors: string[] = [];
|
||||
if (!firstName && !fullName) errors.push('Falta el nombre');
|
||||
if (!phone || phone.replace(/\D/g, '').length < 6) {
|
||||
errors.push('Teléfono inválido o faltante');
|
||||
}
|
||||
|
||||
contacts.push({
|
||||
id: `row-${idx}-${Math.random().toString(36).slice(2, 6)}`,
|
||||
firstName: firstName || fullName,
|
||||
lastName,
|
||||
fullName: fullName || firstName,
|
||||
phone,
|
||||
email: email.trim(),
|
||||
notes: notes.trim(),
|
||||
isValid: errors.length === 0,
|
||||
error: errors.join(', '),
|
||||
});
|
||||
}
|
||||
|
||||
return contacts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Descarga una plantilla de ejemplo en formato CSV para la carga masiva.
|
||||
*/
|
||||
export function downloadAttendeeTemplateCsv() {
|
||||
const csvContent =
|
||||
'Nombre,Apellido,Teléfono,Email,Notas\r\n' +
|
||||
'Sofía,Rodríguez,+5491144556677,sofia@ejemplo.com,Nivel intermedio\r\n' +
|
||||
'Lucas,Benítez,+5491155667788,lucas@ejemplo.com,Trae instrumento\r\n' +
|
||||
'Valentina,Morales,+5491166778899,,\r\n';
|
||||
|
||||
const blob = new Blob([new Uint8Array([0xef, 0xbb, 0xbf]), csvContent], {
|
||||
type: 'text/csv;charset=utf-8;',
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.setAttribute('href', url);
|
||||
link.setAttribute('download', 'plantilla_alumnos_gruperly.csv');
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { RouterProvider } from '@tanstack/react-router'
|
||||
import { router } from './router'
|
||||
import { AuthProvider } from './context/AuthProvider'
|
||||
import { ThemeProvider } from './context/ThemeProvider'
|
||||
import { ToastProvider } from './components/ui'
|
||||
import './index.css'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -18,7 +19,9 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ToastProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -11,6 +11,8 @@ import { LoginPage } from './routes/auth/login'
|
||||
import { SignupPage } from './routes/auth/signup'
|
||||
import { VerifyEmailPage } from './routes/auth/verify-email'
|
||||
import { OnboardingView } from './routes/onboarding'
|
||||
import { GroupDetailView } from './routes/group-detail'
|
||||
import { JoinGroupView } from './routes/join-group'
|
||||
|
||||
const rootRoute = createRootRoute({
|
||||
component: () => <Outlet />,
|
||||
@@ -40,6 +42,12 @@ const onboardingRoute = createRoute({
|
||||
component: OnboardingView,
|
||||
})
|
||||
|
||||
const joinGroupRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/join/$token',
|
||||
component: JoinGroupView,
|
||||
})
|
||||
|
||||
// Capa con la navegación de la app autenticada (Sidebar + BottomNav).
|
||||
// El guard redirige a /onboarding a quien no completó el onboarding.
|
||||
const appLayoutRoute = createRoute({
|
||||
@@ -60,6 +68,12 @@ const groupsRoute = createRoute({
|
||||
component: GroupsView,
|
||||
})
|
||||
|
||||
const groupDetailRoute = createRoute({
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
path: '/groups/$groupId',
|
||||
component: GroupDetailView,
|
||||
})
|
||||
|
||||
const paymentsRoute = createRoute({
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
path: '/payments',
|
||||
@@ -95,9 +109,11 @@ const routeTree = rootRoute.addChildren([
|
||||
signupRoute,
|
||||
verifyEmailRoute,
|
||||
onboardingRoute,
|
||||
joinGroupRoute,
|
||||
appLayoutRoute.addChildren([
|
||||
indexRoute,
|
||||
groupsRoute,
|
||||
groupDetailRoute,
|
||||
paymentsRoute,
|
||||
settingsRoute,
|
||||
securityRoute,
|
||||
|
||||
852
apps/web/src/routes/group-detail.tsx
Normal file
852
apps/web/src/routes/group-detail.tsx
Normal file
@@ -0,0 +1,852 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -7,10 +7,11 @@ import { getGroups } from '../lib/api'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format'
|
||||
|
||||
function GroupCard({ group }: { group: GroupDto }) {
|
||||
const navigate = useNavigate()
|
||||
const hasSchedule = (group.days?.length ?? 0) > 0
|
||||
|
||||
return (
|
||||
<article className="rounded-xl border border-border bg-surface p-5">
|
||||
<article className="rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/40">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3>
|
||||
@@ -41,6 +42,16 @@ function GroupCard({ group }: { group: GroupDto }) {
|
||||
) : (
|
||||
<p className="mt-4 text-sm text-foreground/50">Aún sin plan de cobro configurado.</p>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex items-center justify-end gap-2 border-t border-border pt-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void navigate({ to: `/groups/${group.id}` })}
|
||||
>
|
||||
Gestionar Miembros
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
309
apps/web/src/routes/join-group.tsx
Normal file
309
apps/web/src/routes/join-group.tsx
Normal file
@@ -0,0 +1,309 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation } from '@tanstack/react-query';
|
||||
import { useParams, Link } from '@tanstack/react-router';
|
||||
import {
|
||||
CalendarClock,
|
||||
CheckCircle2,
|
||||
GraduationCap,
|
||||
Loader2,
|
||||
Moon,
|
||||
Sun,
|
||||
Users,
|
||||
} from 'lucide-react';
|
||||
import { Badge, Button, Input, Label } from '../components/ui';
|
||||
import { Logo } from '../components/brand';
|
||||
import { useTheme } from '../context/ThemeProvider';
|
||||
import { getInviteInfo, joinViaInvite, ApiError } from '../lib/api';
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format';
|
||||
|
||||
export function JoinGroupView() {
|
||||
const { token } = useParams({ strict: false }) as { token: string };
|
||||
const { theme, setTheme, isDark } = useTheme();
|
||||
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
// Success state
|
||||
const [registeredAttendee, setRegisteredAttendee] = useState<{
|
||||
fullName: string;
|
||||
phone: string | null;
|
||||
} | null>(null);
|
||||
|
||||
const inviteQuery = useQuery({
|
||||
queryKey: ['public-invite', token],
|
||||
queryFn: () => getInviteInfo(token),
|
||||
enabled: Boolean(token),
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const joinMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
joinViaInvite(token, {
|
||||
firstName: firstName.trim(),
|
||||
lastName: lastName.trim(),
|
||||
phone: phone.trim(),
|
||||
email: email.trim() || undefined,
|
||||
}),
|
||||
onSuccess: (data) => {
|
||||
setErrorMessage(null);
|
||||
setRegisteredAttendee({
|
||||
fullName: data.attendee.fullName,
|
||||
phone: data.attendee.phone,
|
||||
});
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.problem?.code === 'attendee_already_registered') {
|
||||
setErrorMessage(
|
||||
'Ya te encuentras registrado en este grupo con ese número de teléfono. El profesor ya tiene tus datos.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setErrorMessage(error.message || 'Error al procesar la inscripción.');
|
||||
} else if (error instanceof Error) {
|
||||
setErrorMessage(error.message);
|
||||
} else {
|
||||
setErrorMessage('Ocurrió un error inesperado. Por favor, intenta de nuevo.');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setErrorMessage(null);
|
||||
|
||||
if (!firstName.trim() || !lastName.trim() || !phone.trim()) {
|
||||
setErrorMessage('Por favor completa los campos requeridos (Nombre, Apellido y Teléfono).');
|
||||
return;
|
||||
}
|
||||
|
||||
joinMutation.mutate();
|
||||
};
|
||||
|
||||
const group = inviteQuery.data;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-primary flex flex-col justify-between selection:bg-accent selection:text-white">
|
||||
{/* Public Header */}
|
||||
<header className="border-b border-border bg-surface/80 backdrop-blur-md sticky top-0 z-10 px-4 py-3 sm:px-8 flex items-center justify-between">
|
||||
<Link to="/" className="flex items-center gap-2">
|
||||
<Logo className="h-7 w-auto" />
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTheme(isDark ? 'light' : 'dark')}
|
||||
className="p-2 rounded-xl text-foreground/70 hover:text-primary hover:bg-primary-soft transition-colors"
|
||||
title={isDark ? 'Cambiar a tema claro' : 'Cambiar a tema oscuro'}
|
||||
>
|
||||
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 flex items-center justify-center p-4 sm:p-6 md:p-10">
|
||||
<div className="w-full max-w-lg space-y-6">
|
||||
{inviteQuery.isPending ? (
|
||||
<div className="flex flex-col items-center justify-center py-20 gap-3">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
<p className="text-sm text-foreground/60">Cargando información del grupo...</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{inviteQuery.isError || !group ? (
|
||||
<div className="rounded-2xl border border-danger/20 bg-danger-soft p-6 sm:p-8 text-center space-y-3">
|
||||
<h2 className="text-xl font-bold text-danger">Enlace no válido o expirado</h2>
|
||||
<p className="text-sm text-foreground/70 max-w-sm mx-auto">
|
||||
No pudimos encontrar este grupo. Por favor consulta con tu profesor para solicitar un nuevo enlace de invitación.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Registration Success Confirmation */}
|
||||
{registeredAttendee && group ? (
|
||||
<div className="rounded-2xl border border-success/30 bg-surface p-6 sm:p-8 text-center shadow-xl space-y-5 animate-step-enter">
|
||||
<div className="size-16 rounded-full bg-success-soft text-success flex items-center justify-center mx-auto">
|
||||
<CheckCircle2 className="size-10" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Badge variant="success" className="mb-2">
|
||||
Registro Confirmado
|
||||
</Badge>
|
||||
<h1 className="text-2xl font-bold text-primary">¡Inscripción Exitosa!</h1>
|
||||
<p className="mt-2 text-sm text-foreground/70 leading-relaxed">
|
||||
Tus datos han sido registrados con éxito en el grupo{' '}
|
||||
<strong className="text-primary font-semibold">{group.name}</strong>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-border bg-primary-soft/50 p-4 text-left text-xs space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Profesor:</span>
|
||||
<span className="font-semibold text-primary">{group.teacherName}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Alumno:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.fullName}</span>
|
||||
</div>
|
||||
{registeredAttendee.phone ? (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Teléfono registrado:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.phone}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-foreground/60">
|
||||
El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y coordinar los detalles de la clase.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Inscription Form */}
|
||||
{!registeredAttendee && group ? (
|
||||
<div className="rounded-2xl border border-border bg-surface p-6 sm:p-8 shadow-xl space-y-6">
|
||||
{/* Group Info Header */}
|
||||
<div className="border-b border-border pb-5">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge variant="neutral" className="gap-1 text-[11px]">
|
||||
<GraduationCap className="size-3.5 text-accent" />
|
||||
<span>Invitación Oficial</span>
|
||||
</Badge>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-primary">{group.name}</h1>
|
||||
<p className="mt-1 text-sm font-medium text-foreground/80">
|
||||
Profesor: <span className="text-primary font-semibold">{group.teacherName}</span>
|
||||
</p>
|
||||
{group.description ? (
|
||||
<p className="mt-2 text-sm text-foreground/60">{group.description}</p>
|
||||
) : null}
|
||||
|
||||
{/* Schedule & Price Details */}
|
||||
<div className="mt-4 flex flex-wrap gap-2 text-xs">
|
||||
{(group.days?.length ?? 0) > 0 ? (
|
||||
<div className="inline-flex items-center gap-1.5 rounded-lg bg-primary-soft px-2.5 py-1 text-foreground/80">
|
||||
<CalendarClock className="size-3.5 text-accent" />
|
||||
<span>{formatSchedule(group.days ?? [], group.time)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{group.price != null ? (
|
||||
<div className="inline-flex items-center gap-1.5 rounded-lg bg-primary-soft px-2.5 py-1 text-foreground/80 font-medium">
|
||||
<span>{formatPrice(group.price)}</span>
|
||||
{group.billingType ? <span>· {BILLING_LABELS[group.billingType]}</span> : ''}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{group.capacity ? (
|
||||
<div className="inline-flex items-center gap-1.5 rounded-lg bg-primary-soft px-2.5 py-1 text-foreground/80">
|
||||
<Users className="size-3.5 text-accent" />
|
||||
<span>Cupo {group.capacity}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form Header */}
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-primary">Completa tus datos</h2>
|
||||
<p className="text-xs text-foreground/60 mt-0.5">
|
||||
Ingresa tus datos para registrarte en la lista de alumnos de este grupo.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Error banner */}
|
||||
{errorMessage ? (
|
||||
<div className="rounded-xl border border-danger/30 bg-danger-soft p-3 text-xs text-danger font-medium animate-fade-in">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="student-first-name" className="mb-1 block text-xs">
|
||||
Nombre <span className="text-danger">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="student-first-name"
|
||||
placeholder="Ej. Sofía"
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="student-last-name" className="mb-1 block text-xs">
|
||||
Apellido <span className="text-danger">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="student-last-name"
|
||||
placeholder="Ej. Fernández"
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="student-phone" className="mb-1 block text-xs">
|
||||
Teléfono / WhatsApp <span className="text-danger">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="student-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">
|
||||
El profesor se comunicará contigo por WhatsApp a este número.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="student-email" className="mb-1 block text-xs">
|
||||
Email (opcional)
|
||||
</Label>
|
||||
<Input
|
||||
id="student-email"
|
||||
type="email"
|
||||
placeholder="alumno@ejemplo.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={joinMutation.isPending}
|
||||
className="w-full py-2.5 text-sm font-semibold gap-2"
|
||||
>
|
||||
{joinMutation.isPending ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : null}
|
||||
<span>Completar Inscripción</span>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="border-t border-border py-4 px-4 text-center text-xs text-foreground/40">
|
||||
Gruperly — Gestión sencilla de cobros y grupos
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user