refactor: remove unused attendee detail components and provider

This commit is contained in:
Jose Selesan
2026-09-30 13:37:42 -03:00
parent 27bff32e76
commit 4e86096653
30 changed files with 1710 additions and 475 deletions

View File

@@ -0,0 +1,91 @@
import { useId, useState } from 'react'
import { Check, ChevronDown, Copy, MessageCircle } from 'lucide-react'
import { cn } from '../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ACTION_BUTTON_CLASS } from './actionButton'
import { SECTION_TITLE_CLASS, Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard'
export function AbsenceLinkSection() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
const [isOpen, setIsOpen] = useState(false)
const panelId = useId()
const token = attendee?.notifyToken
const url = token ? `${window.location.origin}/report-absence/${token}` : null
if (!attendee || !url) return null
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
const shareUrl = phoneDigits
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
)}`
: null
return (
<Section
title={
<button
type="button"
onClick={() => setIsOpen((value) => !value)}
aria-expanded={isOpen}
aria-controls={panelId}
className={cn(
SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center gap-1.5 text-left',
)}
>
Link de ausencias
<ChevronDown
className={cn('size-4 transition-transform', isOpen && 'rotate-180')}
aria-hidden="true"
/>
</button>
}
>
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y
el texto de "Link copiado" no se pierde al plegar y desplegar. */}
<div id={panelId} hidden={!isOpen}>
<div className="pt-1">
<p className="text-sm text-foreground">
Mandales este link para que avisen cuando no puedan venir.
</p>
<div className="mt-2.5 flex flex-col gap-2 sm:flex-row">
<button
type="button"
onClick={() => copy(url)}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<Copy className="size-4" aria-hidden="true" />
Copiar link
</button>
{shareUrl ? (
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<MessageCircle className="size-4" aria-hidden="true" />
Enviar por WhatsApp
</a>
) : null}
</div>
<p
aria-live="polite"
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
>
{copied ? (
<>
<Check className="size-3.5" aria-hidden="true" />
Link copiado
</>
) : null}
</p>
</div>
</div>
</Section>
)
}

View File

@@ -0,0 +1,120 @@
import { useEffect, useId, useRef, useState } from 'react'
import type { KeyboardEvent, RefObject } from 'react'
import { Ellipsis, UserMinus } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider'
const ITEM_CLASS =
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Menú "⋯" de la ficha del miembro.
*
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de
* regenerar el token de ausencias, así que la opción no se muestra antes que
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
* lista de abajo.
*
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
export function AttendeeActionsMenu({
triggerRef,
}: {
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
* foco cuando se cierra. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { openRemoveDialog } = useAttendeeDetail()
const [isOpen, setIsOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
const itemRef = useRef<HTMLButtonElement>(null)
const menuId = useId()
useEffect(() => {
if (isOpen) itemRef.current?.focus()
}, [isOpen])
useEffect(() => {
if (!isOpen) return
const handlePointerDown = (event: PointerEvent) => {
const target = event.target as Node
if (menuRef.current?.contains(target) || triggerRef.current?.contains(target)) return
setIsOpen(false)
}
document.addEventListener('pointerdown', handlePointerDown)
return () => document.removeEventListener('pointerdown', handlePointerDown)
}, [isOpen, triggerRef])
const close = (restoreFocus = false) => {
setIsOpen(false)
if (restoreFocus) triggerRef.current?.focus()
}
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Escape') {
event.stopPropagation()
close(true)
return
}
if (event.key === 'Tab') {
close()
return
}
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return
event.preventDefault()
const items = Array.from(
menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [],
)
if (items.length === 0) return
const current = items.indexOf(document.activeElement as HTMLElement)
const next =
event.key === 'Home'
? 0
: event.key === 'End'
? items.length - 1
: (current + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
items[next]?.focus()
}
return (
<div className="relative shrink-0">
<button
ref={triggerRef}
type="button"
onClick={() => setIsOpen((value) => !value)}
aria-haspopup="menu"
aria-expanded={isOpen}
aria-controls={isOpen ? menuId : undefined}
aria-label="Más acciones"
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Ellipsis className="size-5" aria-hidden="true" />
</button>
{isOpen ? (
<div
ref={menuRef}
id={menuId}
role="menu"
aria-label="Acciones del miembro"
onKeyDown={handleKeyDown}
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
>
<button
ref={itemRef}
type="button"
role="menuitem"
className={ITEM_CLASS}
onClick={() => {
close()
openRemoveDialog()
}}
>
<UserMinus className="size-4 shrink-0 text-danger" aria-hidden="true" />
Quitar del grupo
</button>
</div>
) : null}
</div>
)
}

View File

@@ -0,0 +1,116 @@
import { useState } from 'react'
import type { AttendanceStatus } from '@gruperly/shared'
import { Check, ChevronDown, Loader2, Megaphone, Minus, X } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import {
attendanceStatusClass,
attendanceStatusLabel,
attendanceSummaryLabel,
formatSessionShortDate,
HISTORY_LIMIT,
HISTORY_PREVIEW,
visibleSessions,
type AttendanceSession,
} from './attendance'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
PRESENT: Check,
ABSENT: X,
EXCUSED: Megaphone,
UNMARKED: Minus,
}
function iconFor(status: AttendanceSession['status']): LucideIcon {
return STATUS_ICONS[status ?? 'UNMARKED']
}
export function AttendeeAttendanceSection() {
const { history, historyPending, historyFailed } = useAttendeeDetail()
const [showAll, setShowAll] = useState(false)
if (historyPending) {
return (
<Section title="Asistencia" trailing="—">
<div className="flex items-center justify-center py-5">
<Loader2 className="size-5 animate-spin text-accent" />
</div>
</Section>
)
}
if (historyFailed) {
return (
<Section title="Asistencia">
<p className="py-3 text-sm text-foreground">
No pudimos cargar la asistencia de este miembro.
</p>
</Section>
)
}
const sessions = history?.sessions ?? []
if (sessions.length === 0) {
return (
<Section title="Asistencia">
<p className="py-3 text-sm text-foreground">
Todavía no hay clases registradas.
</p>
</Section>
)
}
const visible = visibleSessions(sessions, showAll)
const hasMore = sessions.length > HISTORY_PREVIEW
const isCapped = sessions.length >= HISTORY_LIMIT
return (
<Section title="Asistencia" trailing={attendanceSummaryLabel(visible)}>
<ul className="divide-y divide-border/60">
{visible.map((session) => {
const Icon = iconFor(session.status)
return (
<li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2.5">
<span className="truncate text-sm text-primary">
{formatSessionShortDate(session.startsAt)}
</span>
<span
className={cn(
'flex shrink-0 items-center gap-1.5 text-xs font-semibold',
attendanceStatusClass(session.status),
)}
>
<Icon className="size-3.5" aria-hidden="true" />
{attendanceStatusLabel(session.status)}
</span>
</li>
)
})}
</ul>
{showAll && isCapped ? (
<p className="pt-2 text-xs text-foreground">
El historial guarda las últimas {HISTORY_LIMIT} clases.
</p>
) : null}
{hasMore ? (
<div className="mt-1 flex justify-end">
<Button
variant="ghost"
onClick={() => setShowAll((value) => !value)}
aria-expanded={showAll}
className="h-11 gap-1 px-2 text-sm text-accent hover:text-accent-strong"
>
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
</Button>
</div>
) : null}
</Section>
)
}

View File

@@ -0,0 +1,39 @@
import { MessageCircle, Phone } from 'lucide-react'
import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils'
import { ACTION_BUTTON_CLASS } from './actionButton'
import { useAttendeeDetail } from './AttendeeDetailProvider'
export function AttendeeContactActions() {
const { attendee } = useAttendeeDetail()
const phone = attendee?.phone
if (!phone) return null
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos.
const digits = phone.replace(/\D/g, '')
const label = formatPhoneDisplay(phone) ?? phone
return (
<div className="flex gap-2.5">
<a
href={`https://wa.me/${digits}`}
target="_blank"
rel="noopener noreferrer"
aria-label={`Abrir WhatsApp con ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<MessageCircle className="size-4 text-accent" aria-hidden="true" />
WhatsApp
</a>
<a
href={`tel:${digits}`}
aria-label={`Llamar a ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<Phone className="size-4 text-accent" aria-hidden="true" />
Llamar
</a>
</div>
)
}

