New page for Add group member
This commit is contained in:
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||
import { BulkImportPanel } from './BulkImportPanel'
|
||||
import { CapacityModal } from './CapacityModal'
|
||||
import { QuickAddForm } from './QuickAddForm'
|
||||
|
||||
const TABS = [
|
||||
{ value: 'quick' as const, label: 'Carga Rápida (Individual)' },
|
||||
{ value: 'bulk' as const, label: 'Carga Masiva (CSV / Excel)' },
|
||||
]
|
||||
|
||||
export function AddAttendeePage() {
|
||||
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
||||
useAddAttendee()
|
||||
|
||||
if (groupPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-2xl animate-fade-in space-y-5">
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span>Volver al grupo</span>
|
||||
</Link>
|
||||
|
||||
<header className="space-y-1">
|
||||
<h1 className="text-2xl font-bold text-primary">Agregar miembros</h1>
|
||||
<p className="text-sm text-foreground/60">
|
||||
{groupName ? (
|
||||
<>
|
||||
Sumá miembros a <span className="font-medium text-primary">{groupName}</span> de forma
|
||||
individual o masiva desde una lista.
|
||||
</>
|
||||
) : (
|
||||
'Sumá miembros de forma individual o masiva desde una lista.'
|
||||
)}
|
||||
</p>
|
||||
{capacity != null ? (
|
||||
<p className="text-xs text-foreground/50">
|
||||
{attendeesTotal} de {capacity} lugares ocupados.
|
||||
</p>
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
|
||||
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
||||
{TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.value}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.value)}
|
||||
className={cn(
|
||||
'flex-1 rounded-lg px-1 py-2 text-xs font-semibold transition-all',
|
||||
activeTab === tab.value
|
||||
? 'bg-surface text-primary shadow-xs'
|
||||
: 'text-foreground/60 hover:text-primary',
|
||||
)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
||||
</div>
|
||||
|
||||
<CapacityModal />
|
||||
<BulkCapacityModal />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
import { createContext, useContext, useMemo, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type {
|
||||
CreateAttendee,
|
||||
CreateAttendeeResult,
|
||||
CreateGroupWaitlistEntry,
|
||||
GroupWaitlistEntryDto,
|
||||
GroupWaitlistList,
|
||||
} from '@gruperly/shared'
|
||||
import { useToast } from '../../../components/ui'
|
||||
import {
|
||||
addToGroupWaitlist,
|
||||
ApiError,
|
||||
bulkCreateAttendees,
|
||||
createAttendee,
|
||||
getGroup,
|
||||
getGroupAttendees,
|
||||
} from '../../../lib/api'
|
||||
import type { ParsedContactRow } from '../../../lib/file-parser'
|
||||
|
||||
export type BulkAttendeeRow = {
|
||||
firstName: string
|
||||
lastName: string
|
||||
fullName: string
|
||||
phone: string
|
||||
email?: string
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export type AddAttendeeTab = 'quick' | 'bulk'
|
||||
|
||||
type AddAttendeeContextValue = {
|
||||
groupId: string
|
||||
groupName: string | undefined
|
||||
groupPending: boolean
|
||||
attendeesTotal: number
|
||||
capacity: number | null
|
||||
activeTab: AddAttendeeTab
|
||||
setActiveTab: (value: AddAttendeeTab) => void
|
||||
cancelAddAttendee: () => void
|
||||
isCapacityModalOpen: boolean
|
||||
capacityPayload: CreateAttendee | null
|
||||
closeCapacityModal: () => void
|
||||
isBulkCapacityModalOpen: boolean
|
||||
closeBulkCapacityModal: () => void
|
||||
parsedContacts: ParsedContactRow[]
|
||||
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
||||
removeParsedContact: (id: string) => void
|
||||
fileName: string | null
|
||||
setFileName: (name: string | null) => void
|
||||
isParsingFile: boolean
|
||||
setIsParsingFile: (value: boolean) => void
|
||||
isDragging: boolean
|
||||
setIsDragging: (value: boolean) => void
|
||||
validRowsCount: number
|
||||
invalidRowsCount: number
|
||||
isSubmittingAttendee: boolean
|
||||
isSubmittingForcedAttendee: boolean
|
||||
isSubmittingWaitlistEntry: boolean
|
||||
isSubmittingBulkImport: boolean
|
||||
submitQuickAttendee: (payload: CreateAttendee) => void
|
||||
submitForcedAttendee: () => void
|
||||
submitWaitlistEntry: () => void
|
||||
requestBulkImport: () => void
|
||||
confirmBulkImportOverCapacity: () => void
|
||||
}
|
||||
|
||||
const AddAttendeeContext = createContext<AddAttendeeContextValue | null>(null)
|
||||
|
||||
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
||||
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
||||
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
||||
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
||||
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
||||
const [fileName, setFileName] = useState<string | null>(null)
|
||||
const [isParsingFile, setIsParsingFile] = useState(false)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
|
||||
// así que la página se monta sin spinner ni fetch duplicado.
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ['group', groupId],
|
||||
queryFn: () => getGroup(groupId),
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const attendeesQuery = useQuery({
|
||||
queryKey: ['group-attendees', groupId],
|
||||
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const group = groupQuery.data
|
||||
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? 0
|
||||
const capacity = group?.capacity ?? null
|
||||
|
||||
const goBackToGroup = () => {
|
||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||
}
|
||||
|
||||
const closeCapacityFlow = () => {
|
||||
setPendingCapacityPayload(null)
|
||||
setIsCapacityModalOpen(false)
|
||||
}
|
||||
|
||||
const invalidateGroupQueries = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||
}
|
||||
|
||||
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
||||
if (result.outcome === 'created') {
|
||||
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
||||
} else {
|
||||
toast.info(result.message)
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
goBackToGroup()
|
||||
}
|
||||
|
||||
const createAttendeeMutation = useMutation({
|
||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
||||
onMutate: (payload) => setPendingCapacityPayload(payload),
|
||||
onSuccess: handleCreateSuccess,
|
||||
onError: (err: Error) => {
|
||||
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
||||
setIsCapacityModalOpen(true)
|
||||
return
|
||||
}
|
||||
toast.error(err.message || 'Error al agregar miembro.')
|
||||
},
|
||||
})
|
||||
|
||||
const createAttendeeForceMutation = useMutation({
|
||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
||||
onSuccess: handleCreateSuccess,
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || 'Error al agregar miembro.')
|
||||
},
|
||||
})
|
||||
|
||||
const addToWaitlistMutation = useMutation({
|
||||
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
||||
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
||||
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
||||
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
||||
|
||||
if (previousWaitlist) {
|
||||
const optimisticEntry: GroupWaitlistEntryDto = {
|
||||
id: `temp-${Date.now()}`,
|
||||
groupId,
|
||||
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
||||
phone: payload.phone,
|
||||
email: payload.email || null,
|
||||
notes: payload.notes ?? null,
|
||||
status: 'PENDING',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
||||
data: [optimisticEntry, ...previousWaitlist.data],
|
||||
pagination: {
|
||||
...previousWaitlist.pagination,
|
||||
total: previousWaitlist.pagination.total + 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return { previousWaitlist }
|
||||
},
|
||||
onSuccess: (entry) => {
|
||||
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
||||
invalidateGroupQueries()
|
||||
goBackToGroup()
|
||||
},
|
||||
onError: (err: Error, _payload, context) => {
|
||||
if (context?.previousWaitlist) {
|
||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
||||
}
|
||||
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
||||
toast.info('Este número ya está en la lista de espera del grupo.')
|
||||
} else {
|
||||
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
||||
}
|
||||
closeCapacityFlow()
|
||||
},
|
||||
})
|
||||
|
||||
const bulkImportMutation = useMutation({
|
||||
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
||||
onSuccess: (res) => {
|
||||
toast.success(res.message)
|
||||
setParsedContacts([])
|
||||
setFileName(null)
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
goBackToGroup()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || 'Error al importar miembros.')
|
||||
},
|
||||
})
|
||||
|
||||
const validRows: BulkAttendeeRow[] = useMemo(
|
||||
() =>
|
||||
parsedContacts
|
||||
.filter((contact) => contact.isValid)
|
||||
.map((contact) => ({
|
||||
firstName: contact.firstName,
|
||||
lastName: contact.lastName,
|
||||
fullName: contact.fullName,
|
||||
phone: contact.phone,
|
||||
email: contact.email || undefined,
|
||||
notes: contact.notes || undefined,
|
||||
})),
|
||||
[parsedContacts],
|
||||
)
|
||||
|
||||
const runBulkImport = () => {
|
||||
if (validRows.length === 0) {
|
||||
toast.error('No hay miembros válidos para importar.')
|
||||
return
|
||||
}
|
||||
bulkImportMutation.mutate(validRows)
|
||||
}
|
||||
|
||||
const requestBulkImport = () => {
|
||||
if (validRows.length === 0) {
|
||||
toast.error('No hay miembros válidos para importar.')
|
||||
return
|
||||
}
|
||||
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
||||
setIsBulkCapacityModalOpen(true)
|
||||
return
|
||||
}
|
||||
runBulkImport()
|
||||
}
|
||||
|
||||
const value: AddAttendeeContextValue = {
|
||||
groupId,
|
||||
groupName: group?.name,
|
||||
groupPending: groupQuery.isPending,
|
||||
attendeesTotal,
|
||||
capacity,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
cancelAddAttendee: goBackToGroup,
|
||||
isCapacityModalOpen,
|
||||
capacityPayload: pendingCapacityPayload,
|
||||
closeCapacityModal: closeCapacityFlow,
|
||||
isBulkCapacityModalOpen,
|
||||
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
||||
parsedContacts,
|
||||
setParsedContacts,
|
||||
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
||||
fileName,
|
||||
setFileName,
|
||||
isParsingFile,
|
||||
setIsParsingFile,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
validRowsCount: validRows.length,
|
||||
invalidRowsCount: parsedContacts.length - validRows.length,
|
||||
isSubmittingAttendee: createAttendeeMutation.isPending,
|
||||
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
||||
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
||||
isSubmittingBulkImport: bulkImportMutation.isPending,
|
||||
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
||||
submitForcedAttendee: () => {
|
||||
if (pendingCapacityPayload) {
|
||||
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
||||
}
|
||||
},
|
||||
submitWaitlistEntry: () => {
|
||||
if (pendingCapacityPayload) {
|
||||
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
||||
}
|
||||
},
|
||||
requestBulkImport,
|
||||
confirmBulkImportOverCapacity: () => {
|
||||
setIsBulkCapacityModalOpen(false)
|
||||
runBulkImport()
|
||||
},
|
||||
}
|
||||
|
||||
return <AddAttendeeContext.Provider value={value}>{children}</AddAttendeeContext.Provider>
|
||||
}
|
||||
|
||||
export function useAddAttendee() {
|
||||
const context = useContext(AddAttendeeContext)
|
||||
if (!context) {
|
||||
throw new Error('useAddAttendee debe usarse dentro de <AddAttendeeProvider>')
|
||||
}
|
||||
return context
|
||||
}
|
||||
46
apps/web/src/features/groups/add/BulkCapacityModal.tsx
Normal file
46
apps/web/src/features/groups/add/BulkCapacityModal.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
|
||||
export function BulkCapacityModal() {
|
||||
const {
|
||||
isBulkCapacityModalOpen,
|
||||
closeBulkCapacityModal,
|
||||
confirmBulkImportOverCapacity,
|
||||
validRowsCount,
|
||||
attendeesTotal,
|
||||
groupName,
|
||||
capacity,
|
||||
} = useAddAttendee()
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isBulkCapacityModalOpen}
|
||||
onClose={closeBulkCapacityModal}
|
||||
title="Aviso de cupo"
|
||||
description="La carga supera el cupo del grupo."
|
||||
maxWidth="md"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-foreground/70">
|
||||
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
||||
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
||||
de <strong className="text-primary">{capacity}</strong>. ¿Deseas importarlos de todos modos?
|
||||
</p>
|
||||
<div className="flex flex-col-reverse gap-2.5 pt-2 sm:flex-row sm:items-center sm:justify-end">
|
||||
<Button variant="ghost" onClick={closeBulkCapacityModal} className="w-full sm:w-auto">
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={confirmBulkImportOverCapacity}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Check className="size-4" />
|
||||
Importar de todos modos
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
228
apps/web/src/features/groups/add/BulkImportPanel.tsx
Normal file
228
apps/web/src/features/groups/add/BulkImportPanel.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import { useRef } from 'react'
|
||||
import { Check, Download, FileSpreadsheet, Loader2, Trash2, UploadCloud } from 'lucide-react'
|
||||
import { Badge, Button, useToast } from '../../../components/ui'
|
||||
import {
|
||||
downloadAttendeeTemplateCsv,
|
||||
normalizeRowsToContacts,
|
||||
parseCsvContent,
|
||||
parseXlsxContent,
|
||||
} from '../../../lib/file-parser'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
|
||||
export function BulkImportPanel() {
|
||||
const {
|
||||
parsedContacts,
|
||||
setParsedContacts,
|
||||
removeParsedContact,
|
||||
fileName,
|
||||
setFileName,
|
||||
isParsingFile,
|
||||
setIsParsingFile,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
validRowsCount,
|
||||
invalidRowsCount,
|
||||
isSubmittingBulkImport,
|
||||
cancelAddAttendee,
|
||||
requestBulkImport,
|
||||
} = useAddAttendee()
|
||||
const toast = useToast()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const processFile = async (file: File) => {
|
||||
const fileExtension = file.name.split('.').pop()?.toLowerCase()
|
||||
if (!['csv', 'xlsx', 'xls', 'txt'].includes(fileExtension ?? '')) {
|
||||
toast.error('Formato no compatible. Sube un archivo .csv o .xlsx')
|
||||
return
|
||||
}
|
||||
|
||||
setIsParsingFile(true)
|
||||
setFileName(file.name)
|
||||
try {
|
||||
const rawRows =
|
||||
fileExtension === 'xlsx' || fileExtension === 'xls'
|
||||
? await parseXlsxContent(await file.arrayBuffer())
|
||||
: parseCsvContent(await file.text())
|
||||
|
||||
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)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) {
|
||||
void processFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
void processFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={handleFileDrop}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'relative flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 transition-all',
|
||||
isDragging
|
||||
? 'border-accent bg-accent/5'
|
||||
: 'border-border bg-primary-soft/30 hover:border-accent/60',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".csv,.xlsx,.xls,.txt"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<UploadCloud className="mb-2 size-10 text-accent" />
|
||||
<p className="text-sm font-semibold text-primary">
|
||||
Arrastra tu archivo aquí o haz clic para seleccionarlo
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-foreground/60">Formatos soportados: CSV (.csv) o Excel (.xlsx)</p>
|
||||
|
||||
{fileName ? (
|
||||
<div className="mt-3 flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-1.5 text-xs font-medium text-primary">
|
||||
<FileSpreadsheet className="size-4 text-accent" />
|
||||
<span>{fileName}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-start gap-1 px-1 text-xs sm:flex-row sm:items-center sm:justify-between">
|
||||
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={downloadAttendeeTemplateCsv}
|
||||
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-accent transition-colors hover:text-accent-strong"
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
<span>Descargar plantilla CSV</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isParsingFile ? (
|
||||
<div className="flex items-center justify-center gap-2 py-6 text-sm text-foreground/60">
|
||||
<Loader2 className="size-4 animate-spin text-accent" />
|
||||
<span>Leyendo y analizando archivo...</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{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="h-7 px-2 text-xs text-foreground/50 hover:text-danger"
|
||||
>
|
||||
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 border-b border-border bg-surface font-semibold text-foreground/70">
|
||||
<tr>
|
||||
<th className="px-3 py-2">Nombre</th>
|
||||
<th className="px-3 py-2">Teléfono</th>
|
||||
<th className="px-3 py-2">Email</th>
|
||||
<th className="px-3 py-2">Estado</th>
|
||||
<th className="px-2 py-2 text-right" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{parsedContacts.map((contact) => (
|
||||
<tr
|
||||
key={contact.id}
|
||||
className={!contact.isValid ? 'bg-danger-soft/30' : 'hover:bg-primary-soft/30'}
|
||||
>
|
||||
<td className="px-3 py-2 font-medium text-primary">
|
||||
{contact.fullName || <span className="italic text-danger">Sin nombre</span>}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-foreground/80">
|
||||
{contact.phone || <span className="italic text-danger">Sin teléfono</span>}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-foreground/60">{contact.email || '—'}</td>
|
||||
<td className="px-3 py-2">
|
||||
{contact.isValid ? (
|
||||
<Badge variant="success" className="py-0 text-[10px]">
|
||||
Válido
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="danger" className="py-0 text-[10px]" title={contact.error}>
|
||||
{contact.error}
|
||||
</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-2 py-2 text-right">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeParsedContact(contact.id)}
|
||||
className="rounded p-1 text-foreground/40 transition-colors hover:text-danger"
|
||||
title="Eliminar fila"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||
<Button variant="ghost" onClick={cancelAddAttendee} className="w-full sm:w-auto">
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={requestBulkImport}
|
||||
disabled={isSubmittingBulkImport || validRowsCount === 0}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||
<span>Confirmar e Importar ({validRowsCount})</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
72
apps/web/src/features/groups/add/CapacityModal.tsx
Normal file
72
apps/web/src/features/groups/add/CapacityModal.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
|
||||
export function CapacityModal() {
|
||||
const {
|
||||
isCapacityModalOpen,
|
||||
closeCapacityModal,
|
||||
capacityPayload,
|
||||
groupName,
|
||||
capacity,
|
||||
submitForcedAttendee,
|
||||
submitWaitlistEntry,
|
||||
isSubmittingForcedAttendee,
|
||||
isSubmittingWaitlistEntry,
|
||||
} = useAddAttendee()
|
||||
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isCapacityModalOpen}
|
||||
onClose={closeCapacityModal}
|
||||
title="Cupo alcanzado"
|
||||
description="El grupo llegó a su cupo máximo de miembros."
|
||||
maxWidth="md"
|
||||
>
|
||||
{capacityPayload ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-foreground/70">
|
||||
El grupo <strong className="text-primary">{groupName}</strong> ya alcanzó su cupo de{' '}
|
||||
<strong className="text-primary">{capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
||||
<strong className="text-primary">
|
||||
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
||||
</strong>
|
||||
?
|
||||
</p>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={submitForcedAttendee}
|
||||
disabled={isBusy}
|
||||
className="w-full"
|
||||
>
|
||||
{isSubmittingForcedAttendee ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<UserPlus className="size-4" />
|
||||
)}
|
||||
<span>Agregar de todos modos</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={submitWaitlistEntry}
|
||||
disabled={isBusy}
|
||||
className="w-full"
|
||||
>
|
||||
{isSubmittingWaitlistEntry ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Clock className="size-4" />
|
||||
)}
|
||||
<span>Sumar a la lista de espera</span>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-center text-[11px] text-foreground/50">
|
||||
Si eliges agregarlo de todos modos, el grupo quedará por encima de su cupo.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
129
apps/web/src/features/groups/add/QuickAddForm.tsx
Normal file
129
apps/web/src/features/groups/add/QuickAddForm.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import { useState } from 'react'
|
||||
import { Check, Loader2 } from 'lucide-react'
|
||||
import { Button, Input, Label, useToast } from '../../../components/ui'
|
||||
import { useAddAttendee } from './AddAttendeeProvider'
|
||||
|
||||
export function QuickAddForm() {
|
||||
const { submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
||||
const toast = useToast()
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [notes, setNotes] = useState('')
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!firstName.trim() || !phone.trim()) {
|
||||
toast.error('Nombre y teléfono son obligatorios.')
|
||||
return
|
||||
}
|
||||
submitQuickAttendee({
|
||||
firstName: firstName.trim(),
|
||||
lastName: lastName.trim(),
|
||||
phone: phone.trim(),
|
||||
email: email.trim() || undefined,
|
||||
notes: notes.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const resetForm = () => {
|
||||
setFirstName('')
|
||||
setLastName('')
|
||||
setPhone('')
|
||||
setEmail('')
|
||||
setNotes('')
|
||||
}
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<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 flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
resetForm()
|
||||
cancelAddAttendee()
|
||||
}}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
type="submit"
|
||||
disabled={isSubmittingAttendee}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||
<span>Guardar Miembro</span>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user