development #14
@@ -1,10 +1,10 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
|
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 { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
import { toAttendeeListItemDto } from '../../lib/helpers';
|
||||||
|
|
||||||
type ListAttendeesDeps = {
|
type ListAttendeesDeps = {
|
||||||
db?: Pick<PrismaClient, 'attendee'>;
|
db?: Pick<PrismaClient, 'attendee'>;
|
||||||
@@ -18,18 +18,37 @@ export class ListAttendees {
|
|||||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||||
|
|
||||||
const [records, total] = await Promise.all([
|
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({
|
db.attendee.findMany({
|
||||||
...(where ? { where } : {}),
|
...(where ? { where } : {}),
|
||||||
skip: getPaginationOffset(query),
|
skip: getPaginationOffset(query),
|
||||||
take: query.pageSize,
|
take: query.pageSize,
|
||||||
orderBy: { createdAt: 'desc' },
|
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(),
|
where ? db.attendee.count({ where }) : db.attendee.count(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)),
|
data: records.map((record) => toAttendeeListItemDto(record)),
|
||||||
pagination: getPaginationMetadata(query, total),
|
pagination: getPaginationMetadata(query, total),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { AttendeeDto } from '@gruperly/shared';
|
import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||||
|
|
||||||
export type AttendeeRecord = {
|
export type AttendeeRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -14,6 +14,15 @@ export type AttendeeRecord = {
|
|||||||
updatedAt: Date;
|
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<AttendeeListItem['payment']>['status'];
|
||||||
|
dueDate: Date;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
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.
|
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
const db = {
|
const db = {
|
||||||
@@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
|||||||
notes: null,
|
notes: null,
|
||||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||||
|
attendances: [],
|
||||||
|
payments: [],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
prisma.attendee.count.mockResolvedValue(1);
|
prisma.attendee.count.mockResolvedValue(1);
|
||||||
@@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
expect(data.data.length).toBe(1);
|
expect(data.data.length).toBe(1);
|
||||||
expect(data.data[0].fullName).toBe('Ana García');
|
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({
|
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
||||||
where: { groupId: 'group-1' },
|
where: { groupId: 'group-1' },
|
||||||
skip: 0,
|
skip: 0,
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: 'desc' },
|
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 },
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
98
apps/backend/test/attendees-list-item.test.ts
Normal file
98
apps/backend/test/attendees-list-item.test.ts
Normal file
@@ -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> = {},
|
||||||
|
): 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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
mock.module('@/lib/prisma', () => ({
|
mock.module('@/lib/prisma', () => ({
|
||||||
@@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees';
|
|||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
app.route('/attendees', attendeesRoutes);
|
app.route('/attendees', attendeesRoutes);
|
||||||
|
|
||||||
const attendee = {
|
const attendeeRow = {
|
||||||
id: 'attendee-1',
|
id: 'attendee-1',
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Ana Pérez',
|
fullName: 'Ana Pérez',
|
||||||
@@ -32,6 +33,13 @@ const attendee = {
|
|||||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
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', () => {
|
describe('attendees routes', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
@@ -47,9 +55,13 @@ describe('attendees routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
...attendee,
|
...attendeeRow,
|
||||||
createdAt: attendee.createdAt.toISOString(),
|
createdAt: attendeeRow.createdAt.toISOString(),
|
||||||
updatedAt: attendee.updatedAt.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 },
|
pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 },
|
||||||
@@ -58,6 +70,19 @@ describe('attendees routes', () => {
|
|||||||
skip: 10,
|
skip: 10,
|
||||||
take: 10,
|
take: 10,
|
||||||
orderBy: { createdAt: 'desc' },
|
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();
|
expect(prisma.attendee.count).toHaveBeenCalledWith();
|
||||||
});
|
});
|
||||||
|
|||||||
91
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
91
apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { useId, useState } from 'react'
|
||||||
|
import { Check, ChevronDown, Copy, MessageCircle } from 'lucide-react'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { ACTION_BUTTON_CLASS } from './actionButton'
|
||||||
|
import { SECTION_TITLE_CLASS, Section } from './Section'
|
||||||
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
|
|
||||||
|
export function AbsenceLinkSection() {
|
||||||
|
const { attendee } = useAttendeeDetail()
|
||||||
|
const { copied, copy } = useCopyToClipboard()
|
||||||
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
|
const panelId = useId()
|
||||||
|
|
||||||
|
const token = attendee?.notifyToken
|
||||||
|
const url = token ? `${window.location.origin}/report-absence/${token}` : null
|
||||||
|
if (!attendee || !url) return null
|
||||||
|
|
||||||
|
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
|
||||||
|
const shareUrl = phoneDigits
|
||||||
|
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
||||||
|
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
|
||||||
|
)}`
|
||||||
|
: null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section
|
||||||
|
title={
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsOpen((value) => !value)}
|
||||||
|
aria-expanded={isOpen}
|
||||||
|
aria-controls={panelId}
|
||||||
|
className={cn(
|
||||||
|
SECTION_TITLE_CLASS,
|
||||||
|
'flex min-h-11 w-full items-center gap-1.5 text-left',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Link de ausencias
|
||||||
|
<ChevronDown
|
||||||
|
className={cn('size-4 transition-transform', isOpen && 'rotate-180')}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y
|
||||||
|
el texto de "Link copiado" no se pierde al plegar y desplegar. */}
|
||||||
|
<div id={panelId} hidden={!isOpen}>
|
||||||
|
<div className="pt-1">
|
||||||
|
<p className="text-sm text-foreground">
|
||||||
|
Mandales este link para que avisen cuando no puedan venir.
|
||||||
|
</p>
|
||||||
|
<div className="mt-2.5 flex flex-col gap-2 sm:flex-row">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => copy(url)}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<Copy className="size-4" aria-hidden="true" />
|
||||||
|
Copiar link
|
||||||
|
</button>
|
||||||
|
{shareUrl ? (
|
||||||
|
<a
|
||||||
|
href={shareUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-4" aria-hidden="true" />
|
||||||
|
Enviar por WhatsApp
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p
|
||||||
|
aria-live="polite"
|
||||||
|
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<>
|
||||||
|
<Check className="size-3.5" aria-hidden="true" />
|
||||||
|
Link copiado
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
120
apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
import { useEffect, useId, useRef, useState } from 'react'
|
||||||
|
import type { KeyboardEvent, RefObject } from 'react'
|
||||||
|
import { Ellipsis, UserMinus } from 'lucide-react'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
const ITEM_CLASS =
|
||||||
|
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
|
|
||||||
|
/** Menú "⋯" de la ficha del miembro.
|
||||||
|
*
|
||||||
|
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de
|
||||||
|
* regenerar el token de ausencias, así que la opción no se muestra antes que
|
||||||
|
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
|
||||||
|
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
|
||||||
|
* lista de abajo.
|
||||||
|
*
|
||||||
|
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
|
||||||
|
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
|
||||||
|
export function AttendeeActionsMenu({
|
||||||
|
triggerRef,
|
||||||
|
}: {
|
||||||
|
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
|
||||||
|
* foco cuando se cierra. */
|
||||||
|
triggerRef: RefObject<HTMLButtonElement | null>
|
||||||
|
}) {
|
||||||
|
const { openRemoveDialog } = useAttendeeDetail()
|
||||||
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
|
const itemRef = useRef<HTMLButtonElement>(null)
|
||||||
|
const menuId = useId()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) itemRef.current?.focus()
|
||||||
|
}, [isOpen])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return
|
||||||
|
const handlePointerDown = (event: PointerEvent) => {
|
||||||
|
const target = event.target as Node
|
||||||
|
if (menuRef.current?.contains(target) || triggerRef.current?.contains(target)) return
|
||||||
|
setIsOpen(false)
|
||||||
|
}
|
||||||
|
document.addEventListener('pointerdown', handlePointerDown)
|
||||||
|
return () => document.removeEventListener('pointerdown', handlePointerDown)
|
||||||
|
}, [isOpen, triggerRef])
|
||||||
|
|
||||||
|
const close = (restoreFocus = false) => {
|
||||||
|
setIsOpen(false)
|
||||||
|
if (restoreFocus) triggerRef.current?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.stopPropagation()
|
||||||
|
close(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (event.key === 'Tab') {
|
||||||
|
close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return
|
||||||
|
|
||||||
|
event.preventDefault()
|
||||||
|
const items = Array.from(
|
||||||
|
menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [],
|
||||||
|
)
|
||||||
|
if (items.length === 0) return
|
||||||
|
const current = items.indexOf(document.activeElement as HTMLElement)
|
||||||
|
const next =
|
||||||
|
event.key === 'Home'
|
||||||
|
? 0
|
||||||
|
: event.key === 'End'
|
||||||
|
? items.length - 1
|
||||||
|
: (current + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
|
||||||
|
items[next]?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative shrink-0">
|
||||||
|
<button
|
||||||
|
ref={triggerRef}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsOpen((value) => !value)}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
aria-expanded={isOpen}
|
||||||
|
aria-controls={isOpen ? menuId : undefined}
|
||||||
|
aria-label="Más acciones"
|
||||||
|
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<Ellipsis className="size-5" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isOpen ? (
|
||||||
|
<div
|
||||||
|
ref={menuRef}
|
||||||
|
id={menuId}
|
||||||
|
role="menu"
|
||||||
|
aria-label="Acciones del miembro"
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
ref={itemRef}
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className={ITEM_CLASS}
|
||||||
|
onClick={() => {
|
||||||
|
close()
|
||||||
|
openRemoveDialog()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<UserMinus className="size-4 shrink-0 text-danger" aria-hidden="true" />
|
||||||
|
Quitar del grupo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import type { AttendanceStatus } from '@gruperly/shared'
|
||||||
|
import { Check, ChevronDown, Loader2, Megaphone, Minus, X } from 'lucide-react'
|
||||||
|
import type { LucideIcon } from 'lucide-react'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import {
|
||||||
|
attendanceStatusClass,
|
||||||
|
attendanceStatusLabel,
|
||||||
|
attendanceSummaryLabel,
|
||||||
|
formatSessionShortDate,
|
||||||
|
HISTORY_LIMIT,
|
||||||
|
HISTORY_PREVIEW,
|
||||||
|
visibleSessions,
|
||||||
|
type AttendanceSession,
|
||||||
|
} from './attendance'
|
||||||
|
import { Section } from './Section'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
|
||||||
|
PRESENT: Check,
|
||||||
|
ABSENT: X,
|
||||||
|
EXCUSED: Megaphone,
|
||||||
|
UNMARKED: Minus,
|
||||||
|
}
|
||||||
|
|
||||||
|
function iconFor(status: AttendanceSession['status']): LucideIcon {
|
||||||
|
return STATUS_ICONS[status ?? 'UNMARKED']
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AttendeeAttendanceSection() {
|
||||||
|
const { history, historyPending, historyFailed } = useAttendeeDetail()
|
||||||
|
const [showAll, setShowAll] = useState(false)
|
||||||
|
|
||||||
|
if (historyPending) {
|
||||||
|
return (
|
||||||
|
<Section title="Asistencia" trailing="—">
|
||||||
|
<div className="flex items-center justify-center py-5">
|
||||||
|
<Loader2 className="size-5 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (historyFailed) {
|
||||||
|
return (
|
||||||
|
<Section title="Asistencia">
|
||||||
|
<p className="py-3 text-sm text-foreground">
|
||||||
|
No pudimos cargar la asistencia de este miembro.
|
||||||
|
</p>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessions = history?.sessions ?? []
|
||||||
|
|
||||||
|
if (sessions.length === 0) {
|
||||||
|
return (
|
||||||
|
<Section title="Asistencia">
|
||||||
|
<p className="py-3 text-sm text-foreground">
|
||||||
|
Todavía no hay clases registradas.
|
||||||
|
</p>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const visible = visibleSessions(sessions, showAll)
|
||||||
|
const hasMore = sessions.length > HISTORY_PREVIEW
|
||||||
|
const isCapped = sessions.length >= HISTORY_LIMIT
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Asistencia" trailing={attendanceSummaryLabel(visible)}>
|
||||||
|
<ul className="divide-y divide-border/60">
|
||||||
|
{visible.map((session) => {
|
||||||
|
const Icon = iconFor(session.status)
|
||||||
|
return (
|
||||||
|
<li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2.5">
|
||||||
|
<span className="truncate text-sm text-primary">
|
||||||
|
{formatSessionShortDate(session.startsAt)}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'flex shrink-0 items-center gap-1.5 text-xs font-semibold',
|
||||||
|
attendanceStatusClass(session.status),
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="size-3.5" aria-hidden="true" />
|
||||||
|
{attendanceStatusLabel(session.status)}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{showAll && isCapped ? (
|
||||||
|
<p className="pt-2 text-xs text-foreground">
|
||||||
|
El historial guarda las últimas {HISTORY_LIMIT} clases.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{hasMore ? (
|
||||||
|
<div className="mt-1 flex justify-end">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setShowAll((value) => !value)}
|
||||||
|
aria-expanded={showAll}
|
||||||
|
className="h-11 gap-1 px-2 text-sm text-accent hover:text-accent-strong"
|
||||||
|
>
|
||||||
|
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
|
||||||
|
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { MessageCircle, Phone } from 'lucide-react'
|
||||||
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import { ACTION_BUTTON_CLASS } from './actionButton'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
export function AttendeeContactActions() {
|
||||||
|
const { attendee } = useAttendeeDetail()
|
||||||
|
|
||||||
|
const phone = attendee?.phone
|
||||||
|
if (!phone) return null
|
||||||
|
|
||||||
|
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos.
|
||||||
|
const digits = phone.replace(/\D/g, '')
|
||||||
|
const label = formatPhoneDisplay(phone) ?? phone
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex gap-2.5">
|
||||||
|
<a
|
||||||
|
href={`https://wa.me/${digits}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
aria-label={`Abrir WhatsApp con ${label}`}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-4 text-accent" aria-hidden="true" />
|
||||||
|
WhatsApp
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`tel:${digits}`}
|
||||||
|
aria-label={`Llamar a ${label}`}
|
||||||
|
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||||
|
>
|
||||||
|
<Phone className="size-4 text-accent" aria-hidden="true" />
|
||||||
|
Llamar
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { Check, Copy, Mail } from 'lucide-react'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { Section } from './Section'
|
||||||
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
|
|
||||||
|
const ROW_CLASS =
|
||||||
|
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
|
|
||||||
|
export function AttendeeContactSection() {
|
||||||
|
const { attendee } = useAttendeeDetail()
|
||||||
|
const { copied, copy } = useCopyToClipboard()
|
||||||
|
|
||||||
|
if (!attendee) return null
|
||||||
|
|
||||||
|
const phone = attendee.phone
|
||||||
|
const phoneLabel = formatPhoneDisplay(phone)
|
||||||
|
const { email, notes } = attendee
|
||||||
|
// Sin datos no hay sección: no se dibujan filas con "Sin email"/"Sin notas".
|
||||||
|
if (!phoneLabel && !email && !notes) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Contacto">
|
||||||
|
<div className="divide-y divide-border/60">
|
||||||
|
{phone && phoneLabel ? (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => copy(phone)}
|
||||||
|
className={cn(ROW_CLASS, 'min-w-0 flex-1 text-left')}
|
||||||
|
>
|
||||||
|
<span className="truncate text-base text-primary">{phoneLabel}</span>
|
||||||
|
<span className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-foreground">
|
||||||
|
{copied ? (
|
||||||
|
<Check className="size-4 text-success" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Copy className="size-4" aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
{copied ? 'Copiado' : 'Copiar'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{/* La confirmación visible no se anuncia sola: va en una región viva
|
||||||
|
aparte para no ensuciar el nombre accesible del botón. */}
|
||||||
|
<span aria-live="polite" className="sr-only">
|
||||||
|
{copied ? 'Teléfono copiado al portapapeles' : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{email ? (
|
||||||
|
<a href={`mailto:${email}`} className={ROW_CLASS}>
|
||||||
|
<span className="truncate text-base text-primary">{email}</span>
|
||||||
|
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{notes ? (
|
||||||
|
<p className="whitespace-pre-line py-2.5 text-sm leading-relaxed text-primary">
|
||||||
|
{notes}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,10 +2,9 @@ import { createContext, useContext, useState } from 'react'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared'
|
import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
import { useToast } from '../../../components/ui'
|
import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
|
||||||
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api'
|
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
|
||||||
|
|
||||||
type AttendeeDetailContextValue = {
|
type AttendeeDetailContextValue = {
|
||||||
groupId: string
|
groupId: string
|
||||||
@@ -13,18 +12,17 @@ type AttendeeDetailContextValue = {
|
|||||||
attendee: AttendeeDto | undefined
|
attendee: AttendeeDto | undefined
|
||||||
attendeePending: boolean
|
attendeePending: boolean
|
||||||
attendeeFailed: boolean
|
attendeeFailed: boolean
|
||||||
attendeeStats: AttendeeStats | undefined
|
history: AttendeeHistory | undefined
|
||||||
attendeeStatsPending: boolean
|
historyPending: boolean
|
||||||
attendeeStatsFailed: boolean
|
historyFailed: boolean
|
||||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
waitlistTotal: number
|
waitlistTotal: number
|
||||||
waitlistPending: boolean
|
waitlistPending: boolean
|
||||||
isRemoveModalOpen: boolean
|
isRemoveDialogOpen: boolean
|
||||||
openRemoveModal: () => void
|
openRemoveDialog: () => void
|
||||||
closeRemoveModal: () => void
|
closeRemoveDialog: () => void
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
isSubmittingRemoval: boolean
|
isSubmittingRemoval: boolean
|
||||||
copyAbsenceNotifyUrl: (url: string) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||||
@@ -38,9 +36,8 @@ export function AttendeeDetailProvider({
|
|||||||
attendeeId: string
|
attendeeId: string
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
}) {
|
}) {
|
||||||
const toast = useToast()
|
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false)
|
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
queryKey: ['group', groupId],
|
queryKey: ['group', groupId],
|
||||||
@@ -54,16 +51,20 @@ export function AttendeeDetailProvider({
|
|||||||
enabled: Boolean(groupId && attendeeId),
|
enabled: Boolean(groupId && attendeeId),
|
||||||
})
|
})
|
||||||
|
|
||||||
const attendeeStatsQuery = useQuery({
|
// Misma clave que usa la pantalla de estadísticas: las dos leen el mismo
|
||||||
queryKey: ['attendee-stats', groupId, attendeeId],
|
// historial y no se pisan la caché.
|
||||||
queryFn: () => getAttendeeStats(groupId, attendeeId),
|
const historyQuery = useQuery({
|
||||||
|
queryKey: ['attendee-history', groupId, attendeeId],
|
||||||
|
queryFn: () => getAttendeeHistory(groupId, attendeeId),
|
||||||
enabled: Boolean(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({
|
const waitlistQuery = useQuery({
|
||||||
queryKey: ['group-waitlist', groupId],
|
queryKey: ['group-waitlist', groupId],
|
||||||
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
||||||
enabled: Boolean(groupId && isRemoveModalOpen),
|
enabled: Boolean(groupId && isRemoveDialogOpen),
|
||||||
})
|
})
|
||||||
|
|
||||||
const waitlistEntries = waitlistQuery.data?.data ?? []
|
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||||
@@ -73,38 +74,31 @@ export function AttendeeDetailProvider({
|
|||||||
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||||
groupId,
|
groupId,
|
||||||
onRemoved: () => {
|
onRemoved: () => {
|
||||||
setIsRemoveModalOpen(false)
|
setIsRemoveDialogOpen(false)
|
||||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
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 = {
|
const value: AttendeeDetailContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
groupName: groupQuery.data?.name,
|
groupName: groupQuery.data?.name,
|
||||||
attendee: attendeeQuery.data,
|
attendee: attendeeQuery.data,
|
||||||
attendeePending: attendeeQuery.isPending,
|
attendeePending: attendeeQuery.isPending,
|
||||||
attendeeFailed: attendeeQuery.isError,
|
attendeeFailed: attendeeQuery.isError,
|
||||||
attendeeStats: attendeeStatsQuery.data,
|
history: historyQuery.data,
|
||||||
attendeeStatsPending: attendeeStatsQuery.isPending,
|
historyPending: historyQuery.isPending,
|
||||||
attendeeStatsFailed: attendeeStatsQuery.isError,
|
historyFailed: historyQuery.isError,
|
||||||
firstWaitlistEntry,
|
firstWaitlistEntry,
|
||||||
waitlistTotal,
|
waitlistTotal,
|
||||||
waitlistPending: waitlistQuery.isPending,
|
waitlistPending: waitlistQuery.isPending,
|
||||||
isRemoveModalOpen,
|
isRemoveDialogOpen,
|
||||||
openRemoveModal: () => setIsRemoveModalOpen(true),
|
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||||
closeRemoveModal: () => setIsRemoveModalOpen(false),
|
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||||
if (!attendeeQuery.data) return
|
if (!attendeeQuery.data) return
|
||||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||||
},
|
},
|
||||||
isSubmittingRemoval: isRemovingAttendee,
|
isSubmittingRemoval: isRemovingAttendee,
|
||||||
copyAbsenceNotifyUrl,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||||
87
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
87
apps/web/src/features/attendee-detail/AttendeeDetailView.tsx
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { useRef } from 'react'
|
||||||
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
import { AbsenceLinkSection } from './AbsenceLinkSection'
|
||||||
|
import { AttendeeActionsMenu } from './AttendeeActionsMenu'
|
||||||
|
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
|
||||||
|
import { AttendeeContactActions } from './AttendeeContactActions'
|
||||||
|
import { AttendeeContactSection } from './AttendeeContactSection'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||||
|
import { formatMemberSince } from './attendance'
|
||||||
|
|
||||||
|
export function AttendeeDetailView() {
|
||||||
|
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const menuTriggerRef = useRef<HTMLButtonElement>(null)
|
||||||
|
|
||||||
|
if (attendeePending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attendeeFailed || !attendee) {
|
||||||
|
return (
|
||||||
|
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
|
||||||
|
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a
|
||||||
|
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no
|
||||||
|
pasa los 4.5:1 que necesita un `text-sm`. */}
|
||||||
|
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
|
||||||
|
<p className="mt-2 text-sm text-primary">
|
||||||
|
No se pudo cargar la información de este miembro.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="mt-4 px-0 text-accent hover:bg-transparent hover:text-accent-strong"
|
||||||
|
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||||
|
>
|
||||||
|
Volver al grupo
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="animate-fade-in">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="flex min-h-11 min-w-0 items-center gap-1.5 rounded-lg py-2 text-sm text-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4 shrink-0" aria-hidden="true" />
|
||||||
|
<span className="truncate">{groupName ?? 'Grupo'}</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<AttendeeActionsMenu triggerRef={menuTriggerRef} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-1">
|
||||||
|
<h1 className="text-balance text-2xl font-bold leading-tight tracking-tight text-primary">
|
||||||
|
{attendee.fullName}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 whitespace-nowrap text-sm text-foreground">
|
||||||
|
Miembro desde {formatMemberSince(attendee.createdAt)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<AttendeeContactActions />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
|
||||||
|
arriba de Asistencia; el layout no se toca. */}
|
||||||
|
<div className="mt-6 space-y-5">
|
||||||
|
<AttendeeAttendanceSection />
|
||||||
|
<AttendeeContactSection />
|
||||||
|
<AbsenceLinkSection />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import type { RefObject } from 'react'
|
||||||
|
import type { LucideIcon } from 'lucide-react'
|
||||||
|
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
|
||||||
|
import { Button, Modal } from '../../components/ui'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
type Consequence = { key: string; icon: LucideIcon; text: string }
|
||||||
|
|
||||||
|
export function ConfirmRemoveAttendeeDialog({
|
||||||
|
returnFocusRef,
|
||||||
|
}: {
|
||||||
|
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */
|
||||||
|
returnFocusRef: RefObject<HTMLButtonElement | null>
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
attendee,
|
||||||
|
groupName,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending,
|
||||||
|
isSubmittingRemoval,
|
||||||
|
isRemoveDialogOpen,
|
||||||
|
closeRemoveDialog,
|
||||||
|
confirmRemoveAttendee,
|
||||||
|
} = useAttendeeDetail()
|
||||||
|
|
||||||
|
const wasOpen = useRef(false)
|
||||||
|
const contentRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isRemoveDialogOpen) {
|
||||||
|
wasOpen.current = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!wasOpen.current) return
|
||||||
|
wasOpen.current = false
|
||||||
|
returnFocusRef.current?.focus()
|
||||||
|
}, [isRemoveDialogOpen, returnFocusRef])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isRemoveDialogOpen) return
|
||||||
|
return trapTabWithin(contentRef)
|
||||||
|
}, [isRemoveDialogOpen])
|
||||||
|
|
||||||
|
if (!attendee) return null
|
||||||
|
|
||||||
|
const waiting = waitlistTotal > 0
|
||||||
|
const canPromote = !waitlistPending && firstWaitlistEntry !== null
|
||||||
|
|
||||||
|
const consequences: Consequence[] = [
|
||||||
|
{
|
||||||
|
key: 'historial',
|
||||||
|
icon: History,
|
||||||
|
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
if (attendee.notifyToken) {
|
||||||
|
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
|
||||||
|
}
|
||||||
|
consequences.push({
|
||||||
|
key: 'lugar',
|
||||||
|
icon: Users,
|
||||||
|
text: waiting
|
||||||
|
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
|
||||||
|
waitlistTotal === 1 ? 'persona' : 'personas'
|
||||||
|
} en lista de espera.`
|
||||||
|
: 'Se libera 1 lugar en el grupo.',
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isRemoveDialogOpen}
|
||||||
|
onClose={closeRemoveDialog}
|
||||||
|
title="Quitar del grupo"
|
||||||
|
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||||
|
maxWidth="sm"
|
||||||
|
>
|
||||||
|
<div ref={contentRef} className="space-y-4">
|
||||||
|
<ul className="space-y-2.5">
|
||||||
|
{consequences.map(({ icon: Icon, key, text }) => (
|
||||||
|
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
|
||||||
|
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||||
|
<span>{text}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p className="text-xs text-foreground">
|
||||||
|
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{canPromote && firstWaitlistEntry ? (
|
||||||
|
<div className="rounded-xl bg-accent-soft p-3.5">
|
||||||
|
<p className="text-sm text-foreground">
|
||||||
|
Si lo quitás, podés darle el lugar a{' '}
|
||||||
|
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
|
||||||
|
de la lista de espera.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={() => confirmRemoveAttendee(true)}
|
||||||
|
disabled={isSubmittingRemoval}
|
||||||
|
className="mt-2.5 w-full gap-2"
|
||||||
|
>
|
||||||
|
{isSubmittingRemoval ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<UserPlus className="size-4" />
|
||||||
|
)}
|
||||||
|
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||||
|
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de
|
||||||
|
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro,
|
||||||
|
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */}
|
||||||
|
<Button
|
||||||
|
onClick={() => confirmRemoveAttendee(false)}
|
||||||
|
disabled={isSubmittingRemoval}
|
||||||
|
className="gap-2 bg-danger text-black hover:bg-danger/90"
|
||||||
|
>
|
||||||
|
{isSubmittingRemoval ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
)}
|
||||||
|
<span>Quitar del grupo</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no
|
||||||
|
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si
|
||||||
|
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con
|
||||||
|
* Escape) lo deja seguir su curso normal. */
|
||||||
|
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== 'Tab') return
|
||||||
|
|
||||||
|
const container = contentRef.current
|
||||||
|
if (!container?.contains(document.activeElement)) return
|
||||||
|
|
||||||
|
const focusable = Array.from(container.querySelectorAll<HTMLElement>('button:not([disabled])'))
|
||||||
|
if (focusable.length === 0) return
|
||||||
|
|
||||||
|
const first = focusable[0]
|
||||||
|
const last = focusable[focusable.length - 1]
|
||||||
|
const active = document.activeElement
|
||||||
|
|
||||||
|
if (event.shiftKey && active === first) {
|
||||||
|
event.preventDefault()
|
||||||
|
last.focus()
|
||||||
|
} else if (!event.shiftKey && active === last) {
|
||||||
|
event.preventDefault()
|
||||||
|
first.focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleKeyDown)
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||||
|
}
|
||||||
40
apps/web/src/features/attendee-detail/Section.tsx
Normal file
40
apps/web/src/features/attendee-detail/Section.tsx
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { useId } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
|
||||||
|
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
|
||||||
|
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
|
||||||
|
|
||||||
|
type SectionProps = {
|
||||||
|
/** Título de la sección. Un string por lo general; un botón cuando la
|
||||||
|
* sección se despliega desde el propio título (ver Link de ausencias). */
|
||||||
|
title: ReactNode
|
||||||
|
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
|
||||||
|
trailing?: ReactNode
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bloque de sección: separador fino sobre el fondo, título chico en
|
||||||
|
* mayúsculas y contenido sin padding propio (el de la pantalla).
|
||||||
|
*
|
||||||
|
* La pantalla se arma apilando secciones en este orden, así que sumar una
|
||||||
|
* nueva (Pagos, por ejemplo) es insertar otro bloque y nada más. */
|
||||||
|
export function Section({ title, trailing, children }: SectionProps) {
|
||||||
|
const headingId = useId()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section aria-labelledby={headingId} className="border-t border-border/70 pt-5">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<h2 id={headingId} className={SECTION_TITLE_CLASS}>
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
{trailing ? (
|
||||||
|
<div className="shrink-0 text-xs font-semibold tabular-nums text-foreground">
|
||||||
|
{trailing}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2.5">{children}</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
8
apps/web/src/features/attendee-detail/actionButton.ts
Normal file
8
apps/web/src/features/attendee-detail/actionButton.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link).
|
||||||
|
*
|
||||||
|
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle
|
||||||
|
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
|
||||||
|
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
|
||||||
|
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
|
||||||
|
export const ACTION_BUTTON_CLASS =
|
||||||
|
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
77
apps/web/src/features/attendee-detail/attendance.ts
Normal file
77
apps/web/src/features/attendee-detail/attendance.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import type { AttendanceHistoryItem } from '@gruperly/shared'
|
||||||
|
|
||||||
|
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
|
||||||
|
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
|
||||||
|
"Ver todas" no promete más de lo que hay. */
|
||||||
|
export const HISTORY_PREVIEW = 5
|
||||||
|
export const HISTORY_LIMIT = 20
|
||||||
|
|
||||||
|
export type AttendanceSession = AttendanceHistoryItem
|
||||||
|
|
||||||
|
export function formatSessionShortDate(iso: string): string {
|
||||||
|
const date = new Date(iso)
|
||||||
|
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
|
||||||
|
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
|
||||||
|
const month = date.toLocaleDateString('es-MX', { month: 'short' })
|
||||||
|
return `${weekday} ${day} ${month}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'PRESENT':
|
||||||
|
return 'Asistió'
|
||||||
|
case 'ABSENT':
|
||||||
|
return 'Faltó'
|
||||||
|
case 'EXCUSED':
|
||||||
|
return 'Faltó (avisó)'
|
||||||
|
default:
|
||||||
|
return 'Sin registrar'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado
|
||||||
|
están pensados como texto sobre superficies oscuras y el verde sobre blanco
|
||||||
|
queda justo por debajo de AA, así que la fila lleva las tres señales. */
|
||||||
|
export function attendanceStatusClass(status: AttendanceSession['status']): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'PRESENT':
|
||||||
|
return 'text-success'
|
||||||
|
case 'ABSENT':
|
||||||
|
return 'text-danger'
|
||||||
|
case 'EXCUSED':
|
||||||
|
return 'text-warning'
|
||||||
|
default:
|
||||||
|
return 'text-foreground'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */
|
||||||
|
export function formatMemberSince(iso: string): string {
|
||||||
|
return new Date(iso).toLocaleDateString('es-MX', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
year: 'numeric',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1 clase" / "2 clases". */
|
||||||
|
export function classCountLabel(count: number): string {
|
||||||
|
return count === 1 ? '1 clase' : `${count} clases`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
|
||||||
|
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
|
||||||
|
* contrario (más antigua → más reciente). */
|
||||||
|
export function visibleSessions(
|
||||||
|
sessions: AttendanceSession[],
|
||||||
|
showAll: boolean,
|
||||||
|
): AttendanceSession[] {
|
||||||
|
const ordered = [...sessions].reverse()
|
||||||
|
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "3 de 5 clases", contando solo las sesiones que se están mostrando. */
|
||||||
|
export function attendanceSummaryLabel(sessions: AttendanceSession[]): string {
|
||||||
|
const present = sessions.filter((session) => session.status === 'PRESENT').length
|
||||||
|
return `${present} de ${classCountLabel(sessions.length)}`
|
||||||
|
}
|
||||||
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal file
33
apps/web/src/features/attendee-detail/useCopyToClipboard.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
const FEEDBACK_MS = 1800
|
||||||
|
|
||||||
|
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
|
||||||
|
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
|
||||||
|
export function useCopyToClipboard() {
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
if (timeoutRef.current) clearTimeout(timeoutRef.current)
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
const copy = (text: string) => {
|
||||||
|
if (!navigator.clipboard) return
|
||||||
|
void navigator.clipboard
|
||||||
|
.writeText(text)
|
||||||
|
.then(() => {
|
||||||
|
setCopied(true)
|
||||||
|
if (timeoutRef.current) clearTimeout(timeoutRef.current)
|
||||||
|
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
|
||||||
|
})
|
||||||
|
// Si el navegador rechaza la escritura no hay nada que confirmar: se
|
||||||
|
// deja el control como estaba en vez de dejar la promesa sin manejar.
|
||||||
|
.catch(() => setCopied(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
return { copied, copy }
|
||||||
|
}
|
||||||
@@ -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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type {
|
import type {
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
|
AttendeeListItem,
|
||||||
GroupDto,
|
GroupDto,
|
||||||
GroupPreRegistrationDto,
|
GroupPreRegistrationDto,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
@@ -33,7 +34,7 @@ type GroupDetailContextValue = {
|
|||||||
groupTitle: string
|
groupTitle: string
|
||||||
groupQueryPending: boolean
|
groupQueryPending: boolean
|
||||||
riskLevel: GroupRiskLevel
|
riskLevel: GroupRiskLevel
|
||||||
attendees: AttendeeDto[]
|
attendees: AttendeeListItem[]
|
||||||
attendeesTotal: number
|
attendeesTotal: number
|
||||||
attendeesPending: boolean
|
attendeesPending: boolean
|
||||||
waitlistEntries: GroupWaitlistEntryDto[]
|
waitlistEntries: GroupWaitlistEntryDto[]
|
||||||
@@ -49,6 +50,9 @@ type GroupDetailContextValue = {
|
|||||||
whatsappMessage: string
|
whatsappMessage: string
|
||||||
searchFilter: string
|
searchFilter: string
|
||||||
setSearchFilter: (value: string) => void
|
setSearchFilter: (value: string) => void
|
||||||
|
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */
|
||||||
|
overdueOnly: boolean
|
||||||
|
setOverdueOnly: (value: boolean) => void
|
||||||
listSection: ListSection
|
listSection: ListSection
|
||||||
setListSection: (value: ListSection) => void
|
setListSection: (value: ListSection) => void
|
||||||
isInviteModalOpen: boolean
|
isInviteModalOpen: boolean
|
||||||
@@ -90,12 +94,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||||
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||||
const [searchFilter, setSearchFilter] = useState('')
|
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
|
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
|
||||||
// limpia para no heredar un filtro sin coincidencias.
|
// pestaña se limpian para no heredar un filtro sin coincidencias.
|
||||||
const setListSection = (value: ListSection) => {
|
const setListSection = (value: ListSection) => {
|
||||||
setListSectionState(value)
|
setListSectionState(value)
|
||||||
setSearchFilter('')
|
setSearchFilter('')
|
||||||
|
setOverdueOnly(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
@@ -313,6 +319,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
whatsappMessage,
|
whatsappMessage,
|
||||||
searchFilter,
|
searchFilter,
|
||||||
setSearchFilter,
|
setSearchFilter,
|
||||||
|
overdueOnly,
|
||||||
|
setOverdueOnly,
|
||||||
listSection,
|
listSection,
|
||||||
setListSection,
|
setListSection,
|
||||||
isInviteModalOpen,
|
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 { 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 { Button } from '../../../components/ui'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
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() {
|
export function MembersView() {
|
||||||
const { groupId, attendees, attendeesPending, searchFilter, openInviteModal } = useGroupDetail()
|
const {
|
||||||
|
groupId,
|
||||||
|
attendees,
|
||||||
|
attendeesPending,
|
||||||
|
searchFilter,
|
||||||
|
overdueOnly,
|
||||||
|
openInviteModal,
|
||||||
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const query = searchFilter.trim().toLowerCase()
|
const query = searchFilter.trim().toLowerCase()
|
||||||
const filtered = query
|
// El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda:
|
||||||
? attendees.filter(
|
// es como la mayoría conoce a los alumnos del grupo.
|
||||||
(a) =>
|
const matchesQuery = (attendee: (typeof attendees)[number]) =>
|
||||||
a.fullName.toLowerCase().includes(query) ||
|
!query ||
|
||||||
(a.phone && a.phone.includes(query)) ||
|
attendee.fullName.toLowerCase().includes(query) ||
|
||||||
(a.email && a.email.toLowerCase().includes(query)),
|
(attendee.phone != null && attendee.phone.includes(query)) ||
|
||||||
)
|
(attendee.email != null && attendee.email.toLowerCase().includes(query))
|
||||||
: attendees
|
|
||||||
|
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) {
|
if (attendeesPending) {
|
||||||
return (
|
return (
|
||||||
@@ -28,9 +76,6 @@ export function MembersView() {
|
|||||||
|
|
||||||
if (attendees.length === 0) {
|
if (attendees.length === 0) {
|
||||||
return (
|
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">
|
<div className="bg-surface px-4 py-10 text-center">
|
||||||
<Users className="mx-auto mb-2 size-10 text-foreground/40" />
|
<Users className="mx-auto mb-2 size-10 text-foreground/40" />
|
||||||
<p className="text-sm font-semibold text-primary">
|
<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 (
|
return (
|
||||||
<div className="py-8 text-center text-sm text-foreground/80">
|
<>
|
||||||
No se encontraron miembros que coincidan con la búsqueda.
|
{filterBar}
|
||||||
</div>
|
<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 { Search } from 'lucide-react'
|
||||||
import { Input } from '../../../components/ui'
|
import { Input } from '../../../components/ui'
|
||||||
|
import { MEMBER_SEARCH_MIN } from './constants'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
import { MembersView } from './MembersView'
|
import { MembersView } from './MembersView'
|
||||||
import { PendingView } from './PendingView'
|
import { PendingView } from './PendingView'
|
||||||
import { SectionChips } from './SectionChips'
|
import { SectionChips } from './SectionChips'
|
||||||
|
|
||||||
export function MembersWaitlistSection() {
|
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 (
|
return (
|
||||||
// Una sola superficie: la lista va directo sobre el lavado, como la info
|
// 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">
|
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
|
||||||
<SectionChips />
|
<SectionChips />
|
||||||
|
|
||||||
<div className="relative w-full sm:w-72 lg:shrink-0">
|
{showSearch ? (
|
||||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
|
<div className="relative w-full sm:w-72 lg:shrink-0">
|
||||||
<Input
|
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
|
||||||
placeholder="Buscar por nombre o teléfono..."
|
<Input
|
||||||
value={searchFilter}
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
onChange={(e) => setSearchFilter(e.target.value)}
|
value={searchFilter}
|
||||||
aria-label="Buscar en el listado"
|
onChange={(e) => setSearchFilter(e.target.value)}
|
||||||
className="h-11 rounded-lg border-transparent pl-9 shadow-xs"
|
aria-label="Buscar en el listado"
|
||||||
/>
|
className="h-11 rounded-lg border-transparent pl-9 shadow-xs"
|
||||||
</div>
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre
|
{/* 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' })
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useParams } from '@tanstack/react-router'
|
import { useParams } from '@tanstack/react-router'
|
||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { AttendeeDetailPage } from '../../../../../features/groups/detail/AttendeeDetailPage'
|
import { AttendeeDetailProvider } from '../../../../../features/attendee-detail/AttendeeDetailProvider'
|
||||||
import { AttendeeDetailProvider } from '../../../../../features/groups/detail/AttendeeDetailProvider'
|
import { AttendeeDetailView } from '../../../../../features/attendee-detail/AttendeeDetailView'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({
|
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({
|
||||||
component: () => {
|
component: () => {
|
||||||
@@ -10,7 +10,7 @@ export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/
|
|||||||
})
|
})
|
||||||
return (
|
return (
|
||||||
<AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}>
|
<AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}>
|
||||||
<AttendeeDetailPage />
|
<AttendeeDetailView />
|
||||||
</AttendeeDetailProvider>
|
</AttendeeDetailProvider>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
111
apps/web/test/attendee-attendance.test.ts
Normal file
111
apps/web/test/attendee-attendance.test.ts
Normal file
@@ -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')
|
||||||
|
})
|
||||||
|
})
|
||||||
149
apps/web/test/member-row.test.ts
Normal file
149
apps/web/test/member-row.test.ts
Normal file
@@ -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<AttendeeListItem['payment']>['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',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import { attendanceStatusSchema } from './attendance.js';
|
||||||
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
|
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
|
||||||
|
import { paymentStatusSchema } from './payments.js';
|
||||||
import { GroupWaitlistEntryDtoSchema } from './waitlist.js';
|
import { GroupWaitlistEntryDtoSchema } from './waitlist.js';
|
||||||
|
|
||||||
const isoDateTimeSchema = z.string().datetime();
|
const isoDateTimeSchema = z.string().datetime();
|
||||||
@@ -7,6 +9,11 @@ const pageSchema = createPageSchema();
|
|||||||
const pageSizeSchema = createPageSizeSchema(10);
|
const pageSizeSchema = createPageSizeSchema(10);
|
||||||
const paginationSchema = createPaginationSchema();
|
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({
|
export const AttendeeDtoSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
groupId: z.string(),
|
groupId: z.string(),
|
||||||
@@ -41,8 +48,33 @@ export const AttendeeQuerySchema = z.object({
|
|||||||
});
|
});
|
||||||
export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>;
|
export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<typeof AttendeePaymentSummarySchema>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<typeof AttendeeListItemSchema>;
|
||||||
|
|
||||||
export const AttendeeListSchema = z.object({
|
export const AttendeeListSchema = z.object({
|
||||||
data: z.array(AttendeeDtoSchema),
|
data: z.array(AttendeeListItemSchema),
|
||||||
pagination: paginationSchema,
|
pagination: paginationSchema,
|
||||||
});
|
});
|
||||||
export type AttendeeList = z.output<typeof AttendeeListSchema>;
|
export type AttendeeList = z.output<typeof AttendeeListSchema>;
|
||||||
|
|||||||
Reference in New Issue
Block a user