View File

@@ -0,0 +1,66 @@
import { Check, Copy, Mail } from 'lucide-react'
import { cn } from '../../lib/utils'
import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard'
const ROW_CLASS =
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
if (!attendee) return null
const phone = attendee.phone
const phoneLabel = formatPhoneDisplay(phone)
const { email, notes } = attendee
// Sin datos no hay sección: no se dibujan filas con "Sin email"/"Sin notas".
if (!phoneLabel && !email && !notes) return null
return (
<Section title="Contacto">
<div className="divide-y divide-border/60">
{phone && phoneLabel ? (
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => copy(phone)}
className={cn(ROW_CLASS, 'min-w-0 flex-1 text-left')}
>
<span className="truncate text-base text-primary">{phoneLabel}</span>
<span className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-foreground">
{copied ? (
<Check className="size-4 text-success" aria-hidden="true" />
) : (
<Copy className="size-4" aria-hidden="true" />
)}
{copied ? 'Copiado' : 'Copiar'}
</span>
</button>
{/* La confirmación visible no se anuncia sola: va en una región viva
aparte para no ensuciar el nombre accesible del botón. */}
<span aria-live="polite" className="sr-only">
{copied ? 'Teléfono copiado al portapapeles' : ''}
</span>
</div>
) : null}
{email ? (
<a href={`mailto:${email}`} className={ROW_CLASS}>
<span className="truncate text-base text-primary">{email}</span>
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
</a>
) : null}
{notes ? (
<p className="whitespace-pre-line py-2.5 text-sm leading-relaxed text-primary">
{notes}
</p>
) : null}
</div>
</Section>
)
}

View File

