feat/improve-member-details #9
@@ -56,6 +56,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||
- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición.
|
||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
||||
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
||||
|
||||
@@ -33,14 +33,14 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true },
|
||||
select: { id: true, fullName: true, createdAt: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
const sessions = await db.classSession.findMany({
|
||||
where: { groupId },
|
||||
where: { groupId, startsAt: { gte: attendee.createdAt } },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: HISTORY_SESSIONS_LIMIT,
|
||||
select: { id: true, startsAt: true },
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
import { toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export class GetAttendee {
|
||||
@@ -18,7 +19,7 @@ export class GetAttendee {
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
): Promise<Result<AttendeeDetailDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
@@ -26,11 +27,32 @@ export class GetAttendee {
|
||||
return access;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))());
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
include: {
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
dueDate: { gte: billingPeriod.start, lt: billingPeriod.end },
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 1,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
return ok(toAttendeeDto(attendee));
|
||||
return ok(toAttendeeDetailDto(attendee));
|
||||
}
|
||||
}
|
||||
|
||||
function currentMonthRange(now: Date) {
|
||||
return {
|
||||
start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
|
||||
end: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)),
|
||||
};
|
||||
}
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { UpdateAttendee } from '@gruperly/shared';
|
||||
import { UpdateAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { UpdateAttendeeDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.patch('/:groupId/attendees/:attendeeId', validate.json(UpdateAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new UpdateAttendeeDetails();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
input: c.req.valid('json') as UpdateAttendee,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result, UpdateAttendee } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type UpdateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
};
|
||||
|
||||
type UpdateAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
input: UpdateAttendee;
|
||||
};
|
||||
|
||||
export class UpdateAttendeeDetails {
|
||||
constructor(private readonly deps: UpdateAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: UpdateAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, input } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const updated = await db.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: normalizeEditableFields(input),
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
|
||||
return Object.fromEntries(
|
||||
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
@@ -23,6 +23,10 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||
payments: AttendeeListItemRecord['payments'];
|
||||
};
|
||||
|
||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
return {
|
||||
id: record.id,
|
||||
@@ -60,6 +64,13 @@ function pickRelevantPayment(
|
||||
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
|
||||
}
|
||||
|
||||
export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetailDto {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
};
|
||||
}
|
||||
|
||||
/* The query comes in descending order; the row shows them from oldest to most
|
||||
recent so the dot on the right is the latest event. */
|
||||
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
|
||||
|
||||
@@ -6,6 +6,7 @@ import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createGroupRoute from './features/create/route';
|
||||
@@ -28,6 +29,7 @@ routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', groupPreRegistrationRoutes);
|
||||
routes.route('/', analyticsRoutes);
|
||||
routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
|
||||
|
||||
@@ -202,7 +202,11 @@ describe('analytics routes', () => {
|
||||
describe('GET /groups/:groupId/attendees/:attendeeId/history', () => {
|
||||
it('devuelve el historial de presentismo con su porcentaje', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1', fullName: 'Ana Pérez' });
|
||||
prisma.attendee.findFirst.mockResolvedValue({
|
||||
id: 'a-1',
|
||||
fullName: 'Ana Pérez',
|
||||
createdAt: new Date('2026-09-29T00:00:00.000Z'),
|
||||
});
|
||||
prisma.classSession.findMany.mockResolvedValue([
|
||||
{ id: 's-2', startsAt: new Date(at(7)) },
|
||||
{ id: 's-1', startsAt: new Date(at(0)) },
|
||||
@@ -228,6 +232,15 @@ describe('analytics routes', () => {
|
||||
{ classSessionId: 's-2', startsAt: at(7), status: 'ABSENT' },
|
||||
],
|
||||
});
|
||||
expect(prisma.classSession.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
groupId: 'group-1',
|
||||
startsAt: { gte: new Date('2026-09-29T00:00:00.000Z') },
|
||||
},
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: 20,
|
||||
select: { id: true, startsAt: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('devuelve 404 si el alumno no pertenece al grupo', async () => {
|
||||
|
||||
@@ -47,6 +47,9 @@ const attendee = {
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
payments: [
|
||||
{ status: 'PENDING', dueDate: new Date('2026-10-10T00:00:00.000Z') },
|
||||
],
|
||||
};
|
||||
|
||||
describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
@@ -73,6 +76,21 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
notifyToken: 'token-1',
|
||||
createdAt: '2026-08-01T10:00:00.000Z',
|
||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||
});
|
||||
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1', groupId: 'group-1' },
|
||||
include: {
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
dueDate: { gte: expect.any(Date), lt: expect.any(Date) },
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 1,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
99
apps/backend/test/attendee-update.test.ts
Normal file
99
apps/backend/test/attendee-update.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const db = {
|
||||
group: { findUnique: mock() },
|
||||
attendee: { findFirst: mock(), update: mock() },
|
||||
}
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}))
|
||||
|
||||
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
|
||||
|
||||
const userId = 'user-1'
|
||||
const attendee = {
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: 'Llega temprano',
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
|
||||
}
|
||||
|
||||
function makeApp() {
|
||||
const app = new Hono()
|
||||
app.use('*', async (context, next) => {
|
||||
context.set('user', { id: userId } as never)
|
||||
await next()
|
||||
})
|
||||
app.route('/groups', updateAttendeeRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
db.group.findUnique.mockResolvedValue({
|
||||
id: 'group-1',
|
||||
name: 'Funcional',
|
||||
createdById: userId,
|
||||
members: [],
|
||||
})
|
||||
db.attendee.findFirst.mockResolvedValue(attendee)
|
||||
})
|
||||
|
||||
it('actualiza contacto y conserva los campos vacíos como null', async () => {
|
||||
db.attendee.update.mockResolvedValue({
|
||||
...attendee,
|
||||
email: 'ana@example.com',
|
||||
phone: null,
|
||||
})
|
||||
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: 'ana@example.com', phone: '' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
data: { email: 'ana@example.com', phone: null },
|
||||
})
|
||||
})
|
||||
|
||||
it('actualiza una única nota', async () => {
|
||||
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' })
|
||||
|
||||
await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notes: 'Traer colchoneta' }),
|
||||
})
|
||||
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
data: { notes: 'Traer colchoneta' },
|
||||
})
|
||||
})
|
||||
|
||||
it('rechaza un email inválido', async () => {
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: 'sin-arroba' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(db.attendee.update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,10 @@ type LargeTitleProps = {
|
||||
/** Action to the left of the bar. On desktop it's the "Volver" link that
|
||||
* used to live in the screen body; on mobile it's hidden. */
|
||||
leading?: ReactNode
|
||||
/** Context shown in the center before the large title collapses. */
|
||||
barContext?: ReactNode
|
||||
/** Visual identity beside the large title, such as an avatar. */
|
||||
titleLeading?: ReactNode
|
||||
/** Context that can't disappear on scroll (e.g. the present counter). It
|
||||
* travels to the bar and blends with the title. */
|
||||
barTrailing?: ReactNode
|
||||
@@ -32,7 +36,14 @@ type LargeTitleProps = {
|
||||
* built prop, so React reuses the elements and the subtree below doesn't
|
||||
* re-render on every scroll frame.
|
||||
*/
|
||||
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
|
||||
export function LargeTitle({
|
||||
title,
|
||||
leading,
|
||||
barContext,
|
||||
titleLeading,
|
||||
barTrailing,
|
||||
children,
|
||||
}: LargeTitleProps) {
|
||||
const { titleRef, progress } = useLargeTitleCollapse()
|
||||
const barHost = useImmersiveBarHost()
|
||||
|
||||
@@ -49,18 +60,37 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle
|
||||
style={{ opacity: progress }}
|
||||
/>
|
||||
{leading}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="relative min-w-0 flex-1 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
{barTrailing ? (
|
||||
{barContext ? (
|
||||
<div className="pointer-events-none absolute inset-y-0 left-14 right-14 flex items-center justify-center overflow-hidden text-center">
|
||||
<span
|
||||
className="truncate text-sm font-medium text-secondary"
|
||||
style={{ opacity: 1 - progress }}
|
||||
>
|
||||
{barContext}
|
||||
</span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute inset-x-0 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="relative min-w-0 flex-1 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
)}
|
||||
{barContext ? <span className="min-w-0 flex-1" aria-hidden="true" /> : null}
|
||||
{barTrailing ? (
|
||||
<span
|
||||
aria-hidden={barContext ? undefined : true}
|
||||
className="relative flex shrink-0 items-center"
|
||||
style={{ opacity: progress }}
|
||||
style={{ opacity: barContext ? 1 : progress }}
|
||||
>
|
||||
{barTrailing}
|
||||
</span>
|
||||
@@ -70,12 +100,15 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle
|
||||
)
|
||||
: null}
|
||||
|
||||
<h1
|
||||
ref={titleRef}
|
||||
className="text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
{titleLeading}
|
||||
<h1
|
||||
ref={titleRef}
|
||||
className="min-w-0 text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</>
|
||||
|
||||
@@ -26,19 +26,17 @@ export function AbsenceLinkSection() {
|
||||
return (
|
||||
<Section
|
||||
title="Link de ausencias"
|
||||
description="Para que avise si no puede venir"
|
||||
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
|
||||
>
|
||||
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
|
||||
the "Link copied" text is not lost on collapse/expand. */}
|
||||
<div id={panelId} hidden={!isOpen}>
|
||||
<p className="px-3 text-sm text-foreground">
|
||||
Mandales este link para que avisen cuando no puedan venir.
|
||||
</p>
|
||||
{/* Stacked and full width: at 50% the labels ("Enviar por WhatsApp")
|
||||
wrapped onto two lines and fell below the minimum touch target.
|
||||
Copy stays on top, glued to its confirmation, and the primary action
|
||||
is told apart by the accent fill. */}
|
||||
<div className="mt-2.5 flex flex-col gap-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(url)}
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import type { KeyboardEvent, RefObject } from 'react'
|
||||
import { Ellipsis, UserMinus } from 'lucide-react'
|
||||
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus } from 'lucide-react'
|
||||
import { useToast } from '../../components/ui'
|
||||
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'
|
||||
'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-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||
|
||||
/** "⋯" menu on the attendee detail page.
|
||||
*
|
||||
* For now it only holds "Quitar del grupo": the backend has no way to
|
||||
* regenerate the absence token, so the option is not shown before that
|
||||
* endpoint exists (see `apps/backend/prisma/models/domain.prisma`, field
|
||||
* `notifyToken`). Once it does, it is one more `<button role="menuitem">` in
|
||||
* the list below.
|
||||
*
|
||||
* The label goes in `text-primary` and the icon carries the `text-danger`: the
|
||||
* `danger` red on white sits at 3.7:1 and does not reach AA for normal text. */
|
||||
/** Accessible "⋯" menu for member-level actions. */
|
||||
export function AttendeeActionsMenu({
|
||||
triggerRef,
|
||||
}: {
|
||||
@@ -23,7 +15,8 @@ export function AttendeeActionsMenu({
|
||||
* when it closes. */
|
||||
triggerRef: RefObject<HTMLButtonElement | null>
|
||||
}) {
|
||||
const { openRemoveDialog } = useAttendeeDetail()
|
||||
const { beginContactEdit, openRemoveDialog } = useAttendeeDetail()
|
||||
const toast = useToast()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const itemRef = useRef<HTMLButtonElement>(null)
|
||||
@@ -76,6 +69,18 @@ export function AttendeeActionsMenu({
|
||||
items[next]?.focus()
|
||||
}
|
||||
|
||||
const showPendingChangeGroup = () => {
|
||||
close()
|
||||
// TODO(miembros): navegar al selector cuando se confirmen las reglas y exista el endpoint.
|
||||
toast.info('Cambiar de grupo estará disponible cuando se confirme el flujo de traspaso.')
|
||||
}
|
||||
|
||||
const showPendingPause = () => {
|
||||
close()
|
||||
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
||||
toast.info('Pausar la membresía estará disponible cuando se confirme su lógica de negocio.')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative shrink-0">
|
||||
<button
|
||||
@@ -105,12 +110,46 @@ export function AttendeeActionsMenu({
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={showPendingChangeGroup}
|
||||
>
|
||||
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Cambiar de grupo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={() => {
|
||||
close()
|
||||
beginContactEdit()
|
||||
requestAnimationFrame(() => {
|
||||
document.getElementById('attendee-contact')?.scrollIntoView({ behavior: 'smooth' })
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Pencil className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Editar contacto
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={ITEM_CLASS}
|
||||
onClick={showPendingPause}
|
||||
>
|
||||
<Pause className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
Pausar membresía
|
||||
</button>
|
||||
<div className="my-1 border-t border-border/70" aria-hidden="true" />
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className={`${ITEM_CLASS} text-danger-fg hover:bg-danger-soft`}
|
||||
onClick={() => {
|
||||
close()
|
||||
openRemoveDialog()
|
||||
}}
|
||||
>
|
||||
<UserMinus className="size-4 shrink-0 text-danger" aria-hidden="true" />
|
||||
<UserMinus className="size-4 shrink-0" aria-hidden="true" />
|
||||
Quitar del grupo
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -96,12 +96,6 @@ export function AttendeeAttendanceSection() {
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{/* Classes with no record are not absences: they are reported separately
|
||||
and quietly so the "1 de 1" above does not read as a failure. */}
|
||||
{summary.unmarkedLabel ? (
|
||||
<p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
|
||||
) : null}
|
||||
|
||||
{showAll && isCapped ? (
|
||||
<p className="px-3 pt-2 text-xs text-foreground">
|
||||
El historial guarda las últimas {HISTORY_LIMIT} clases.
|
||||
|
||||
@@ -1,42 +1,67 @@
|
||||
import { MessageCircle, Phone } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { ACTION_BUTTON_CLASS } from './actionButton'
|
||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeeContactActions() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
|
||||
const phone = attendee?.phone
|
||||
if (!phone) return null
|
||||
|
||||
// The links use the raw digits: wa.me and tel: do not understand formats.
|
||||
const digits = phone.replace(/\D/g, '')
|
||||
const label = formatPhoneDisplay(phone) ?? phone
|
||||
const digits = phone?.replace(/\D/g, '') ?? ''
|
||||
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? 'el miembro'
|
||||
|
||||
return (
|
||||
<div className="flex gap-2.5">
|
||||
{/* The icons go with `accent-fg` and not with `accent`: the `accent` blue is
|
||||
the same in both themes and on dark `primary-soft` it sits at 2.2:1.
|
||||
`accent-fg` gives 6.2:1 in light and 7.1:1 in dark. */}
|
||||
<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-fg" 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-fg" aria-hidden="true" />
|
||||
Llamar
|
||||
</a>
|
||||
<div>
|
||||
<div className="grid grid-cols-[1.4fr_1fr] gap-2.5">
|
||||
{phone ? (
|
||||
<a
|
||||
href={`https://wa.me/${digits}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Abrir WhatsApp con ${label}`}
|
||||
className={PRIMARY_ACTION_CLASS}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
WhatsApp
|
||||
</a>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-describedby="missing-phone-feedback"
|
||||
className={cn(PRIMARY_ACTION_CLASS, 'cursor-not-allowed opacity-45')}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
WhatsApp
|
||||
</button>
|
||||
)}
|
||||
{phone ? (
|
||||
<a
|
||||
href={`tel:${digits}`}
|
||||
aria-label={`Llamar a ${label}`}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||
>
|
||||
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
||||
Llamar
|
||||
</a>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-describedby="missing-phone-feedback"
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full cursor-not-allowed opacity-45')}
|
||||
>
|
||||
<Phone className="size-4 text-secondary" aria-hidden="true" />
|
||||
Llamar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{!phone ? (
|
||||
<p id="missing-phone-feedback" className="mt-2 text-xs text-secondary">
|
||||
Agregá un teléfono para usar estas acciones
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Loader2, Mail, Phone } from 'lucide-react'
|
||||
import { Button, Input } from '../../components/ui'
|
||||
|
||||
type AttendeeContactFormProps = {
|
||||
phone: string
|
||||
email: string
|
||||
error: string | null
|
||||
isSaving: boolean
|
||||
onPhoneChange: (value: string) => void
|
||||
onEmailChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSave: () => void
|
||||
}
|
||||
|
||||
export function AttendeeContactForm({
|
||||
phone,
|
||||
email,
|
||||
error,
|
||||
isSaving,
|
||||
onPhoneChange,
|
||||
onEmailChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: AttendeeContactFormProps) {
|
||||
return (
|
||||
<div className="space-y-3 px-3 pb-1">
|
||||
<ContactInput icon={Phone} label="Teléfono">
|
||||
<Input
|
||||
type="tel"
|
||||
value={phone}
|
||||
onChange={(event) => onPhoneChange(event.target.value)}
|
||||
autoComplete="tel"
|
||||
autoFocus
|
||||
aria-label="Teléfono"
|
||||
/>
|
||||
</ContactInput>
|
||||
<ContactInput icon={Mail} label="Email">
|
||||
<Input
|
||||
type="email"
|
||||
value={email}
|
||||
invalid={error === 'Ingresá un email válido'}
|
||||
onChange={(event) => onEmailChange(event.target.value)}
|
||||
autoComplete="email"
|
||||
aria-label="Email"
|
||||
aria-describedby={error ? 'contact-error' : undefined}
|
||||
/>
|
||||
</ContactInput>
|
||||
{error ? (
|
||||
<p id="contact-error" role="alert" className="text-sm text-danger-fg">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ContactInputProps = {
|
||||
icon: typeof Phone
|
||||
label: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function ContactInput({ icon: Icon, label, children }: ContactInputProps) {
|
||||
return (
|
||||
<label className="grid grid-cols-[1.25rem_1fr] items-center gap-x-3 gap-y-1">
|
||||
<Icon className="size-4 text-secondary" aria-hidden="true" />
|
||||
<span className="text-xs font-medium text-secondary">{label}</span>
|
||||
<span className="col-start-2">{children}</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -1,43 +1,135 @@
|
||||
import { Mail } from 'lucide-react'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Mail, Phone } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { AttendeeContactForm } from './AttendeeContactForm'
|
||||
import { contactEmailError } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
/* Inner `px-3`: the hover band bleeds all the way to the section edge
|
||||
(it separates from the text, not the other way around) and the notes below
|
||||
add the same so the email and they land in the same column. */
|
||||
const ROW_CLASS =
|
||||
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||
|
||||
/** The attendee's email and notes. The phone does not go here: it is already in
|
||||
* the subtitle, behind the WhatsApp and Llamar buttons, and repeating it filled
|
||||
* the screen with a value that was already in view.
|
||||
*
|
||||
* With no data the section is not drawn: there are no "Sin email"/"Sin notas"
|
||||
* rows. It shows up on its own as soon as the attendee has one of them (today
|
||||
* the email can arrive when approving a pre-registration; the notes, once
|
||||
* editing exists). */
|
||||
export function AttendeeContactSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const {
|
||||
attendee,
|
||||
isEditingContact,
|
||||
beginContactEdit,
|
||||
endContactEdit,
|
||||
saveAttendee,
|
||||
isUpdatingAttendee,
|
||||
} = useAttendeeDetail()
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEditingContact || !attendee) return
|
||||
setPhone(attendee.phone ?? '')
|
||||
setEmail(attendee.email ?? '')
|
||||
setError(null)
|
||||
}, [attendee, isEditingContact])
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const { email, notes } = attendee
|
||||
if (!email && !notes) return null
|
||||
const cancel = () => {
|
||||
setError(null)
|
||||
endContactEdit()
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const emailError = contactEmailError(email)
|
||||
if (emailError) {
|
||||
setError(emailError)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await saveAttendee({ phone, email })
|
||||
endContactEdit()
|
||||
} catch {
|
||||
setError('No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title="Contacto">
|
||||
<div className="divide-y divide-border/60">
|
||||
{email ? (
|
||||
<a href={`mailto:${email}`} className={ROW_CLASS}>
|
||||
<span className="truncate text-sm text-primary">{email}</span>
|
||||
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
{notes ? (
|
||||
<p className="whitespace-pre-line px-3 py-2 text-sm leading-relaxed text-primary">{notes}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Section
|
||||
id="attendee-contact"
|
||||
title="Contacto"
|
||||
trailing={
|
||||
!isEditingContact ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginContactEdit}
|
||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{isEditingContact ? (
|
||||
<AttendeeContactForm
|
||||
phone={phone}
|
||||
email={email}
|
||||
error={error}
|
||||
isSaving={isUpdatingAttendee}
|
||||
onPhoneChange={(value) => {
|
||||
setPhone(value)
|
||||
setError(null)
|
||||
}}
|
||||
onEmailChange={(value) => {
|
||||
setEmail(value)
|
||||
setError(null)
|
||||
}}
|
||||
onCancel={cancel}
|
||||
onSave={() => void save()}
|
||||
/>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
<ContactRow
|
||||
icon={Phone}
|
||||
label="Teléfono"
|
||||
value={formatPhoneDisplay(attendee.phone) ?? 'Agregar teléfono'}
|
||||
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
|
||||
placeholder={!attendee.phone}
|
||||
/>
|
||||
<ContactRow
|
||||
icon={Mail}
|
||||
label="Email"
|
||||
value={attendee.email ?? 'Agregar email'}
|
||||
href={attendee.email ? `mailto:${attendee.email}` : undefined}
|
||||
placeholder={!attendee.email}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
type ContactRowProps = {
|
||||
icon: typeof Phone
|
||||
label: string
|
||||
value: string
|
||||
href?: string
|
||||
placeholder: boolean
|
||||
}
|
||||
|
||||
function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) {
|
||||
const content = (
|
||||
<>
|
||||
<Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||
<span className="min-w-0">
|
||||
<span className="block text-xs font-medium text-secondary">{label}</span>
|
||||
<span className={cn('block truncate text-sm text-primary', placeholder && 'text-secondary')}>
|
||||
{value}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
|
||||
const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2'
|
||||
return href ? (
|
||||
<a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}>
|
||||
{content}
|
||||
</a>
|
||||
) : (
|
||||
<div className={className}>{content}</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import { createContext, useContext, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||
import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
|
||||
import type {
|
||||
AttendeeDetailDto,
|
||||
AttendeeHistory,
|
||||
GroupWaitlistEntryDto,
|
||||
UpdateAttendee,
|
||||
} from '@gruperly/shared'
|
||||
import {
|
||||
getAttendeeHistory,
|
||||
getGroup,
|
||||
getGroupAttendee,
|
||||
getGroupWaitlist,
|
||||
updateGroupAttendee,
|
||||
} from '../../lib/api'
|
||||
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||
|
||||
type AttendeeDetailContextValue = {
|
||||
groupId: string
|
||||
groupName: string | undefined
|
||||
attendee: AttendeeDto | undefined
|
||||
attendee: AttendeeDetailDto | undefined
|
||||
attendeePending: boolean
|
||||
attendeeFailed: boolean
|
||||
history: AttendeeHistory | undefined
|
||||
@@ -18,6 +29,11 @@ type AttendeeDetailContextValue = {
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
isEditingContact: boolean
|
||||
beginContactEdit: () => void
|
||||
endContactEdit: () => void
|
||||
saveAttendee: (input: UpdateAttendee) => Promise<void>
|
||||
isUpdatingAttendee: boolean
|
||||
isRemoveDialogOpen: boolean
|
||||
openRemoveDialog: () => void
|
||||
closeRemoveDialog: () => void
|
||||
@@ -37,7 +53,9 @@ export function AttendeeDetailProvider({
|
||||
children: ReactNode
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||
const [isEditingContact, setIsEditingContact] = useState(false)
|
||||
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ['group', groupId],
|
||||
@@ -51,6 +69,17 @@ export function AttendeeDetailProvider({
|
||||
enabled: Boolean(groupId && attendeeId),
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (input: UpdateAttendee) => updateGroupAttendee(groupId, attendeeId, input),
|
||||
onSuccess: (updated) => {
|
||||
queryClient.setQueryData<AttendeeDetailDto>(
|
||||
['group-attendee', groupId, attendeeId],
|
||||
(current) => (current ? { ...current, ...updated } : current),
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
},
|
||||
})
|
||||
|
||||
// Same key the analytics screen uses: both read the same history and do not
|
||||
// clobber each other's cache.
|
||||
const historyQuery = useQuery({
|
||||
@@ -91,6 +120,13 @@ export function AttendeeDetailProvider({
|
||||
firstWaitlistEntry,
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
isEditingContact,
|
||||
beginContactEdit: () => setIsEditingContact(true),
|
||||
endContactEdit: () => setIsEditingContact(false),
|
||||
saveAttendee: async (input) => {
|
||||
await updateMutation.mutateAsync(input)
|
||||
},
|
||||
isUpdatingAttendee: updateMutation.isPending,
|
||||
isRemoveDialogOpen,
|
||||
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||
|
||||
@@ -1,88 +1,98 @@
|
||||
import { useRef } from 'react'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||
import { Avatar, Badge, 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 { AttendeePhoneLine } from './AttendeePhoneLine'
|
||||
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
||||
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||
import { formatMemberSince } from './attendance'
|
||||
import { paymentPresentation } from './detail'
|
||||
|
||||
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">
|
||||
{/* The title carries the red (at 18px it already counts as large text and
|
||||
reaches 3:1) and the body uses `text-primary`: on `danger-soft` the red
|
||||
does not pass the 4.5:1 a `text-sm` needs. */}
|
||||
<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-fg hover:bg-transparent hover:text-primary"
|
||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||
>
|
||||
Volver al grupo
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const payment = attendee ? paymentPresentation(attendee.payment) : null
|
||||
|
||||
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>
|
||||
<section className="mx-auto w-full max-w-md animate-fade-in lg:max-w-2xl">
|
||||
<LargeTitle
|
||||
title={attendee?.fullName ?? 'Miembro'}
|
||||
barContext={groupName ?? 'Grupo'}
|
||||
leading={
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
aria-label="Volver al grupo"
|
||||
className="relative z-10 inline-flex size-11 shrink-0 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"
|
||||
>
|
||||
<ArrowLeft className="size-5" aria-hidden="true" />
|
||||
</Link>
|
||||
}
|
||||
barTrailing={<AttendeeActionsMenu triggerRef={menuTriggerRef} />}
|
||||
titleLeading={
|
||||
attendee ? (
|
||||
<Avatar
|
||||
name={attendee.fullName}
|
||||
className="size-14 rounded-full bg-accent-soft text-base text-accent-fg ring-1 ring-border"
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{attendee && payment ? (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2 text-sm text-secondary">
|
||||
<Badge variant={payment.isDue ? 'warning' : 'success'} className="text-[11px]">
|
||||
{payment.chipLabel}
|
||||
</Badge>
|
||||
<span>Desde {formatMemberSince(attendee.createdAt)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</LargeTitle>
|
||||
|
||||
<AttendeeActionsMenu triggerRef={menuTriggerRef} />
|
||||
</div>
|
||||
{attendeePending ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<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>
|
||||
<AttendeePhoneLine />
|
||||
</div>
|
||||
{attendeeFailed || (!attendeePending && !attendee) ? (
|
||||
<div className="mt-6 rounded-2xl bg-danger-soft p-6">
|
||||
<h2 className="text-lg font-bold text-danger-fg">Miembro no encontrado</h2>
|
||||
<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-fg hover:bg-transparent hover:text-primary"
|
||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||
>
|
||||
Volver al grupo
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-3">
|
||||
<AttendeeContactActions />
|
||||
</div>
|
||||
{attendee ? (
|
||||
<>
|
||||
<div className="mt-5">
|
||||
<AttendeeContactActions />
|
||||
</div>
|
||||
|
||||
{/* Ordered by how often they are used. Adding Pagos means inserting one
|
||||
more block above Asistencia; each section brings its own spacing, so
|
||||
the layout does not need to change. */}
|
||||
<div className="mt-5">
|
||||
<AttendeeAttendanceSection />
|
||||
<AttendeeContactSection />
|
||||
<AbsenceLinkSection />
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<AttendeeContactSection />
|
||||
<AttendeePaymentsSection />
|
||||
<AttendeeAttendanceSection />
|
||||
<AttendeeNotesSection />
|
||||
<AbsenceLinkSection />
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
||||
</section>
|
||||
|
||||
47
apps/web/src/features/attendee-detail/AttendeeNotesForm.tsx
Normal file
47
apps/web/src/features/attendee-detail/AttendeeNotesForm.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
|
||||
type AttendeeNotesFormProps = {
|
||||
draft: string
|
||||
error: string | null
|
||||
isSaving: boolean
|
||||
onDraftChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSave: () => void
|
||||
}
|
||||
|
||||
export function AttendeeNotesForm({
|
||||
draft,
|
||||
error,
|
||||
isSaving,
|
||||
onDraftChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: AttendeeNotesFormProps) {
|
||||
return (
|
||||
<div className="space-y-3 px-3 pb-1">
|
||||
<textarea
|
||||
value={draft}
|
||||
onChange={(event) => onDraftChange(event.target.value)}
|
||||
rows={4}
|
||||
autoFocus
|
||||
aria-label="Notas del miembro"
|
||||
className="w-full resize-y rounded-xl border border-border bg-surface px-3 py-2.5 text-base leading-relaxed text-primary placeholder:text-secondary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
|
||||
/>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-danger-fg">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Guardar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import { AttendeeNotesForm } from './AttendeeNotesForm'
|
||||
import { formatNotesUpdatedAt } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeeNotesSection() {
|
||||
const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const beginEditing = () => {
|
||||
setDraft(attendee.notes ?? '')
|
||||
setError(null)
|
||||
setIsEditing(true)
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
try {
|
||||
await saveAttendee({ notes: draft })
|
||||
setIsEditing(false)
|
||||
} catch {
|
||||
setError('No pudimos guardar la nota. Revisá tu conexión e intentá de nuevo.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
title="Notas"
|
||||
trailing={
|
||||
!isEditing ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={beginEditing}
|
||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{isEditing ? (
|
||||
<AttendeeNotesForm
|
||||
draft={draft}
|
||||
error={error}
|
||||
isSaving={isUpdatingAttendee}
|
||||
onDraftChange={(value) => {
|
||||
setDraft(value)
|
||||
setError(null)
|
||||
}}
|
||||
onCancel={() => {
|
||||
setIsEditing(false)
|
||||
setError(null)
|
||||
}}
|
||||
onSave={() => void save()}
|
||||
/>
|
||||
) : (
|
||||
<div className="px-3 pb-1">
|
||||
<p className="whitespace-pre-line text-sm leading-relaxed text-primary">
|
||||
{attendee.notes || 'Sin notas todavía.'}
|
||||
</p>
|
||||
<p className="mt-1.5 text-xs text-secondary">{formatNotesUpdatedAt(attendee.updatedAt)}</p>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Badge, useToast } from '../../components/ui'
|
||||
import { paymentPresentation } from './detail'
|
||||
import { Section } from './Section'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
|
||||
export function AttendeePaymentsSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const toast = useToast()
|
||||
if (!attendee) return null
|
||||
|
||||
const payment = paymentPresentation(attendee.payment)
|
||||
|
||||
const registerPayment = () => {
|
||||
// TODO(cobros): conectar esta acción cuando se confirme el flujo y el endpoint de pagos.
|
||||
toast.info('Registrar pagos estará disponible cuando se defina el flujo de cobros.')
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title="Cobros">
|
||||
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-primary">
|
||||
{payment.periodLabel} · {payment.statusLabel}
|
||||
</p>
|
||||
<Badge variant={payment.isDue ? 'warning' : 'success'} className="mt-1.5 text-[11px]">
|
||||
{payment.chipLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={registerPayment}
|
||||
className="min-h-11 shrink-0 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||
>
|
||||
Registrar pago
|
||||
</button>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -16,17 +16,18 @@ export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking
|
||||
and it is the content that is set off from the edge (the `px-3` on the `h2`
|
||||
and on the `trailing` below align the label and the summary with this row). */
|
||||
const TOGGLE_ROW_CLASS = cn(
|
||||
SECTION_TITLE_CLASS,
|
||||
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary',
|
||||
'transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
|
||||
)
|
||||
|
||||
type SectionProps = {
|
||||
id?: string
|
||||
/** The section title. Usually a string. */
|
||||
title: ReactNode
|
||||
/** To the right of the title: the attendance summary, for example. */
|
||||
trailing?: ReactNode
|
||||
description?: ReactNode
|
||||
/** When present, the whole title is the content's trigger and `title` is just
|
||||
* its label: the `<h2>` is still the section heading and the button takes the
|
||||
* full row. */
|
||||
@@ -41,11 +42,11 @@ type SectionProps = {
|
||||
* own padding, so the separator always sits the same distance from the content
|
||||
* above. Adding another section (Pagos, say) means inserting one more block and
|
||||
* nothing else. */
|
||||
export function Section({ title, trailing, toggle, children }: SectionProps) {
|
||||
export function Section({ id, title, trailing, description, toggle, children }: SectionProps) {
|
||||
const headingId = useId()
|
||||
|
||||
return (
|
||||
<section aria-labelledby={headingId} className="border-t border-border/70 py-4">
|
||||
<section id={id} aria-labelledby={headingId} className="border-t border-border/70 py-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
{toggle ? (
|
||||
// The button lives inside the `<h2>`: the heading is not lost and the
|
||||
@@ -59,7 +60,14 @@ export function Section({ title, trailing, toggle, children }: SectionProps) {
|
||||
onClick={toggle.onToggle}
|
||||
className={TOGGLE_ROW_CLASS}
|
||||
>
|
||||
<span className="truncate">{title}</span>
|
||||
<span className="min-w-0">
|
||||
<span className={cn(SECTION_TITLE_CLASS, 'block truncate')}>{title}</span>
|
||||
{description ? (
|
||||
<span className="mt-0.5 block truncate text-sm font-normal normal-case tracking-normal text-secondary">
|
||||
{description}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-4 shrink-0 transition-transform',
|
||||
|
||||
@@ -70,35 +70,16 @@ export function visibleSessions(
|
||||
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
|
||||
}
|
||||
|
||||
/** Classes with a recorded attendance: attended, was absent or was absent with
|
||||
* notice. The "Sin registrar" ones do not count: without a record there is
|
||||
* neither attendance nor absence, and putting them in the denominator made
|
||||
* "1 de 3" read as two absences. */
|
||||
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
|
||||
return sessions.filter((session) => session.status != null)
|
||||
}
|
||||
|
||||
export type AttendanceSummary = {
|
||||
/** "1 de 1 clase", or "Sin clases registradas" if there is none with a record. */
|
||||
/** "1 de 1 clase", or "Sin clases registradas" if there are no visible rows. */
|
||||
label: string
|
||||
/** "2 sin registrar", or `null` if there are no classes without a record. */
|
||||
unmarkedLabel: string | null
|
||||
}
|
||||
|
||||
/** Summary of the rows being shown: how many classes the person recorded out of
|
||||
* how many have a record, and how many were left unmarked.
|
||||
*
|
||||
* The "sin registrar" text is dimmed when there is no marked class: the summary
|
||||
* already says there is no data and the two texts would say the same thing
|
||||
* twice. */
|
||||
/** Summary of the rows being shown. The denominator deliberately includes
|
||||
* unmarked sessions so the counter always matches the visible list. */
|
||||
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
|
||||
const marked = markedSessions(sessions)
|
||||
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }
|
||||
if (sessions.length === 0) return { label: 'Sin clases registradas' }
|
||||
|
||||
const present = marked.filter((session) => session.status === 'PRESENT').length
|
||||
const unmarked = sessions.length - marked.length
|
||||
return {
|
||||
label: `${present} de ${classCountLabel(marked.length)}`,
|
||||
unmarkedLabel: unmarked > 0 ? `${unmarked} sin registrar` : null,
|
||||
}
|
||||
const present = sessions.filter((session) => session.status === 'PRESENT').length
|
||||
return { label: `${present} de ${classCountLabel(sessions.length)}` }
|
||||
}
|
||||
|
||||
79
apps/web/src/features/attendee-detail/detail.ts
Normal file
79
apps/web/src/features/attendee-detail/detail.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import type { AttendeePaymentSummary } from '@gruperly/shared'
|
||||
import { UpdateAttendeeSchema } from '@gruperly/shared'
|
||||
|
||||
export function contactEmailError(email: string): string | null {
|
||||
const result = UpdateAttendeeSchema.safeParse({ email })
|
||||
if (result.success) return null
|
||||
return result.error.issues[0]?.message ?? 'Ingresá un email válido'
|
||||
}
|
||||
|
||||
export type PaymentPresentation = {
|
||||
periodLabel: string
|
||||
statusLabel: string
|
||||
chipLabel: string
|
||||
isDue: boolean
|
||||
}
|
||||
|
||||
export function paymentPresentation(
|
||||
payment: AttendeePaymentSummary | null,
|
||||
today = new Date(),
|
||||
): PaymentPresentation {
|
||||
const periodLabel = capitalize(formatMonthAndYear(today))
|
||||
if (!payment) {
|
||||
return { periodLabel, statusLabel: 'Sin cobro registrado', chipLabel: 'Al día', isDue: false }
|
||||
}
|
||||
|
||||
const isDue = payment.status === 'PENDING' || payment.status === 'OVERDUE'
|
||||
return {
|
||||
periodLabel,
|
||||
statusLabel: paymentStatusLabel(payment.status),
|
||||
chipLabel: isDue ? `Debe ${formatMonth(new Date(payment.dueDate))}` : 'Al día',
|
||||
isDue,
|
||||
}
|
||||
}
|
||||
|
||||
export function formatNotesUpdatedAt(updatedAt: string, today = new Date()): string {
|
||||
const date = new Date(updatedAt)
|
||||
if (sameCalendarDate(date, today)) return 'Editado hoy'
|
||||
return `Editado ${date.toLocaleDateString('es-MX', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
})}`
|
||||
}
|
||||
|
||||
function paymentStatusLabel(status: AttendeePaymentSummary['status']): string {
|
||||
switch (status) {
|
||||
case 'PAID':
|
||||
return 'Pagado'
|
||||
case 'OVERDUE':
|
||||
return 'Vencido'
|
||||
case 'CANCELLED':
|
||||
return 'Cancelado'
|
||||
default:
|
||||
return 'Pendiente'
|
||||
}
|
||||
}
|
||||
|
||||
function formatMonth(date: Date): string {
|
||||
return date.toLocaleDateString('es-MX', { month: 'long' })
|
||||
}
|
||||
|
||||
function formatMonthAndYear(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat('es-MX', { month: 'long', year: 'numeric' }).formatToParts(date)
|
||||
const month = parts.find((part) => part.type === 'month')?.value ?? ''
|
||||
const year = parts.find((part) => part.type === 'year')?.value ?? ''
|
||||
return `${month} ${year}`.trim()
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return `${value.charAt(0).toUpperCase()}${value.slice(1)}`
|
||||
}
|
||||
|
||||
function sameCalendarDate(left: Date, right: Date): boolean {
|
||||
return (
|
||||
left.getFullYear() === right.getFullYear() &&
|
||||
left.getMonth() === right.getMonth() &&
|
||||
left.getDate() === right.getDate()
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
AbsenceDetails,
|
||||
ApproveGroupPreRegistrationResult,
|
||||
AttendeeDetailDto,
|
||||
AttendeeDto,
|
||||
AttendeeHistory,
|
||||
AttendeeList,
|
||||
@@ -43,6 +44,7 @@ import type {
|
||||
RemoveGroupWaitlistEntryResult,
|
||||
SessionStudents,
|
||||
StudentsAtRisk,
|
||||
UpdateAttendee,
|
||||
UpdateStudentStatusResult,
|
||||
} from '@gruperly/shared'
|
||||
|
||||
@@ -178,7 +180,17 @@ export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) =>
|
||||
apiFetch<AttendeeList>(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`)
|
||||
|
||||
export const getGroupAttendee = (groupId: string, attendeeId: string) =>
|
||||
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`)
|
||||
apiFetch<AttendeeDetailDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`)
|
||||
|
||||
export const updateGroupAttendee = (
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
payload: UpdateAttendee,
|
||||
) =>
|
||||
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
|
||||
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||
['groups', ':id'],
|
||||
['groups', ':id', 'analytics'],
|
||||
['groups', ':id', 'attendees', ':attendeeId'],
|
||||
['class', ':id', 'attendance'],
|
||||
]
|
||||
|
||||
|
||||
@@ -57,15 +57,9 @@ describe('attendanceStatusLabel', () => {
|
||||
})
|
||||
|
||||
describe('attendanceSummary', () => {
|
||||
test('el denominador son las clases registradas, no todas las filas', () => {
|
||||
// La vista previa son 5 filas, pero una quedó sin registrar: el resumen
|
||||
// cuenta 4, no 5, porque sin dato no hay ni asistencia ni ausencia.
|
||||
test('el denominador coincide con todas las filas visibles', () => {
|
||||
const { label } = attendanceSummary(visibleSessions(historial, false))
|
||||
expect(label).toBe('2 de 4 clases')
|
||||
})
|
||||
|
||||
test('las clases sin registro se avisan aparte, no mezcladas en el total', () => {
|
||||
expect(attendanceSummary(visibleSessions(historial, false)).unmarkedLabel).toBe('1 sin registrar')
|
||||
expect(label).toBe('2 de 5 clases')
|
||||
})
|
||||
|
||||
test('con una sola clase el total va en singular', () => {
|
||||
@@ -75,18 +69,16 @@ describe('attendanceSummary', () => {
|
||||
test('sin nada registrado lo dice, en vez de "0 de 0"', () => {
|
||||
const sinRegistrar = [sesion(5, null), sesion(6, null)]
|
||||
expect(attendanceSummary(sinRegistrar)).toEqual({
|
||||
label: 'Sin clases registradas',
|
||||
unmarkedLabel: null,
|
||||
label: '0 de 2 clases',
|
||||
})
|
||||
expect(attendanceSummary([])).toEqual({
|
||||
label: 'Sin clases registradas',
|
||||
unmarkedLabel: null,
|
||||
})
|
||||
})
|
||||
|
||||
test('faltó y faltó con aviso también cuentan como clases registradas', () => {
|
||||
const marcadas = [sesion(1, 'ABSENT'), sesion(2, 'EXCUSED')]
|
||||
expect(attendanceSummary(marcadas)).toEqual({ label: '0 de 2 clases', unmarkedLabel: null })
|
||||
expect(attendanceSummary(marcadas)).toEqual({ label: '0 de 2 clases' })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
108
apps/web/test/attendee-detail.test.ts
Normal file
108
apps/web/test/attendee-detail.test.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { createElement } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { AttendeeContactForm } from '../src/features/attendee-detail/AttendeeContactForm'
|
||||
import { AttendeeNotesForm } from '../src/features/attendee-detail/AttendeeNotesForm'
|
||||
import {
|
||||
contactEmailError,
|
||||
formatNotesUpdatedAt,
|
||||
paymentPresentation,
|
||||
} from '../src/features/attendee-detail/detail'
|
||||
|
||||
describe('contactEmailError', () => {
|
||||
test('permite email vacío', () => {
|
||||
expect(contactEmailError('')).toBeNull()
|
||||
})
|
||||
|
||||
test('muestra el error acordado para un email inválido', () => {
|
||||
expect(contactEmailError('sin-arroba')).toBe('Ingresá un email válido')
|
||||
})
|
||||
|
||||
test('acepta un email válido', () => {
|
||||
expect(contactEmailError('lucas@example.com')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('paymentPresentation', () => {
|
||||
const today = new Date('2026-10-01T12:00:00.000Z')
|
||||
|
||||
test('un cobro pendiente alimenta la sección y el chip', () => {
|
||||
expect(
|
||||
paymentPresentation(
|
||||
{ status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||
today,
|
||||
),
|
||||
).toEqual({
|
||||
periodLabel: 'Octubre 2026',
|
||||
statusLabel: 'Pendiente',
|
||||
chipLabel: 'Debe octubre',
|
||||
isDue: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('un cobro pagado se muestra al día', () => {
|
||||
expect(
|
||||
paymentPresentation(
|
||||
{ status: 'PAID', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||
today,
|
||||
).chipLabel,
|
||||
).toBe('Al día')
|
||||
})
|
||||
|
||||
test('sin cobro registrado no inventa un pendiente', () => {
|
||||
expect(paymentPresentation(null, today)).toEqual({
|
||||
periodLabel: 'Octubre 2026',
|
||||
statusLabel: 'Sin cobro registrado',
|
||||
chipLabel: 'Al día',
|
||||
isDue: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatNotesUpdatedAt', () => {
|
||||
test('usa hoy cuando la edición fue en la misma fecha', () => {
|
||||
expect(
|
||||
formatNotesUpdatedAt('2026-10-01T08:00:00.000Z', new Date('2026-10-01T18:00:00.000Z')),
|
||||
).toBe('Editado hoy')
|
||||
})
|
||||
|
||||
test('usa una fecha corta para ediciones anteriores', () => {
|
||||
expect(
|
||||
formatNotesUpdatedAt('2026-09-29T08:00:00.000Z', new Date('2026-10-01T18:00:00.000Z')),
|
||||
).toBe('Editado 29 sep 2026')
|
||||
})
|
||||
})
|
||||
|
||||
describe('foco inicial de los formularios del miembro', () => {
|
||||
test('el formulario de contacto enfoca el teléfono', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
createElement(AttendeeContactForm, {
|
||||
phone: '',
|
||||
email: '',
|
||||
error: null,
|
||||
isSaving: false,
|
||||
onPhoneChange: () => {},
|
||||
onEmailChange: () => {},
|
||||
onCancel: () => {},
|
||||
onSave: () => {},
|
||||
}),
|
||||
)
|
||||
|
||||
expect(markup).toMatch(/<input[^>]*autofocus=""[^>]*aria-label="Teléfono"/)
|
||||
})
|
||||
|
||||
test('el formulario de notas enfoca el textarea', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
createElement(AttendeeNotesForm, {
|
||||
draft: '',
|
||||
error: null,
|
||||
isSaving: false,
|
||||
onDraftChange: () => {},
|
||||
onCancel: () => {},
|
||||
onSave: () => {},
|
||||
}),
|
||||
)
|
||||
|
||||
expect(markup).toMatch(/<textarea[^>]*autofocus=""[^>]*aria-label="Notas del miembro"/)
|
||||
})
|
||||
})
|
||||
@@ -11,12 +11,15 @@ describe('isImmersiveRoute', () => {
|
||||
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
|
||||
})
|
||||
|
||||
test('las rutas hijas del grupo no lo son', () => {
|
||||
test('el detalle de miembro también es immersive', () => {
|
||||
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(true)
|
||||
})
|
||||
|
||||
test('las demás rutas hijas del grupo no lo son', () => {
|
||||
expect(isImmersiveRoute('/groups')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/new')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/cm1234/attendees/new')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(false)
|
||||
})
|
||||
|
||||
test('el resto de la app mantiene el header global', () => {
|
||||
|
||||
@@ -59,6 +59,28 @@ export const AttendeePaymentSummarySchema = z.object({
|
||||
});
|
||||
export type AttendeePaymentSummary = z.output<typeof AttendeePaymentSummarySchema>;
|
||||
|
||||
export const AttendeeDetailDtoSchema = AttendeeDtoSchema.extend({
|
||||
payment: AttendeePaymentSummarySchema.nullable(),
|
||||
});
|
||||
export type AttendeeDetailDto = z.output<typeof AttendeeDetailDtoSchema>;
|
||||
|
||||
const EditableAttendeeFieldsSchema = z.object({
|
||||
phone: z.string().trim().nullable(),
|
||||
email: z
|
||||
.string()
|
||||
.trim()
|
||||
.email('Ingresá un email válido')
|
||||
.or(z.literal(''))
|
||||
.nullable(),
|
||||
notes: z.string().trim().nullable(),
|
||||
});
|
||||
|
||||
export const UpdateAttendeeSchema = EditableAttendeeFieldsSchema.partial().refine(
|
||||
(value) => Object.keys(value).length > 0,
|
||||
'Enviá al menos un campo para actualizar',
|
||||
);
|
||||
export type UpdateAttendee = z.output<typeof UpdateAttendeeSchema>;
|
||||
|
||||
/**
|
||||
* Member listing item: `AttendeeDto` plus the summary the row needs so it does
|
||||
* not run dry of data. It is a superset, so every consumer of the plain DTO
|
||||
|
||||
Reference in New Issue
Block a user