From faf949fc9bbba4b0be816fa6bde2489ff89f939b Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Thu, 1 Oct 2026 18:41:55 -0300 Subject: [PATCH 1/2] feat(attendee-detail): enhance attendee detail view with payment and notes sections - Added payment presentation logic to display payment status and due dates. - Introduced AttendeeNotesSection and AttendeePaymentsSection components for managing notes and payments. - Implemented forms for editing contact information and notes with validation. - Updated API to support attendee updates and added corresponding tests. - Improved attendance summary logic to reflect all visible sessions. - Enhanced UI with loading states and error handling for better user experience. --- AGENTS.md | 1 + .../features/get-attendee-history/use-case.ts | 6 +- .../attendees/features/get-by-id/use-case.ts | 32 +++- .../attendees/features/update/route.ts | 24 +++ .../attendees/features/update/use-case.ts | 44 +++++ .../src/modules/attendees/lib/helpers.ts | 13 +- apps/backend/src/modules/groups/routes.ts | 4 +- apps/backend/test/analytics.test.ts | 17 +- apps/backend/test/attendee-get-by-id.test.ts | 18 ++ apps/backend/test/attendee-update.test.ts | 99 +++++++++++ apps/web/src/components/layout/LargeTitle.tsx | 65 ++++++-- .../attendee-detail/AbsenceLinkSection.tsx | 6 +- .../attendee-detail/AttendeeActionsMenu.tsx | 67 ++++++-- .../AttendeeAttendanceSection.tsx | 6 - .../AttendeeContactActions.tsx | 81 +++++---- .../attendee-detail/AttendeeContactForm.tsx | 81 +++++++++ .../AttendeeContactSection.tsx | 156 ++++++++++++++---- .../AttendeeDetailProvider.tsx | 44 ++++- .../attendee-detail/AttendeeDetailView.tsx | 136 ++++++++------- .../attendee-detail/AttendeeNotesForm.tsx | 47 ++++++ .../attendee-detail/AttendeeNotesSection.tsx | 70 ++++++++ .../AttendeePaymentsSection.tsx | 39 +++++ .../src/features/attendee-detail/Section.tsx | 16 +- .../features/attendee-detail/attendance.ts | 31 +--- .../src/features/attendee-detail/detail.ts | 79 +++++++++ apps/web/src/lib/api.ts | 16 +- apps/web/src/lib/immersive-routes.ts | 1 + apps/web/test/attendee-attendance.test.ts | 16 +- apps/web/test/attendee-detail.test.ts | 108 ++++++++++++ apps/web/test/immersive-routes.test.ts | 7 +- packages/shared/src/schemas/attendees.ts | 24 ++- 31 files changed, 1129 insertions(+), 225 deletions(-) create mode 100644 apps/backend/src/modules/attendees/features/update/route.ts create mode 100644 apps/backend/src/modules/attendees/features/update/use-case.ts create mode 100644 apps/backend/test/attendee-update.test.ts create mode 100644 apps/web/src/features/attendee-detail/AttendeeContactForm.tsx create mode 100644 apps/web/src/features/attendee-detail/AttendeeNotesForm.tsx create mode 100644 apps/web/src/features/attendee-detail/AttendeeNotesSection.tsx create mode 100644 apps/web/src/features/attendee-detail/AttendeePaymentsSection.tsx create mode 100644 apps/web/src/features/attendee-detail/detail.ts create mode 100644 apps/web/test/attendee-detail.test.ts diff --git a/AGENTS.md b/AGENTS.md index b7876c2..6298e14 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `
`, `
` 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 `
`. (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 ``; nada más. En las tres pantallas el `

` 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 `
` 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. diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts index 09a2b85..8001e47 100644 --- a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts @@ -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 }, @@ -80,4 +80,4 @@ export class GetAttendeeHistory { sessions: orderedSessions, }); } -} \ No newline at end of file +} diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts index fac192b..0f9e987 100644 --- a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts @@ -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; + now?: () => Date; }; export class GetAttendee { @@ -18,7 +19,7 @@ export class GetAttendee { groupId: string, attendeeId: string, userId: string, - ): Promise> { + ): Promise> { 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)), + }; +} diff --git a/apps/backend/src/modules/attendees/features/update/route.ts b/apps/backend/src/modules/attendees/features/update/route.ts new file mode 100644 index 0000000..507b5ac --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update/route.ts @@ -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; diff --git a/apps/backend/src/modules/attendees/features/update/use-case.ts b/apps/backend/src/modules/attendees/features/update/use-case.ts new file mode 100644 index 0000000..e288e80 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update/use-case.ts @@ -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; +}; + +type UpdateAttendeeCommand = { + groupId: string; + attendeeId: string; + userId: string; + input: UpdateAttendee; +}; + +export class UpdateAttendeeDetails { + constructor(private readonly deps: UpdateAttendeeDeps = {}) {} + + async execute(command: UpdateAttendeeCommand): Promise> { + 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]), + ); +} diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index d3b86bb..06ac783 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -1,4 +1,4 @@ -import type { AttendeeDto, 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 { diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index 603ca8b..3ee336e 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -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,7 +29,8 @@ routes.route('/', groupWaitlistRoutes); routes.route('/', groupPreRegistrationRoutes); routes.route('/', analyticsRoutes); routes.route('/', getAttendeeRoute); +routes.route('/', updateAttendeeRoute); routes.route('/', getAttendeeStatsRoute); routes.route('/', removeAttendeeRoute); -export default routes; \ No newline at end of file +export default routes; diff --git a/apps/backend/test/analytics.test.ts b/apps/backend/test/analytics.test.ts index a18c404..ebc9fa4 100644 --- a/apps/backend/test/analytics.test.ts +++ b/apps/backend/test/analytics.test.ts @@ -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 () => { @@ -322,4 +335,4 @@ describe('analytics routes', () => { expect(res.status).toBe(401); }); }); -}); \ No newline at end of file +}); diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts index d992f7d..aed0da3 100644 --- a/apps/backend/test/attendee-get-by-id.test.ts +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -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 }, + }, + }, }); }); diff --git a/apps/backend/test/attendee-update.test.ts b/apps/backend/test/attendee-update.test.ts new file mode 100644 index 0000000..ad2f63e --- /dev/null +++ b/apps/backend/test/attendee-update.test.ts @@ -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() + }) +}) diff --git a/apps/web/src/components/layout/LargeTitle.tsx b/apps/web/src/components/layout/LargeTitle.tsx index 57c2510..1bfd246 100644 --- a/apps/web/src/components/layout/LargeTitle.tsx +++ b/apps/web/src/components/layout/LargeTitle.tsx @@ -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} - - {barTrailing ? ( + {barContext ? ( +
+ + {barContext} + + +
+ ) : ( + )} + {barContext ?