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.
This commit is contained in:
Jose Selesan
2026-10-01 18:41:55 -03:00
parent 6d120f4b1f
commit faf949fc9b
31 changed files with 1129 additions and 225 deletions

View File

@@ -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,
});
}
}
}

View File

@@ -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)),
};
}

View 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;

View File

@@ -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]),
);
}

View File

@@ -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 {

View File

@@ -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;
export default routes;

View File

@@ -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);
});
});
});
});

View File

@@ -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 },
},
},
});
});

View 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()
})
})