diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts index 0a3dd6c..c3f81a4 100644 --- a/apps/backend/src/modules/attendees/features/get-all/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts @@ -1,10 +1,10 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared'; -import { ok } from '@gruperly/shared'; +import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; -import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; +import { toAttendeeListItemDto } from '../../lib/helpers'; type ListAttendeesDeps = { db?: Pick; @@ -18,18 +18,37 @@ export class ListAttendees { const where = query.groupId ? { groupId: query.groupId } : undefined; const [records, total] = await Promise.all([ + /* El resumen de cada fila viaja en la misma consulta en vez de armarse con + una petición por miembro. Ambas relaciones vienen acotadas a propósito: + la tabla de pagos crece un renglón por mes y para siempre, y el listado + solo necesita el estado actual de cada persona. */ db.attendee.findMany({ ...(where ? { where } : {}), skip: getPaginationOffset(query), take: query.pageSize, orderBy: { createdAt: 'desc' }, + include: { + // Por fecha de la clase, no por `markedAt`: marcar la asistencia + // tarde no debe cambiar qué clase cuenta como reciente. + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, }), where ? db.attendee.count({ where }) : db.attendee.count(), ]); return ok({ - data: records.map((r) => toAttendeeDto(r as AttendeeRecord)), + data: records.map((record) => toAttendeeListItemDto(record)), pagination: getPaginationMetadata(query, total), }); } -} \ No newline at end of file +} diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 61c8c95..7a6cde9 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -1,4 +1,4 @@ -import type { AttendeeDto } from '@gruperly/shared'; +import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared'; export type AttendeeRecord = { id: string; @@ -14,6 +14,15 @@ export type AttendeeRecord = { updatedAt: Date; }; +/** Item del listado con el resumen de asistencia y cobro ya resuelto. */ +export type AttendeeListItemRecord = AttendeeRecord & { + attendances: { status: AttendeeListItem['recentAttendance'][number] }[]; + payments: { + status: NonNullable['status']; + dueDate: Date; + }[]; +}; + export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { return { id: record.id, @@ -30,6 +39,37 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { }; } +/* El renglón que resume el cobro vigente. Si hay algo impago manda el de + vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos + días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada + impago, el último pago cerrado sirve para marcar la fila como al día. */ +function pickRelevantPayment( + payments: AttendeeListItemRecord['payments'], +): AttendeeListItem['payment'] { + // CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos + // acá también evita que un cargo anulado gane la fila por ser el más antiguo. + const byDueDate = payments + .filter((payment) => payment.status !== 'CANCELLED') + .sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime()); + const outstanding = byDueDate.find((payment) => payment.status !== 'PAID'); + const relevant = outstanding ?? byDueDate[byDueDate.length - 1]; + + if (!relevant) { + return null; + } + return { status: relevant.status, dueDate: relevant.dueDate.toISOString() }; +} + +/* La consulta viene en orden descendente; la fila los muestra de más antigua a + más reciente para que el punto de la derecha sea el último hecho. */ +export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem { + return { + ...toAttendeeDto(record), + recentAttendance: [...record.attendances].reverse().map((attendance) => attendance.status), + payment: pickRelevantPayment(record.payments), + }; +} + /** * Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos. * Conserva el '+' si lo tiene al inicio para números internacionales. diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts index 582124b..e2608c7 100644 --- a/apps/backend/test/attendees-incorporation.test.ts +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { Hono } from 'hono'; const db = { @@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => { notes: null, createdAt: new Date('2026-09-18T10:00:00.000Z'), updatedAt: new Date('2026-09-18T10:00:00.000Z'), + attendances: [], + payments: [], }, ] as never); prisma.attendee.count.mockResolvedValue(1); @@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => { const data = await res.json(); expect(data.data.length).toBe(1); expect(data.data[0].fullName).toBe('Ana García'); + expect(data.data[0].recentAttendance).toEqual([]); + expect(data.data[0].payment).toBeNull(); expect(prisma.attendee.findMany).toHaveBeenCalledWith({ where: { groupId: 'group-1' }, skip: 0, take: 10, orderBy: { createdAt: 'desc' }, + // El resumen de la fila se pide en la misma consulta: una petición por + // miembro sería N+1 sobre un listado de hasta 100. + include: { + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, }); }); }); diff --git a/apps/backend/test/attendees-list-item.test.ts b/apps/backend/test/attendees-list-item.test.ts new file mode 100644 index 0000000..4bfae10 --- /dev/null +++ b/apps/backend/test/attendees-list-item.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'bun:test'; +import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers'; +import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers'; + +/* El resumen de la fila se arma en memoria: qué clase cuenta como reciente y + qué cobro se muestra. Son las dos decisiones que la fila leen. */ + +function record( + overrides: Partial = {}, +): AttendeeListItemRecord { + return { + id: 'att-1', + groupId: 'group-1', + fullName: 'Ana Pérez', + email: null, + phone: null, + guardianName: null, + guardianPhone: null, + notes: null, + notifyToken: null, + createdAt: new Date('2026-08-01T10:00:00.000Z'), + updatedAt: new Date('2026-08-01T10:00:00.000Z'), + attendances: [], + payments: [], + ...overrides, + }; +} + +const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`); + +describe('toAttendeeListItemDto', () => { + it('invierte la asistencia para que la clase más reciente quede a la derecha', () => { + const dto = toAttendeeListItemDto( + record({ + // Llega de más reciente a más antigua. + attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }], + }), + ); + + expect(dto.recentAttendance).toEqual(['ABSENT', 'EXCUSED', 'PRESENT']); + }); + + it('deja la lista vacía cuando no hay ninguna clase registrada', () => { + expect(toAttendeeListItemDto(record()).recentAttendance).toEqual([]); + }); + + it('no inventa cobro cuando no hay pagos', () => { + expect(toAttendeeListItemDto(record()).payment).toBeNull(); + }); + + it('arranca en cero los pagos impagos y descarta los cancelados', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'CANCELLED', dueDate: day('2026-01-05') }, + { status: 'PAID', dueDate: day('2026-08-10') }, + { status: 'PENDING', dueDate: day('2026-09-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'PENDING', dueDate: '2026-09-10T00:00:00.000Z' }); + }); + + it('manda el impago más antiguo: los días de atraso son los que hay que ver', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'PENDING', dueDate: day('2026-09-10') }, + { status: 'OVERDUE', dueDate: day('2026-04-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'OVERDUE', dueDate: '2026-04-10T00:00:00.000Z' }); + }); + + it('cae al último pago cerrado cuando no queda nada impago', () => { + const dto = toAttendeeListItemDto( + record({ + payments: [ + { status: 'PAID', dueDate: day('2026-08-10') }, + { status: 'PAID', dueDate: day('2026-09-10') }, + ], + }), + ); + + expect(dto.payment).toEqual({ status: 'PAID', dueDate: '2026-09-10T00:00:00.000Z' }); + }); + + it('conserva los campos del DTO plano', () => { + const dto = toAttendeeListItemDto(record({ phone: '22222222' })); + + expect(dto.fullName).toBe('Ana Pérez'); + expect(dto.phone).toBe('22222222'); + expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z'); + }); +}); diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index ca49895..1aa7cb0 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { Hono } from 'hono'; mock.module('@/lib/prisma', () => ({ @@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees'; const app = new Hono(); app.route('/attendees', attendeesRoutes); -const attendee = { +const attendeeRow = { id: 'attendee-1', groupId: 'group-1', fullName: 'Ana Pérez', @@ -32,6 +33,13 @@ const attendee = { updatedAt: new Date('2026-08-01T10:00:00.000Z'), }; +// Lo que devuelve el mock de Prisma: la fila más las relaciones del resumen. +const attendee = { + ...attendeeRow, + attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }], + payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }], +}; + describe('attendees routes', () => { beforeEach(() => { vi.clearAllMocks(); @@ -47,9 +55,13 @@ describe('attendees routes', () => { expect(await res.json()).toEqual({ data: [ { - ...attendee, - createdAt: attendee.createdAt.toISOString(), - updatedAt: attendee.updatedAt.toISOString(), + ...attendeeRow, + createdAt: attendeeRow.createdAt.toISOString(), + updatedAt: attendeeRow.updatedAt.toISOString(), + // La consulta viene de más reciente a más antigua; la fila los + // muestra al revés, con la clase más reciente a la derecha. + recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'], + payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' }, }, ], pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 }, @@ -58,6 +70,19 @@ describe('attendees routes', () => { skip: 10, take: 10, orderBy: { createdAt: 'desc' }, + include: { + attendances: { + orderBy: { classSession: { startsAt: 'desc' } }, + take: RECENT_ATTENDANCE_LIMIT, + select: { status: true }, + }, + payments: { + where: { status: { not: 'CANCELLED' } }, + orderBy: { dueDate: 'desc' }, + take: 3, + select: { status: true, dueDate: true }, + }, + }, }); expect(prisma.attendee.count).toHaveBeenCalledWith(); }); diff --git a/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx new file mode 100644 index 0000000..f0e7c66 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx @@ -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 ( +
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 +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx new file mode 100644 index 0000000..e378450 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx @@ -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 ` + + {isOpen ? ( + + ) : null} + + ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx b/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx new file mode 100644 index 0000000..75b2375 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx @@ -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 = { + 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 ( +
+
+ +
+
+ ) + } + + if (historyFailed) { + return ( +
+

+ No pudimos cargar la asistencia de este miembro. +

+
+ ) + } + + const sessions = history?.sessions ?? [] + + if (sessions.length === 0) { + return ( +
+

+ Todavía no hay clases registradas. +

+
+ ) + } + + const visible = visibleSessions(sessions, showAll) + const hasMore = sessions.length > HISTORY_PREVIEW + const isCapped = sessions.length >= HISTORY_LIMIT + + return ( +
+
    + {visible.map((session) => { + const Icon = iconFor(session.status) + return ( +
  • + + {formatSessionShortDate(session.startsAt)} + + + +
  • + ) + })} +
+ + {showAll && isCapped ? ( +

+ El historial guarda las últimas {HISTORY_LIMIT} clases. +

+ ) : null} + + {hasMore ? ( +
+ +
+ ) : null} +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx new file mode 100644 index 0000000..70bd0b7 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx @@ -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 ( +
+ + + + +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx new file mode 100644 index 0000000..f5fbee8 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx @@ -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 ( +
+
+ {phone && phoneLabel ? ( +
+ + {/* La confirmación visible no se anuncia sola: va en una región viva + aparte para no ensuciar el nombre accesible del botón. */} + + {copied ? 'Teléfono copiado al portapapeles' : ''} + +
+ ) : null} + + {email ? ( + + {email} + + ) : null} + + {notes ? ( +

+ {notes} +

+ ) : null} +
+
+ ) +} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx b/apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx similarity index 65% rename from apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx rename to apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx index c6ee77f..1ca56eb 100644 --- a/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx @@ -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(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 {children} diff --git a/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx b/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx new file mode 100644 index 0000000..e73085a --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx @@ -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(null) + + if (attendeePending) { + return ( +
+ +
+ ) + } + + if (attendeeFailed || !attendee) { + return ( +
+ {/* 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`. */} +

Miembro no encontrado

+

+ No se pudo cargar la información de este miembro. +

+ +
+ ) + } + + return ( +
+
+ +
+ +
+

+ {attendee.fullName} +

+

+ Miembro desde {formatMemberSince(attendee.createdAt)} +

+
+ +
+ +
+ + {/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más + arriba de Asistencia; el layout no se toca. */} +
+ + + +
+ + +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx b/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx new file mode 100644 index 0000000..5b0bffa --- /dev/null +++ b/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx @@ -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 +}) { + const { + attendee, + groupName, + firstWaitlistEntry, + waitlistTotal, + waitlistPending, + isSubmittingRemoval, + isRemoveDialogOpen, + closeRemoveDialog, + confirmRemoveAttendee, + } = useAttendeeDetail() + + const wasOpen = useRef(false) + const contentRef = useRef(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 ( + +
+
    + {consequences.map(({ icon: Icon, key, text }) => ( +
  • +
  • + ))} +
+ +

+ Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos. +

+ + {canPromote && firstWaitlistEntry ? ( +
+

+ Si lo quitás, podés darle el lugar a{' '} + {firstWaitlistEntry.fullName}, el primero + de la lista de espera. +

+ +
+ ) : null} + +
+ + {/* 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. */} + +
+
+
+ ) +} + +/** 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) { + 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('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) +} diff --git a/apps/web/src/features/attendee-detail/Section.tsx b/apps/web/src/features/attendee-detail/Section.tsx new file mode 100644 index 0000000..6dcceb3 --- /dev/null +++ b/apps/web/src/features/attendee-detail/Section.tsx @@ -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 ( +
+
+

+ {title} +

+ {trailing ? ( +
+ {trailing} +
+ ) : null} +
+
{children}
+
+ ) +} diff --git a/apps/web/src/features/attendee-detail/actionButton.ts b/apps/web/src/features/attendee-detail/actionButton.ts new file mode 100644 index 0000000..be2fb81 --- /dev/null +++ b/apps/web/src/features/attendee-detail/actionButton.ts @@ -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' diff --git a/apps/web/src/features/attendee-detail/attendance.ts b/apps/web/src/features/attendee-detail/attendance.ts new file mode 100644 index 0000000..0d585aa --- /dev/null +++ b/apps/web/src/features/attendee-detail/attendance.ts @@ -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)}` +} diff --git a/apps/web/src/features/attendee-detail/useCopyToClipboard.ts b/apps/web/src/features/attendee-detail/useCopyToClipboard.ts new file mode 100644 index 0000000..bb59666 --- /dev/null +++ b/apps/web/src/features/attendee-detail/useCopyToClipboard.ts @@ -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 | 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 } +} diff --git a/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx b/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx deleted file mode 100644 index cea2ad4..0000000 --- a/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx +++ /dev/null @@ -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 = { - good: 'bg-success', - mid: 'bg-warning', - low: 'bg-danger', - none: 'bg-border', -} - -const valueTone: Record = { - good: 'text-success', - mid: 'text-warning', - low: 'text-danger', - none: 'text-foreground/40', -} - -export function AttendeeAttendanceStats() { - const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail() - - if (attendeeStatsPending) { - return ( -
- -
- ) - } - - if (attendeeStatsFailed || !attendeeStats) { - return ( -
- No pudimos cargar la asistencia de este participante. -
- ) - } - - const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats - const tone = rateTone(attendanceRate, totalMarked) - - return ( -
-
-
-

- Asistencia -

-

- {totalMarked > 0 - ? `Sobre ${totalMarked} clases registradas` - : 'Sin clases registradas todavía'} -

-
-

- {totalMarked > 0 ? `${attendanceRate}%` : '—'} -

-
- - - ) -} - -function StatCounter({ - value, - label, - valueClass, -}: { - value: number - label: string - valueClass: string -}) { - return ( -
-
{label}
-
{value}
-
- ) -} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx b/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx deleted file mode 100644 index 6fe07c9..0000000 --- a/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx +++ /dev/null @@ -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 ( -
- -
- ) - } - - if (attendeeFailed || !attendee) { - return ( -
-

Participante no encontrado

-

No se pudo cargar la información de este participante.

- -
- ) - } - - const absenceNotifyUrl = attendee.notifyToken - ? `${window.location.origin}/report-absence/${attendee.notifyToken}` - : null - - return ( -
- - - Volver al grupo - - -
-
- {attendee.fullName.charAt(0).toUpperCase()} -
-
-

{attendee.fullName}

-

- {groupName ? `${groupName} · ` : ''}Incorporado el{' '} - {new Date(attendee.createdAt).toLocaleDateString('es-ES', { - day: 'numeric', - month: 'long', - year: 'numeric', - })} -

-
-
- - - -
- } label="Teléfono"> - {attendee.phone ? ( -
- {formatPhoneDisplay(attendee.phone)} - - - WhatsApp - -
- ) : ( - Sin teléfono - )} -
- - } label="Email"> - {attendee.email ? ( - - {attendee.email} - - ) : ( - Sin email - )} - - - {attendee.guardianName || attendee.guardianPhone ? ( - <> - } label="Responsable"> - - {attendee.guardianName || —} - - - {attendee.guardianPhone ? ( - } label="Tel. Responsable"> -
- {formatPhoneDisplay(attendee.guardianPhone)} - - - -
-
- ) : null} - - ) : null} - - } label="Notas"> - {attendee.notes ? ( - {attendee.notes} - ) : ( - Sin notas - )} - -
- - {absenceNotifyUrl ? ( -
-

Link para avisar ausencias

-
- - {absenceNotifyUrl} - - -
- {attendee.phone ? ( - - - Enviar por WhatsApp - - ) : null} -
- ) : null} - -
- -
- - -
- ) -} diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx index 90b84a6..cfeb5f9 100644 --- a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -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(null) const [selectedPreRegistration, setSelectedPreRegistration] = useState(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, diff --git a/apps/web/src/features/groups/detail/MembersList.tsx b/apps/web/src/features/groups/detail/MembersList.tsx new file mode 100644 index 0000000..1186f30 --- /dev/null +++ b/apps/web/src/features/groups/detail/MembersList.tsx @@ -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 = { + settled: 'text-foreground', + dueSoon: 'font-medium text-warning', + overdue: 'font-semibold text-danger', +} + +function PaymentLabel({ state }: { state: PaymentState }) { + return ( + + {state.kind === 'settled' ? ( + + ) +} + +function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) { + const summary = summarizeAttendance(recent) + + if (summary.recorded === 0) { + return

{summary.label}

+ } + + return ( +
+ {/* Cada punto lleva su propio nombre accesible: el color solo es el + refuerzo visual, no la única forma de saber qué pasó. */} + + {summary.dots.map((status, index) => ( + + ))} + + {summary.label} +
+ ) +} + +function MemberRow({ + attendee, + groupId, +}: { + attendee: AttendeeListItem + groupId: string +}) { + const paymentState = resolvePaymentState(attendee.payment) + + return ( + , 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', + )} + > +
+
+ + {attendee.fullName} + + {paymentState ? : null} +
+ +
+ + ) +} + +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 ( +
    + {attendees.map((attendee) => ( +
  • + +
  • + ))} +
+ ) +} diff --git a/apps/web/src/features/groups/detail/MembersTable.tsx b/apps/web/src/features/groups/detail/MembersTable.tsx deleted file mode 100644 index 764ef30..0000000 --- a/apps/web/src/features/groups/detail/MembersTable.tsx +++ /dev/null @@ -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 ( - - - {/* `border-foreground/10` y no `border`: en dark `--border` es igual a - `primary-soft`, el fondo de la fila, y el separador desaparecería. */} - - - - - - - - {attendees.map((attendee) => ( - 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. */} - - {/* 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. */} - - - - ))} - -
NombreTeléfono - Detalle -
-
-
- {attendee.fullName.charAt(0).toUpperCase()} -
- {/* `truncate` solo recorta lo pintado: el texto completo sigue en - el DOM para lectores de pantalla, y `title` lo muestra al hover. */} - - {attendee.fullName} - -
-
- {attendee.phone ? ( - - {formatPhoneDisplay(attendee.phone)} - - ) : ( - — - )} - - -
- ) -} diff --git a/apps/web/src/features/groups/detail/MembersView.tsx b/apps/web/src/features/groups/detail/MembersView.tsx index 67ee856..e0f1f7f 100644 --- a/apps/web/src/features/groups/detail/MembersView.tsx +++ b/apps/web/src/features/groups/detail/MembersView.tsx @@ -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 ( +
+ +
+ ) +} 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.