@@ -2,10 +2,9 @@ import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared'
import { useToast } from '../../../components/ui'
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api'
import { useRemoveAttendee } from './useRemoveAttendee'
import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
type AttendeeDetailContextValue = {
groupId: string
@@ -13,18 +12,17 @@ type AttendeeDetailContextValue = {
attendee: AttendeeDto | undefined
attendeePending: boolean
attendeeFailed: boolean
attendeeStats: AttendeeStats | undefined
attendeeStatsPending: boolean
attendeeStatsFailed: boolean
history: AttendeeHistory | undefined
historyPending: boolean
historyFailed: boolean
firstWaitlistEntry: GroupWaitlistEntryDto | null
waitlistTotal: number
waitlistPending: boolean
isRemoveModalOpen: boolean
openRemoveModal: () => void
closeRemoveModal: () => void
isRemoveDialogOpen: boolean
openRemoveDialog: () => void
closeRemoveDialog: () => void
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
isSubmittingRemoval: boolean
copyAbsenceNotifyUrl: (url: string) => void
}
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
@@ -38,9 +36,8 @@ export function AttendeeDetailProvider({
attendeeId: string
children: ReactNode
}) {
const toast = useToast()
const navigate = useNavigate()
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false)
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
const groupQuery = useQuery({
queryKey: ['group', groupId],
@@ -54,16 +51,20 @@ export function AttendeeDetailProvider({
enabled: Boolean(groupId && attendeeId),
})
const attendeeStatsQuery = useQuery({
queryKey: ['attendee-stats', groupId, attendeeId],
queryFn: () => getAttendeeStats(groupId, attendeeId),
// Misma clave que usa la pantalla de estadísticas: las dos leen el mismo
// historial y no se pisan la caché.
const historyQuery = useQuery({
queryKey: ['attendee-history', groupId, attendeeId],
queryFn: () => getAttendeeHistory(groupId, attendeeId),
enabled: Boolean(groupId && attendeeId),
})
// La lista de espera solo hace falta para el diálogo de quitar, así que no se
// pide hasta que el usuario lo abre.
const waitlistQuery = useQuery({
queryKey: ['group-waitlist', groupId],
queryFn: () => getGroupWaitlist(groupId, 1, 100),
enabled: Boolean(groupId && isRemoveModalOpen),
enabled: Boolean(groupId && isRemoveDialogOpen),
})
const waitlistEntries = waitlistQuery.data?.data ?? []
@@ -73,38 +74,31 @@ export function AttendeeDetailProvider({
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
groupId,
onRemoved: () => {
setIsRemoveModalOpen(false)
setIsRemoveDialogOpen(false)
void navigate({ to: '/groups/$groupId', params: { groupId } })
},
})
const copyAbsenceNotifyUrl = (url: string) => {
void navigator.clipboard.writeText(url).then(() => {
toast.success('Link copiado al portapapeles.')
})
}
const value: AttendeeDetailContextValue = {
groupId,
groupName: groupQuery.data?.name,
attendee: attendeeQuery.data,
attendeePending: attendeeQuery.isPending,
attendeeFailed: attendeeQuery.isError,
attendeeStats: attendeeStatsQuery.data,
attendeeStatsPending: attendeeStatsQuery.isPending,
attendeeStatsFailed: attendeeStatsQuery.isError,
history: historyQuery.data,
historyPending: historyQuery.isPending,
historyFailed: historyQuery.isError,
firstWaitlistEntry,
waitlistTotal,
waitlistPending: waitlistQuery.isPending,
isRemoveModalOpen,
openRemoveModal: () => setIsRemoveModalOpen(true),
closeRemoveModal: () => setIsRemoveModalOpen(false),
isRemoveDialogOpen,
openRemoveDialog: () => setIsRemoveDialogOpen(true),
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
confirmRemoveAttendee: (promoteFromWaitlist) => {
if (!attendeeQuery.data) return
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
},
isSubmittingRemoval: isRemovingAttendee,
copyAbsenceNotifyUrl,
}
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>

View File

@@ -0,0 +1,87 @@
import { useRef } from 'react'
import { Link, useNavigate } from '@tanstack/react-router'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { AbsenceLinkSection } from './AbsenceLinkSection'
import { AttendeeActionsMenu } from './AttendeeActionsMenu'
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
import { formatMemberSince } from './attendance'
export function AttendeeDetailView() {
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
const navigate = useNavigate()
const menuTriggerRef = useRef<HTMLButtonElement>(null)
if (attendeePending) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)
}
if (attendeeFailed || !attendee) {
return (
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no
pasa los 4.5:1 que necesita un `text-sm`. */}
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
<p className="mt-2 text-sm text-primary">
No se pudo cargar la información de este miembro.
</p>
<Button
variant="ghost"
className="mt-4 px-0 text-accent hover:bg-transparent hover:text-accent-strong"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
>
Volver al grupo
</Button>
</div>
)
}
return (
<section className="animate-fade-in">
<div className="flex items-center justify-between gap-2">
<Link
to="/groups/$groupId"
params={{ groupId }}
className="flex min-h-11 min-w-0 items-center gap-1.5 rounded-lg py-2 text-sm text-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<ArrowLeft className="size-4 shrink-0" aria-hidden="true" />
<span className="truncate">{groupName ?? 'Grupo'}</span>
</Link>
<AttendeeActionsMenu triggerRef={menuTriggerRef} />
</div>
<div className="mt-1">
<h1 className="text-balance text-2xl font-bold leading-tight tracking-tight text-primary">
{attendee.fullName}
</h1>
<p className="mt-1 whitespace-nowrap text-sm text-foreground">
Miembro desde {formatMemberSince(attendee.createdAt)}
</p>
</div>
<div className="mt-4">
<AttendeeContactActions />
</div>
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
arriba de Asistencia; el layout no se toca. */}
<div className="mt-6 space-y-5">
<AttendeeAttendanceSection />
<AttendeeContactSection />
<AbsenceLinkSection />
</div>
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
</section>
)
}

View File

@@ -0,0 +1,170 @@
import { useEffect, useRef } from 'react'
import type { RefObject } from 'react'
import type { LucideIcon } from 'lucide-react'
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
type Consequence = { key: string; icon: LucideIcon; text: string }
export function ConfirmRemoveAttendeeDialog({
returnFocusRef,
}: {
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */
returnFocusRef: RefObject<HTMLButtonElement | null>
}) {
const {
attendee,
groupName,
firstWaitlistEntry,
waitlistTotal,
waitlistPending,
isSubmittingRemoval,
isRemoveDialogOpen,
closeRemoveDialog,
confirmRemoveAttendee,
} = useAttendeeDetail()
const wasOpen = useRef(false)
const contentRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (isRemoveDialogOpen) {
wasOpen.current = true
return
}
if (!wasOpen.current) return
wasOpen.current = false
returnFocusRef.current?.focus()
}, [isRemoveDialogOpen, returnFocusRef])
useEffect(() => {
if (!isRemoveDialogOpen) return
return trapTabWithin(contentRef)
}, [isRemoveDialogOpen])
if (!attendee) return null
const waiting = waitlistTotal > 0
const canPromote = !waitlistPending && firstWaitlistEntry !== null
const consequences: Consequence[] = [
{
key: 'historial',
icon: History,
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
},
]
if (attendee.notifyToken) {
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
}
consequences.push({
key: 'lugar',
icon: Users,
text: waiting
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
waitlistTotal === 1 ? 'persona' : 'personas'
} en lista de espera.`
: 'Se libera 1 lugar en el grupo.',
})
return (
<Modal
isOpen={isRemoveDialogOpen}
onClose={closeRemoveDialog}
title="Quitar del grupo"
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
maxWidth="sm"
>
<div ref={contentRef} className="space-y-4">
<ul className="space-y-2.5">
{consequences.map(({ icon: Icon, key, text }) => (
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
<span>{text}</span>
</li>
))}
</ul>
<p className="text-xs text-foreground">
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
</p>
{canPromote && firstWaitlistEntry ? (
<div className="rounded-xl bg-accent-soft p-3.5">
<p className="text-sm text-foreground">
Si lo quitás, podés darle el lugar a{' '}
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
de la lista de espera.
</p>
<Button
variant="primary"
onClick={() => confirmRemoveAttendee(true)}
disabled={isSubmittingRemoval}
className="mt-2.5 w-full gap-2"
>
{isSubmittingRemoval ? (
<Loader2 className="size-4 animate-spin" />
) : (
<UserPlus className="size-4" />
)}
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
</Button>
</div>
) : null}
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
Cancelar
</Button>
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro,
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */}
<Button
onClick={() => confirmRemoveAttendee(false)}
disabled={isSubmittingRemoval}
className="gap-2 bg-danger text-black hover:bg-danger/90"
>
{isSubmittingRemoval ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Trash2 className="size-4" />
)}
<span>Quitar del grupo</span>
</Button>
</div>
</div>
</Modal>
)
}
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con
* Escape) lo deja seguir su curso normal. */
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return
const container = contentRef.current
if (!container?.contains(document.activeElement)) return
const focusable = Array.from(container.querySelectorAll<HTMLElement>('button:not([disabled])'))
if (focusable.length === 0) return
const first = focusable[0]
const last = focusable[focusable.length - 1]
const active = document.activeElement
if (event.shiftKey && active === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && active === last) {
event.preventDefault()
first.focus()
}
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}

View File

@@ -0,0 +1,40 @@
import { useId } from 'react'
import type { ReactNode } from 'react'
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
type SectionProps = {
/** Título de la sección. Un string por lo general; un botón cuando la
* sección se despliega desde el propio título (ver Link de ausencias). */
title: ReactNode
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
trailing?: ReactNode
children: ReactNode
}
/** Bloque de sección: separador fino sobre el fondo, título chico en
* mayúsculas y contenido sin padding propio (el de la pantalla).
*
* La pantalla se arma apilando secciones en este orden, así que sumar una
* nueva (Pagos, por ejemplo) es insertar otro bloque y nada más. */
export function Section({ title, trailing, children }: SectionProps) {
const headingId = useId()
return (
<section aria-labelledby={headingId} className="border-t border-border/70 pt-5">
<div className="flex items-center justify-between gap-3">
<h2 id={headingId} className={SECTION_TITLE_CLASS}>
{title}
</h2>
{trailing ? (
<div className="shrink-0 text-xs font-semibold tabular-nums text-foreground">
{trailing}
</div>
) : null}
</div>
<div className="mt-2.5">{children}</div>
</section>
)
}

View File

@@ -0,0 +1,8 @@
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link).
*
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
export const ACTION_BUTTON_CLASS =
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'

View File

@@ -0,0 +1,77 @@
import type { AttendanceHistoryItem } from '@gruperly/shared'
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
"Ver todas" no promete más de lo que hay. */
export const HISTORY_PREVIEW = 5
export const HISTORY_LIMIT = 20
export type AttendanceSession = AttendanceHistoryItem
export function formatSessionShortDate(iso: string): string {
const date = new Date(iso)
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
const month = date.toLocaleDateString('es-MX', { month: 'short' })
return `${weekday} ${day} ${month}`
}
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
return 'Asistió'
case 'ABSENT':
return 'Faltó'
case 'EXCUSED':
return 'Faltó (avisó)'
default:
return 'Sin registrar'
}
}
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado
están pensados como texto sobre superficies oscuras y el verde sobre blanco
queda justo por debajo de AA, así que la fila lleva las tres señales. */
export function attendanceStatusClass(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
return 'text-success'
case 'ABSENT':
return 'text-danger'
case 'EXCUSED':
return 'text-warning'
default:
return 'text-foreground'
}
}
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */
export function formatMemberSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-MX', {
day: 'numeric',
month: 'short',
year: 'numeric',
})
}
/** "1 clase" / "2 clases". */
export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases`
}
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
* contrario (más antigua → más reciente). */
export function visibleSessions(
sessions: AttendanceSession[],
showAll: boolean,
): AttendanceSession[] {
const ordered = [...sessions].reverse()
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
}
/** "3 de 5 clases", contando solo las sesiones que se están mostrando. */
export function attendanceSummaryLabel(sessions: AttendanceSession[]): string {
const present = sessions.filter((session) => session.status === 'PRESENT').length
return `${present} de ${classCountLabel(sessions.length)}`
}

