refactor: remove unused attendee detail components and provider
This commit is contained in:
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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'
|
||||
|
||||
type AttendeeDetailContextValue = {
|
||||
groupId: string
|
||||
groupName: string | undefined
|
||||
attendee: AttendeeDto | undefined
|
||||
attendeePending: boolean
|
||||
attendeeFailed: boolean
|
||||
attendeeStats: AttendeeStats | undefined
|
||||
attendeeStatsPending: boolean
|
||||
attendeeStatsFailed: boolean
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
isRemoveModalOpen: boolean
|
||||
openRemoveModal: () => void
|
||||
closeRemoveModal: () => void
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
isSubmittingRemoval: boolean
|
||||
copyAbsenceNotifyUrl: (url: string) => void
|
||||
}
|
||||
|
||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||
|
||||
export function AttendeeDetailProvider({
|
||||
groupId,
|
||||
attendeeId,
|
||||
children,
|
||||
}: {
|
||||
groupId: string
|
||||
attendeeId: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const toast = useToast()
|
||||
const navigate = useNavigate()
|
||||
const [isRemoveModalOpen, setIsRemoveModalOpen] = 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),
|
||||
})
|
||||
|
||||
const attendeeStatsQuery = useQuery({
|
||||
queryKey: ['attendee-stats', groupId, attendeeId],
|
||||
queryFn: () => getAttendeeStats(groupId, attendeeId),
|
||||
enabled: Boolean(groupId && attendeeId),
|
||||
})
|
||||
|
||||
const waitlistQuery = useQuery({
|
||||
queryKey: ['group-waitlist', groupId],
|
||||
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
||||
enabled: Boolean(groupId && isRemoveModalOpen),
|
||||
})
|
||||
|
||||
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||
|
||||
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||
groupId,
|
||||
onRemoved: () => {
|
||||
setIsRemoveModalOpen(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,
|
||||
firstWaitlistEntry,
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
isRemoveModalOpen,
|
||||
openRemoveModal: () => setIsRemoveModalOpen(true),
|
||||
closeRemoveModal: () => setIsRemoveModalOpen(false),
|
||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||
if (!attendeeQuery.data) return
|
||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||
},
|
||||
isSubmittingRemoval: isRemovingAttendee,
|
||||
copyAbsenceNotifyUrl,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
109
apps/web/src/features/groups/detail/MembersList.tsx
Normal file
109
apps/web/src/features/groups/detail/MembersList.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
11
apps/web/src/features/groups/detail/constants.ts
Normal file
11
apps/web/src/features/groups/detail/constants.ts
Normal 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
|
||||
103
apps/web/src/features/groups/detail/member-row.ts
Normal file
103
apps/web/src/features/groups/detail/member-row.ts
Normal 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' })
|
||||
}
|
||||
Reference in New Issue
Block a user