refactor: remove unused attendee detail components and provider
This commit is contained in:
91
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
91
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
113
apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx
Normal file
113
apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
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, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||
import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
|
||||
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||
|
||||
type AttendeeDetailContextValue = {
|
||||
groupId: string
|
||||
groupName: string | undefined
|
||||
attendee: AttendeeDto | undefined
|
||||
attendeePending: boolean
|
||||
attendeeFailed: boolean
|
||||
history: AttendeeHistory | undefined
|
||||
historyPending: boolean
|
||||
historyFailed: boolean
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
isRemoveDialogOpen: boolean
|
||||
openRemoveDialog: () => void
|
||||
closeRemoveDialog: () => void
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
isSubmittingRemoval: boolean
|
||||
}
|
||||
|
||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||
|
||||
export function AttendeeDetailProvider({
|
||||
groupId,
|
||||
attendeeId,
|
||||
children,
|
||||
}: {
|
||||
groupId: string
|
||||
attendeeId: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ['group', groupId],
|
||||
queryFn: () => getGroup(groupId),
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const attendeeQuery = useQuery({
|
||||
queryKey: ['group-attendee', groupId, attendeeId],
|
||||
queryFn: () => getGroupAttendee(groupId, attendeeId),
|
||||
enabled: Boolean(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 && isRemoveDialogOpen),
|
||||
})
|
||||
|
||||
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||
|
||||
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||
groupId,
|
||||
onRemoved: () => {
|
||||
setIsRemoveDialogOpen(false)
|
||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||
},
|
||||
})
|
||||
|
||||
const value: AttendeeDetailContextValue = {
|
||||
groupId,
|
||||
groupName: groupQuery.data?.name,
|
||||
attendee: attendeeQuery.data,
|
||||
attendeePending: attendeeQuery.isPending,
|
||||
attendeeFailed: attendeeQuery.isError,
|
||||
history: historyQuery.data,
|
||||
historyPending: historyQuery.isPending,
|
||||
historyFailed: historyQuery.isError,
|
||||
firstWaitlistEntry,
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
isRemoveDialogOpen,
|
||||
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||
if (!attendeeQuery.data) return
|
||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||
},
|
||||
isSubmittingRemoval: isRemovingAttendee,
|
||||
}
|
||||
|
||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||
}
|
||||
|
||||
export function useAttendeeDetail() {
|
||||
const context = useContext(AttendeeDetailContext)
|
||||
if (!context) {
|
||||
throw new Error('useAttendeeDetail debe usarse dentro de <AttendeeDetailProvider>')
|
||||
}
|
||||
return context
|
||||
}
|
||||
87
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
87
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
40
apps/web/src/features/attendee-detail/Section.tsx
Normal file
40
apps/web/src/features/attendee-detail/Section.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
8
apps/web/src/features/attendee-detail/actionButton.ts
Normal file
8
apps/web/src/features/attendee-detail/actionButton.ts
Normal 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'
|
||||
77
apps/web/src/features/attendee-detail/attendance.ts
Normal file
77
apps/web/src/features/attendee-detail/attendance.ts
Normal 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)}`
|
||||
}
|
||||
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal file
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal 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 }
|
||||
}
|
||||
Reference in New Issue
Block a user