View File

@@ -0,0 +1,33 @@
import { useEffect, useRef, useState } from 'react'
const FEEDBACK_MS = 1800
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
export function useCopyToClipboard() {
const [copied, setCopied] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(
() => () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
},
[],
)
const copy = (text: string) => {
if (!navigator.clipboard) return
void navigator.clipboard
.writeText(text)
.then(() => {
setCopied(true)
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
})
// Si el navegador rechaza la escritura no hay nada que confirmar: se
// deja el control como estaba en vez de dejar la promesa sin manejar.
.catch(() => setCopied(false))
}
return { copied, copy }
}

View File

@@ -1,106 +0,0 @@
import { Loader2 } from 'lucide-react'
import { cn } from '../../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider'
type RateTone = 'good' | 'mid' | 'low' | 'none'
function rateTone(rate: number, totalMarked: number): RateTone {
if (totalMarked === 0) return 'none'
if (rate >= 75) return 'good'
if (rate >= 50) return 'mid'
return 'low'
}
const barTone: Record<RateTone, string> = {
good: 'bg-success',
mid: 'bg-warning',
low: 'bg-danger',
none: 'bg-border',
}
const valueTone: Record<RateTone, string> = {
good: 'text-success',
mid: 'text-warning',
low: 'text-danger',
none: 'text-foreground/40',
}
export function AttendeeAttendanceStats() {
const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail()
if (attendeeStatsPending) {
return (
<div className="flex items-center justify-center rounded-xl border border-border bg-primary-soft/30 py-8">
<Loader2 className="size-5 animate-spin text-accent" />
</div>
)
}
if (attendeeStatsFailed || !attendeeStats) {
return (
<div className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
No pudimos cargar la asistencia de este participante.
</div>
)
}
const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats
const tone = rateTone(attendanceRate, totalMarked)
return (
<div className="space-y-3 rounded-xl border border-border bg-primary-soft/30 p-3 sm:p-4">
<div className="flex items-end justify-between gap-3">
<div className="min-w-0">
<p className="text-[11px] font-medium uppercase tracking-wide text-foreground/50">
Asistencia
</p>
<p className="text-xs text-foreground/50">
{totalMarked > 0
? `Sobre ${totalMarked} clases registradas`
: 'Sin clases registradas todavía'}
</p>
</div>
<p className={cn('text-2xl font-bold tabular-nums', valueTone[tone])}>
{totalMarked > 0 ? `${attendanceRate}%` : '—'}
</p>
</div>
<div
className="h-1.5 overflow-hidden rounded-full bg-border"
role="presentation"
aria-hidden="true"
>
<div
className={cn(
'h-full rounded-full transition-[width] duration-500 ease-out',
barTone[tone],
)}
style={{ width: `${attendanceRate}%` }}
/>
</div>
<dl className="grid grid-cols-3 gap-1.5 sm:gap-2">
<StatCounter value={presentCount} label="Clases asistidas" valueClass="text-success" />
<StatCounter value={absentCount} label="Clases ausentes" valueClass="text-danger" />
<StatCounter value={excusedCount} label="Avisó ausencia" valueClass="text-warning" />
</dl>
</div>
)
}
function StatCounter({
value,
label,
valueClass,
}: {
value: number
label: string
valueClass: string
}) {
return (
<div className="min-w-0 rounded-lg bg-surface px-2 py-2">
<dt className="text-[11px] font-medium uppercase leading-tight text-foreground/50">{label}</dt>
<dd className={cn('text-lg font-bold tabular-nums', valueClass)}>{value}</dd>
</div>
)
}