@@ -60,13 +105,27 @@ export function MembersView() { ) } - if (filtered.length === 0) { + const filterBar = overdueCount > 0 ? : 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 ( -

- No se encontraron miembros que coincidan con la búsqueda. -
+ <> + {filterBar} +
+ {overdueOnly + ? 'Ningún miembro con pago vencido coincide con la búsqueda.' + : 'No se encontraron miembros que coincidan con la búsqueda.'} +
+ ) } - return + return ( + <> + {filterBar} + + + ) } diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx index 1ec0c5f..2999c26 100644 --- a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -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() {
-
- - setSearchFilter(e.target.value)} - aria-label="Buscar en el listado" - className="h-11 rounded-lg border-transparent pl-9 shadow-xs" - /> -
+ {showSearch ? ( +
+ + setSearchFilter(e.target.value)} + aria-label="Buscar en el listado" + className="h-11 rounded-lg border-transparent pl-9 shadow-xs" + /> +
+ ) : null}
{/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre diff --git a/apps/web/src/features/groups/detail/constants.ts b/apps/web/src/features/groups/detail/constants.ts new file mode 100644 index 0000000..1344b15 --- /dev/null +++ b/apps/web/src/features/groups/detail/constants.ts @@ -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 diff --git a/apps/web/src/features/groups/detail/member-row.ts b/apps/web/src/features/groups/detail/member-row.ts new file mode 100644 index 0000000..763b933 --- /dev/null +++ b/apps/web/src/features/groups/detail/member-row.ts @@ -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' }) +} diff --git a/apps/web/src/routes/_authenticated/groups/$groupId/attendees/$attendeeId.tsx b/apps/web/src/routes/_authenticated/groups/$groupId/attendees/$attendeeId.tsx index 439e9ca..4e3fd36 100644 --- a/apps/web/src/routes/_authenticated/groups/$groupId/attendees/$attendeeId.tsx +++ b/apps/web/src/routes/_authenticated/groups/$groupId/attendees/$attendeeId.tsx @@ -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 ( - + ) }, diff --git a/apps/web/test/attendee-attendance.test.ts b/apps/web/test/attendee-attendance.test.ts new file mode 100644 index 0000000..3adf424 --- /dev/null +++ b/apps/web/test/attendee-attendance.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, test } from 'bun:test' +import type { AttendanceStatus } from '@gruperly/shared' +import { + attendanceStatusLabel, + attendanceSummaryLabel, + classCountLabel, + formatMemberSince, + formatSessionShortDate, + HISTORY_LIMIT, + HISTORY_PREVIEW, + visibleSessions, + type AttendanceSession, +} from '../src/features/attendee-detail/attendance' + +/* La sección de asistencia no lee estos valores de la API: los deriva. Todo lo + que decide qué se muestra —cuántas filas, el plural, el orden— vive acá. */ + +const fecha = (day: number) => new Date(2026, 8, day, 12).toISOString() + +const sesion = ( + day: number, + status: AttendanceStatus | null = 'PRESENT', +): AttendanceSession => ({ + classSessionId: `s-${day}`, + startsAt: fecha(day), + status, +}) + +// El endpoint devuelve de la más antigua a la más reciente. +const historial = [ + sesion(1, 'PRESENT'), + sesion(2, 'ABSENT'), + sesion(3, 'EXCUSED'), + sesion(4, 'PRESENT'), + sesion(5, null), + sesion(6, 'PRESENT'), +] + +describe('classCountLabel', () => { + test('una clase en singular, dos en plural', () => { + expect(classCountLabel(1)).toBe('1 clase') + expect(classCountLabel(2)).toBe('2 clases') + expect(classCountLabel(0)).toBe('0 clases') + }) +}) + +describe('attendanceStatusLabel', () => { + test('el estado se escribe, no se insinúa con el color', () => { + expect(attendanceStatusLabel('PRESENT')).toBe('Asistió') + expect(attendanceStatusLabel('ABSENT')).toBe('Faltó') + expect(attendanceStatusLabel('EXCUSED')).toBe('Faltó (avisó)') + }) + + test('una clase sin marcar no se cuenta como asistencia', () => { + expect(attendanceStatusLabel(null)).toBe('Sin registrar') + }) +}) + +describe('attendanceSummaryLabel', () => { + test('cuenta solo las asistidas de las filas que se ven', () => { + expect(attendanceSummaryLabel(visibleSessions(historial, false))).toBe('2 de 5 clases') + }) + + test('con una sola clase el total va en singular', () => { + expect(attendanceSummaryLabel([sesion(6, 'PRESENT')])).toBe('1 de 1 clase') + }) + + test('sin clases no inventa una asistencia', () => { + expect(attendanceSummaryLabel([])).toBe('0 de 0 clases') + }) +}) + +describe('visibleSessions', () => { + test('la vista previa son las últimas, de la más reciente a la más antigua', () => { + const visibles = visibleSessions(historial, false) + expect(visibles).toHaveLength(HISTORY_PREVIEW) + expect(visibles.map((item) => item.classSessionId)).toEqual([ + 's-6', + 's-5', + 's-4', + 's-3', + 's-2', + ]) + }) + + test('"ver todas" muestra el historial entero, sin inventar clases', () => { + expect(visibleSessions(historial, true)).toHaveLength(historial.length) + expect(visibleSessions([], true)).toEqual([]) + }) + + test('con menos de 5 clases se muestran todas y no hace falta el toggle', () => { + const pocas = historial.slice(0, 3) + expect(visibleSessions(pocas, false)).toHaveLength(3) + }) + + test('el tope es el del endpoint: 20 sesiones', () => { + expect(HISTORY_LIMIT).toBe(20) + }) +}) + +describe('formatSessionShortDate', () => { + test('fecha corta con día de la semana', () => { + expect(formatSessionShortDate(fecha(28))).toBe('lun 28 sep') + }) +}) + +describe('formatMemberSince', () => { + test('fecha abreviada con año, en una sola línea', () => { + expect(formatMemberSince(fecha(18))).toBe('18 sep 2026') + }) +}) diff --git a/apps/web/test/member-row.test.ts b/apps/web/test/member-row.test.ts new file mode 100644 index 0000000..20422f3 --- /dev/null +++ b/apps/web/test/member-row.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, test } from 'bun:test' +import type { AttendeeListItem } from '@gruperly/shared' +import { + byFullName, + isOverdue, + paymentStateLabel, + resolvePaymentState, + summarizeAttendance, +} from '../src/features/groups/detail/member-row' + +/* La fila del listado no lee estos valores de la API: los deriva. Todo lo que + decide qué se muestra —qué día es "vencido", cuántas clases hay— vive acá. */ + +type PaymentStatus = NonNullable['status'] + +const HOY = new Date(2026, 8, 30) // 30 de septiembre de 2026, hora local +const dias = (offset: number) => new Date(2026, 8, 30 + offset) + +const payment = (status: PaymentStatus, dueDate: Date): AttendeeListItem['payment'] => ({ + status, + dueDate: dueDate.toISOString(), +}) + +const member = (fullName: string) => ({ fullName }) as AttendeeListItem +const nombres = (members: AttendeeListItem[]) => members.map((m) => m.fullName) + +describe('resolvePaymentState', () => { + test('sin cobros registrados no inventa un estado', () => { + expect(resolvePaymentState(null, HOY)).toBeNull() + }) + + test('un pago cerrado es "al día"', () => { + expect(resolvePaymentState(payment('PAID', dias(-10)), HOY)).toEqual({ kind: 'settled' }) + expect(resolvePaymentState(payment('PAID', dias(10)), HOY)).toEqual({ kind: 'settled' }) + }) + + test('avisa cuando faltan 3 días o menos, que es el umbral', () => { + expect(resolvePaymentState(payment('PENDING', dias(0)), HOY)).toEqual({ + kind: 'dueSoon', + days: 0, + }) + expect(resolvePaymentState(payment('PENDING', dias(1)), HOY)).toEqual({ + kind: 'dueSoon', + days: 1, + }) + expect(resolvePaymentState(payment('PENDING', dias(3)), HOY)).toEqual({ + kind: 'dueSoon', + days: 3, + }) + }) + + test('más allá del umbral no molesta: todavía no toca pagar', () => { + expect(resolvePaymentState(payment('PENDING', dias(4)), HOY)).toBeNull() + }) + + test('un PENDING ya vencido cuenta como vencido, no como "al día"', () => { + expect(resolvePaymentState(payment('PENDING', dias(-1)), HOY)).toEqual({ + kind: 'overdue', + days: 1, + }) + }) + + test('OVERDUE está vencido aunque su vencimiento siga en el futuro', () => { + expect(resolvePaymentState(payment('OVERDUE', dias(5)), HOY)).toEqual({ + kind: 'overdue', + days: 5, + }) + }) + + test('el atraso va en días calendario, sin horas', () => { + // 23:59 de ayer y 00:01 de hoy son un solo día para el docente: 1 de atraso. + const ayerTarde = new Date(2026, 8, 29, 23, 59) + const hoyTemprano = new Date(2026, 8, 30, 0, 1) + expect(resolvePaymentState(payment('PENDING', ayerTarde), hoyTemprano)).toEqual({ + kind: 'overdue', + days: 1, + }) + }) +}) + +describe('paymentStateLabel', () => { + test('el estado quieto se dice, no se calla', () => { + expect(paymentStateLabel({ kind: 'settled' })).toBe('Al día') + }) + + test('hoy y mañana tienen palabras: "Vence en 0 d" no es español', () => { + expect(paymentStateLabel({ kind: 'dueSoon', days: 0 })).toBe('Vence hoy') + expect(paymentStateLabel({ kind: 'dueSoon', days: 1 })).toBe('Vence mañana') + expect(paymentStateLabel({ kind: 'dueSoon', days: 3 })).toBe('Vence en 3 d') + }) + + test('el atraso va con el número de días', () => { + expect(paymentStateLabel({ kind: 'overdue', days: 12 })).toBe('Vencido · 12 d') + }) +}) + +describe('isOverdue', () => { + test('solo el vencido cuenta como deudor', () => { + expect(isOverdue({ kind: 'overdue', days: 4 })).toBe(true) + expect(isOverdue({ kind: 'dueSoon', days: 0 })).toBe(false) + expect(isOverdue({ kind: 'settled' })).toBe(false) + expect(isOverdue(null)).toBe(false) + }) +}) + +describe('summarizeAttendance', () => { + test('sin clases registradas dice "Sin clases aún"', () => { + expect(summarizeAttendance([])).toEqual({ + dots: [], + attended: 0, + recorded: 0, + label: 'Sin clases aún', + }) + }) + + test('cuenta asistidas sobre las registradas de la ventana', () => { + const summary = summarizeAttendance(['PRESENT', 'ABSENT', 'EXCUSED', 'PRESENT', 'PRESENT']) + expect(summary.attended).toBe(3) + expect(summary.recorded).toBe(5) + expect(summary.label).toBe('3 de 5 clases') + }) + + test('"clases" concuerda en singular', () => { + expect(summarizeAttendance(['PRESENT']).label).toBe('1 de 1 clase') + }) + + test('no rellena con puntos vacíos cuando hay menos de 5 clases', () => { + expect(summarizeAttendance(['ABSENT', 'PRESENT']).dots).toEqual(['ABSENT', 'PRESENT']) + }) + + test('el aviso cuenta como clase registrada pero no como asistencia', () => { + const summary = summarizeAttendance(['EXCUSED']) + expect(summary.recorded).toBe(1) + expect(summary.attended).toBe(0) + }) +}) + +describe('byFullName', () => { + test('ordena alfabéticamente sin depender de mayúsculas ni acentos', () => { + const sueltos = [member('Zoe Ruiz'), member('ángel Díaz'), member('Bruno Díaz'), member('Ana López')] + + expect(nombres([...sueltos].sort(byFullName))).toEqual([ + 'Ana López', + 'ángel Díaz', + 'Bruno Díaz', + 'Zoe Ruiz', + ]) + }) +}) diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index 7833e50..45b108c 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -1,5 +1,7 @@ import { z } from 'zod'; +import { attendanceStatusSchema } from './attendance.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; +import { paymentStatusSchema } from './payments.js'; import { GroupWaitlistEntryDtoSchema } from './waitlist.js'; const isoDateTimeSchema = z.string().datetime(); @@ -7,6 +9,11 @@ const pageSchema = createPageSchema(); const pageSizeSchema = createPageSizeSchema(10); const paginationSchema = createPaginationSchema(); +/* Cuántas clases recientes viajan por miembro en el listado. Es el tamaño de la + tira de puntos del roster, no una ventana de análisis: la analítica pide + HISTORY_SESSIONS_LIMIT clases aparte. */ +export const RECENT_ATTENDANCE_LIMIT = 5; + export const AttendeeDtoSchema = z.object({ id: z.string(), groupId: z.string(), @@ -41,8 +48,33 @@ export const AttendeeQuerySchema = z.object({ }); export type AttendeeQuery = z.output; +/** + * Cobro del período vigente, tal como está en la base: sin columna + * desnormalizada y sin veredicto calculado. El backend devuelve el pago + * impago más reciente; el cliente decide cómo presentarlo. + */ +export const AttendeePaymentSummarySchema = z.object({ + status: paymentStatusSchema, + dueDate: isoDateTimeSchema, +}); +export type AttendeePaymentSummary = z.output; + +/** + * Item del listado de miembros: `AttendeeDto` más el resumen que la fila + * necesita para no vaciarse de datos. Es un superconjunto, así que todo + * consumidor del DTO plano sigue sirviéndose sin cambios; solo los listados + * verían estos dos campos extra. + */ +export const AttendeeListItemSchema = AttendeeDtoSchema.extend({ + /** Últimas clases de más antigua a más reciente. Vacío si nunca se registró ninguna. */ + recentAttendance: z.array(attendanceStatusSchema).max(RECENT_ATTENDANCE_LIMIT), + /** `null` si no hay ningún cobro impago registrado. */ + payment: AttendeePaymentSummarySchema.nullable(), +}); +export type AttendeeListItem = z.output; + export const AttendeeListSchema = z.object({ - data: z.array(AttendeeDtoSchema), + data: z.array(AttendeeListItemSchema), pagination: paginationSchema, }); export type AttendeeList = z.output;