View File

@@ -1,213 +0,0 @@
import { Link, useNavigate } from '@tanstack/react-router'
import {
ArrowLeft,
Copy,
Loader2,
Mail,
MessageCircle,
Phone,
ShieldCheck,
StickyNote,
UserMinus,
} from 'lucide-react'
import { Button } from '../../../components/ui'
import { formatPhoneDisplay } from '../../../lib/format'
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { DetailRow } from './DetailRow'
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
export function AttendeeDetailPage() {
const {
groupId,
groupName,
attendee,
attendeePending,
attendeeFailed,
openRemoveModal,
isRemoveModalOpen,
closeRemoveModal,
confirmRemoveAttendee,
firstWaitlistEntry,
waitlistTotal,
waitlistPending,
isSubmittingRemoval,
copyAbsenceNotifyUrl,
} = useAttendeeDetail()
const navigate = useNavigate()
if (attendeePending) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)
}
if (attendeeFailed || !attendee) {
return (
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
<h2 className="text-lg font-semibold">Participante no encontrado</h2>
<p className="mt-2 text-sm">No se pudo cargar la información de este participante.</p>
<Button
variant="outline"
className="mt-4"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
>
Volver al grupo
</Button>
</div>
)
}
const absenceNotifyUrl = attendee.notifyToken
? `${window.location.origin}/report-absence/${attendee.notifyToken}`
: null
return (
<section className="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>
<div className="flex items-center gap-3">
<div className="flex size-14 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xl font-bold text-accent">
{attendee.fullName.charAt(0).toUpperCase()}
</div>
<div className="min-w-0">
<h1 className="truncate text-xl font-bold text-primary">{attendee.fullName}</h1>
<p className="text-xs text-foreground/50">
{groupName ? `${groupName} · ` : ''}Incorporado el{' '}
{new Date(attendee.createdAt).toLocaleDateString('es-ES', {
day: 'numeric',
month: 'long',
year: 'numeric',
})}
</p>
</div>
</div>
<AttendeeAttendanceStats />
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
{attendee.phone ? (
<div className="flex items-center gap-2">
<span className="text-primary">{formatPhoneDisplay(attendee.phone)}</span>
<a
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
<span>WhatsApp</span>
</a>
</div>
) : (
<span className="text-foreground/40">Sin teléfono</span>
)}
</DetailRow>
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
{attendee.email ? (
<a
href={`mailto:${attendee.email}`}
className="text-primary transition-colors hover:text-accent"
>
{attendee.email}
</a>
) : (
<span className="text-foreground/40">Sin email</span>
)}
</DetailRow>
{attendee.guardianName || attendee.guardianPhone ? (
<>
<DetailRow icon={<ShieldCheck className="size-4 text-accent" />} label="Responsable">
<span className="text-primary">
{attendee.guardianName || <span className="text-foreground/40">—</span>}
</span>
</DetailRow>
{attendee.guardianPhone ? (
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
<div className="flex items-center gap-2">
<span className="text-primary">{formatPhoneDisplay(attendee.guardianPhone)}</span>
<a
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
</a>
</div>
</DetailRow>
) : null}
</>
) : null}
<DetailRow icon={<StickyNote className="size-4 text-accent" />} label="Notas">
{attendee.notes ? (
<span className="text-xs leading-relaxed text-primary">{attendee.notes}</span>
) : (
<span className="text-foreground/40">Sin notas</span>
)}
</DetailRow>
</div>
{absenceNotifyUrl ? (
<div className="space-y-2 rounded-xl border border-border p-4">
<p className="text-xs font-medium text-foreground/60">Link para avisar ausencias</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded-lg bg-primary-soft px-2 py-1.5 text-xs text-primary">
{absenceNotifyUrl}
</code>
<Button variant="outline" size="sm" onClick={() => copyAbsenceNotifyUrl(absenceNotifyUrl)}>
<Copy className="size-3.5" />
Copiar
</Button>
</div>
{attendee.phone ? (
<a
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${absenceNotifyUrl}`)}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
<span>Enviar por WhatsApp</span>
</a>
) : null}
</div>
) : null}
<div className="border-t border-border pt-2">
<Button
variant="ghost"
onClick={openRemoveModal}
className="w-full gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
>
<UserMinus className="size-4" />
Quitar del grupo
</Button>
</div>
<RemoveAttendeeModal
attendee={isRemoveModalOpen ? attendee : null}
groupName={groupName}
firstWaitlistEntry={firstWaitlistEntry}
waitlistTotal={waitlistTotal}
isResolvingWaitlist={isRemoveModalOpen && waitlistPending}
isSubmitting={isSubmittingRemoval}
onCancel={closeRemoveModal}
onConfirm={confirmRemoveAttendee}
/>
</section>
)
}

View File

@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type {
AttendeeDto,
AttendeeListItem,
GroupDto,
GroupPreRegistrationDto,
GroupWaitlistEntryDto,
@@ -33,7 +34,7 @@ type GroupDetailContextValue = {
groupTitle: string
groupQueryPending: boolean
riskLevel: GroupRiskLevel
attendees: AttendeeDto[]
attendees: AttendeeListItem[]
attendeesTotal: number
attendeesPending: boolean
waitlistEntries: GroupWaitlistEntryDto[]
@@ -49,6 +50,9 @@ type GroupDetailContextValue = {
whatsappMessage: string
searchFilter: string
setSearchFilter: (value: string) => void
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */
overdueOnly: boolean
setOverdueOnly: (value: boolean) => void
listSection: ListSection
setListSection: (value: ListSection) => void
isInviteModalOpen: boolean
@@ -90,12 +94,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
const [searchFilter, setSearchFilter] = useState('')
const [overdueOnly, setOverdueOnly] = useState(false)
// La búsqueda pertenece a la vista que la abrió: al cambiar de pestaña se
// limpia para no heredar un filtro sin coincidencias.
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
// pestaña se limpian para no heredar un filtro sin coincidencias.
const setListSection = (value: ListSection) => {
setListSectionState(value)
setSearchFilter('')
setOverdueOnly(false)
}
const groupQuery = useQuery({
@@ -313,6 +319,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
whatsappMessage,
searchFilter,
setSearchFilter,
overdueOnly,
setOverdueOnly,
listSection,
setListSection,
isInviteModalOpen,

View File

@@ -0,0 +1,109 @@
import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { Check } from 'lucide-react'
import { cn } from '../../../lib/utils'
import { dotClass, statusLabel } from '../analytics/format'
import { useGroupDetail } from './GroupDetailProvider'
import {
type PaymentState,
paymentStateLabel,
resolvePaymentState,
summarizeAttendance,
} from './member-row'
/* Solo lo excepcional se pinta. "Al día" queda en el tono base y con un check
para que el estado se lea sin depender del color; vencido es el único que
sube de peso. */
const PAYMENT_TONE: Record<PaymentState['kind'], string> = {
settled: 'text-foreground',
dueSoon: 'font-medium text-warning',
overdue: 'font-semibold text-danger',
}
function PaymentLabel({ state }: { state: PaymentState }) {
return (
<span className={cn('flex shrink-0 items-center gap-1 text-xs', PAYMENT_TONE[state.kind])}>
{state.kind === 'settled' ? (
<Check className="size-3 shrink-0" aria-hidden="true" />
) : null}
{paymentStateLabel(state)}
</span>
)
}
function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) {
const summary = summarizeAttendance(recent)
if (summary.recorded === 0) {
return <p className="mt-0.5 text-xs text-foreground">{summary.label}</p>
}
return (
<div className="mt-0.5 flex items-center gap-2">
{/* Cada punto lleva su propio nombre accesible: el color solo es el
refuerzo visual, no la única forma de saber qué pasó. */}
<span className="flex items-center gap-1">
{summary.dots.map((status, index) => (
<span
key={index}
role="img"
aria-label={`Clase ${index + 1} de ${summary.recorded}: ${statusLabel(status).toLowerCase()}`}
className={cn('size-2 rounded-full', dotClass(status))}
/>
))}
</span>
<span className="text-xs text-foreground">{summary.label}</span>
</div>
)
}
function MemberRow({
attendee,
groupId,
}: {
attendee: AttendeeListItem
groupId: string
}) {
const paymentState = resolvePaymentState(attendee.payment)
return (
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId, attendeeId: attendee.id }}
// `min-h-14` (56px) es el piso táctil cómodo. La fila entera es el link, así
// que no hace falta chevron ni fila con tabIndex: hereda el rol y el
// teclado del <a>, y además sirve el href real al abrir en otra pestaña.
className={cn(
'flex min-h-14 items-center border-b border-foreground/10 px-3 py-2.5',
'transition-colors duration-150 hover:bg-surface/60 active:bg-surface',
'focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent',
)}
>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-3">
<span className="min-w-0 truncate font-medium text-primary" title={attendee.fullName}>
{attendee.fullName}
</span>
{paymentState ? <PaymentLabel state={paymentState} /> : null}
</div>
<AttendanceStrip recent={attendee.recentAttendance} />
</div>
</Link>
)
}
export function MembersList({ attendees }: { attendees: AttendeeListItem[] }) {
// El groupId se lee una vez y se pasa: suscribir cada fila al contexto entero
// hace que un cambio de estado del provider re-renderice N filas sin motivo.
const { groupId } = useGroupDetail()
return (
<ul>
{attendees.map((attendee) => (
<li key={attendee.id}>
<MemberRow attendee={attendee} groupId={groupId} />
</li>
))}
</ul>
)
}

View File

@@ -1,79 +0,0 @@
import type { AttendeeDto } from '@gruperly/shared'
import { useNavigate } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react'
import { formatPhoneDisplay } from '../../../lib/format'
import { useGroupDetail } from './GroupDetailProvider'
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
const { groupId } = useGroupDetail()
const navigate = useNavigate()
const openAttendee = (attendeeId: string) => {
void navigate({ to: '/groups/$groupId/attendees/$attendeeId', params: { groupId, attendeeId } })
}
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a
`primary-soft`, el fondo de la fila, y el separador desaparecería. */}
<tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th>
<th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span>
</th>
</tr>
</thead>
<tbody>
{attendees.map((attendee) => (
<tr
key={attendee.id}
tabIndex={0}
// El hover va a `surface` porque la fila ya vive sobre `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => openAttendee(attendee.id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
openAttendee(attendee.id)
}
}}
>
{/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
<td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
{attendee.fullName.charAt(0).toUpperCase()}
</div>
{/* `truncate` solo recorta lo pintado: el texto completo sigue en
el DOM para lectores de pantalla, y `title` lo muestra al hover. */}
<span
className="min-w-0 truncate font-semibold text-primary"
title={attendee.fullName}
>
{attendee.fullName}
</span>
</div>
</td>
{/* El nombre manda; el teléfono es un dato secundario: un nivel
más abajo en la escala de color, en un tamaño menor. */}
<td className="min-w-0 px-3 py-2 text-xs text-foreground/70">
{attendee.phone ? (
<span className="block truncate tabular-nums" title={attendee.phone}>
{formatPhoneDisplay(attendee.phone)}
</span>
) : (
<span className="text-foreground/60">—</span>
)}
</td>
<td className="w-8 px-1 py-2 text-foreground/50">
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
</td>
</tr>
))}
</tbody>
</table>
)
}

View File

@@ -1,22 +1,70 @@
import { useNavigate } from '@tanstack/react-router'
import { Loader2, Plus, Share2, Users } from 'lucide-react'
import { Loader2, Plus, Share2, Users, X } from 'lucide-react'
import { Button } from '../../../components/ui'
import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider'
import { MembersTable } from './MembersTable'
import { MembersList } from './MembersList'
import { byFullName, isOverdue, resolvePaymentState } from './member-row'
function OverdueFilter({ count }: { count: number }) {
const { overdueOnly, setOverdueOnly } = useGroupDetail()
return (
<div className="px-3 pb-1.5">
<button
type="button"
aria-pressed={overdueOnly}
onClick={() => setOverdueOnly(!overdueOnly)}
className={cn(
// min-h-11 (44px): objetivo táctil mínimo, igual que los chips de sección.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold',
'transition-[background-color,color,border-color,box-shadow] duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',
overdueOnly
? 'border-transparent bg-danger-soft text-danger'
: 'border-border bg-surface text-foreground hover:border-danger/40 hover:text-danger',
)}
>
{/* La ✕ solo aparece con el filtro puesto: es la señal de que tocarlo
lo saca, sin tener que decirlo. */}
{overdueOnly ? <X className="size-3.5 shrink-0" aria-hidden="true" /> : null}
<span className="whitespace-nowrap">{count} con pago vencido</span>
</button>
</div>
)
}
export function MembersView() {
const { groupId, attendees, attendeesPending, searchFilter, openInviteModal } = useGroupDetail()
const {
groupId,
attendees,
attendeesPending,
searchFilter,
overdueOnly,
openInviteModal,
} = useGroupDetail()
const navigate = useNavigate()
const query = searchFilter.trim().toLowerCase()
const filtered = query
? attendees.filter(
(a) =>
a.fullName.toLowerCase().includes(query) ||
(a.phone && a.phone.includes(query)) ||
(a.email && a.email.toLowerCase().includes(query)),
)
: attendees
// El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda:
// es como la mayoría conoce a los alumnos del grupo.
const matchesQuery = (attendee: (typeof attendees)[number]) =>
!query ||
attendee.fullName.toLowerCase().includes(query) ||
(attendee.phone != null && attendee.phone.includes(query)) ||
(attendee.email != null && attendee.email.toLowerCase().includes(query))
const overdueCount = attendees.filter((attendee) =>
isOverdue(resolvePaymentState(attendee.payment)),
).length
const visible = attendees
.filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment)))
.filter(matchesQuery)
// Orden alfabético fijo: si se ordenara por cobro o asistencia las filas
// saltarían de lugar cada vez que alguien paga o falta, y el nombre es la
// única columna estable de la lista.
.sort(byFullName)
if (attendeesPending) {
return (
@@ -28,9 +76,6 @@ export function MembersView() {
if (attendees.length === 0) {
return (
// Full-bleed y sin radio propio: el `overflow-hidden` del panel lo recorta
// contra la silueta redondeada. `surface` sobre `primary-soft` hunde el
// bloque; con el lavado anterior se camuflaba.
<div className="bg-surface px-4 py-10 text-center">
<Users className="mx-auto mb-2 size-10 text-foreground/40" />
<p className="text-sm font-semibold text-primary">
@@ -60,13 +105,27 @@ export function MembersView() {
)
}
if (filtered.length === 0) {
const filterBar = overdueCount > 0 ? <OverdueFilter count={overdueCount} /> : null
if (visible.length === 0) {
// El filtro de vencidos nunca queda vacío por sí solo (el chip no se muestra
// si no hay vencidos), así que un vacío acá es siempre la búsqueda.
return (
<div className="py-8 text-center text-sm text-foreground/80">
No se encontraron miembros que coincidan con la búsqueda.
</div>
<>
{filterBar}
<div className="px-4 py-8 text-center text-sm text-foreground">
{overdueOnly
? 'Ningún miembro con pago vencido coincide con la búsqueda.'
: 'No se encontraron miembros que coincidan con la búsqueda.'}
</div>
</>
)
}
return <MembersTable attendees={filtered} />
return (
<>
{filterBar}
<MembersList attendees={visible} />
</>
)
}

View File

@@ -1,12 +1,18 @@
import { Search } from 'lucide-react'
import { Input } from '../../../components/ui'
import { MEMBER_SEARCH_MIN } from './constants'
import { useGroupDetail } from './GroupDetailProvider'
import { MembersView } from './MembersView'
import { PendingView } from './PendingView'
import { SectionChips } from './SectionChips'
export function MembersWaitlistSection() {
const { listSection, searchFilter, setSearchFilter } = useGroupDetail()
const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail()
// Con pocos miembros el buscador es ruido: se alcanza con recorrer la lista.
// Se quita del árbol en vez de esconderse, para no dejar un hueco en la fila.
// En Pendientes no cambia nada: ahí el volumen es el que es.
const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN
return (
// Una sola superficie: la lista va directo sobre el lavado, como la info
@@ -21,16 +27,18 @@ export function MembersWaitlistSection() {
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
<SectionChips />
<div className="relative w-full sm:w-72 lg:shrink-0">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
<Input
placeholder="Buscar por nombre o teléfono..."
value={searchFilter}
onChange={(e) => setSearchFilter(e.target.value)}
aria-label="Buscar en el listado"
className="h-11 rounded-lg border-transparent pl-9 shadow-xs"
/>
</div>
{showSearch ? (
<div className="relative w-full sm:w-72 lg:shrink-0">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
<Input
placeholder="Buscar por nombre o teléfono..."
value={searchFilter}
onChange={(e) => setSearchFilter(e.target.value)}
aria-label="Buscar en el listado"
className="h-11 rounded-lg border-transparent pl-9 shadow-xs"
/>
</div>
) : null}
</div>
{/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre

View File

@@ -0,0 +1,11 @@
/* Ajustes de la lista de miembros de la ficha de grupo. Viven acá y no
incrustados en el componente porque son decisiones de producto, no de estilo:
cambiarlas no debería obligar a tocar la fila. */
/* A partir de cuántos días para el vencimiento el cobro pasa a kuning y la fila
avisa. Más atrás ya no es "pronto": o se pagó o quedó en el pasado. */
export const PAYMENT_DUE_SOON_DAYS = 3
/* El buscador se muestra a partir de cierta cantidad de miembros. Con pocos, es
más ruido que ayuda: alcanza con mirar la lista. */
export const MEMBER_SEARCH_MIN = 8

View File

@@ -0,0 +1,103 @@
import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'
import { PAYMENT_DUE_SOON_DAYS } from './constants'
/* La fila del listado no pide al backend juicios de presentación: pide los
datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los
días que faltan cambian según cuándo se mira, así que no pueden venir
guardados desde el servidor. */
/** Días calendario entre dos fechas, sin horas: "vence el día 10" no tiene hora. */
function calendarDaysBetween(from: Date, to: Date): number {
const startOf = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
return Math.round((startOf(to) - startOf(from)) / 86_400_000)
}
export type PaymentState =
| { kind: 'settled' }
| { kind: 'dueSoon'; days: number }
| { kind: 'overdue'; days: number }
/**
* Qué hay que marcarle al cobro en la fila.
*
* Devuelve `null` cuando no hay nada que avisar: o el miembro no tiene ningún
* cobro registrado, o el que tiene vence más adelante que la ventana de aviso y
* todavía no venció. No es lo mismo que "al día", que es un pago cerrado.
*
* Un `PENDING` con vencimiento ya pasado cuenta como vencido, igual que un
* `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo
* actualiza a mano y la fila no puede depender de esa disciplina.
*/
export function resolvePaymentState(
payment: AttendeeListItem['payment'],
today: Date = new Date(),
): PaymentState | null {
if (!payment) return null
if (payment.status === 'PAID') return { kind: 'settled' }
const days = calendarDaysBetween(today, new Date(payment.dueDate))
if (payment.status === 'OVERDUE' || days < 0) {
return { kind: 'overdue', days: Math.abs(days) }
}
if (days <= PAYMENT_DUE_SOON_DAYS) {
return { kind: 'dueSoon', days }
}
return null
}
export function isOverdue(state: PaymentState | null): boolean {
return state?.kind === 'overdue'
}
export function paymentStateLabel(state: PaymentState): string {
switch (state.kind) {
case 'settled':
return 'Al día'
case 'dueSoon':
// "Vence en 0 d" no es español de persona: hoy y mañana tienen palabras.
if (state.days === 0) return 'Vence hoy'
if (state.days === 1) return 'Vence mañana'
return `Vence en ${state.days} d`
case 'overdue':
return `Vencido · ${state.days} d`
}
}
export type AttendanceSummary = {
/** Estados a dibujar, del más antiguo al más reciente. */
dots: AttendanceStatus[]
attended: number
recorded: number
/** "Sin clases aún" cuando no hay nada registrado. */
label: string
}
/** Los últimos puntos de clase registrados, contados sobre esa misma ventana. */
export function summarizeAttendance(
recentAttendance: AttendanceStatus[],
): AttendanceSummary {
// La ventana la fija el backend; el corte final evita que una fila se alargue
// si el contrato llegara con más clases de las previstas.
const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT)
const recorded = dots.length
if (recorded === 0) {
return { dots, attended: 0, recorded: 0, label: 'Sin clases aún' }
}
const attended = dots.filter((status) => status === 'PRESENT').length
return {
dots,
attended,
recorded,
label: `${attended} de ${recorded} ${recorded === 1 ? 'clase' : 'clases'}`,
}
}
/** Orden alfabético fijo del listado. */
export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number {
return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' })
}

View File

@@ -1,7 +1,7 @@
import { useParams } from '@tanstack/react-router'
import { createFileRoute } from '@tanstack/react-router'
import { AttendeeDetailPage } from '../../../../../features/groups/detail/AttendeeDetailPage'
import { AttendeeDetailProvider } from '../../../../../features/groups/detail/AttendeeDetailProvider'
import { AttendeeDetailProvider } from '../../../../../features/attendee-detail/AttendeeDetailProvider'
import { AttendeeDetailView } from '../../../../../features/attendee-detail/AttendeeDetailView'
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({
component: () => {
@@ -10,7 +10,7 @@ export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/
})
return (
<AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}>
<AttendeeDetailPage />
<AttendeeDetailView />
</AttendeeDetailProvider>
)
},