feat: add attendee detail and stats features

- Implemented API endpoints to fetch attendee details and statistics.
- Created new route for fetching attendee by ID and their attendance stats.
- Added schemas for attendee statistics.
- Developed frontend components to display attendee details and attendance statistics.
- Integrated attendee detail provider to manage state and data fetching.
- Added tests for attendee retrieval and statistics calculation.
This commit is contained in:
Jose Selesan
2026-09-28 16:16:21 -03:00
parent e736ed3547
commit 02af5e3c11
22 changed files with 997 additions and 232 deletions

View File

@@ -0,0 +1,20 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetAttendee } from './use-case';
const route = new Hono();
route.get('/:groupId/attendees/:attendeeId', async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const groupId = c.req.param('groupId');
const attendeeId = c.req.param('attendeeId');
const useCase = new GetAttendee();
const result = await useCase.execute(groupId, attendeeId, user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,36 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, 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';
type GetAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
};
export class GetAttendee {
constructor(private readonly deps: GetAttendeeDeps = {}) {}
async execute(
groupId: string,
attendeeId: string,
userId: string,
): Promise<Result<AttendeeDto, ProblemDetails>> {
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));
}
return ok(toAttendeeDto(attendee));
}
}

View File

@@ -0,0 +1,20 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetAttendeeStats } from './use-case';
const route = new Hono();
route.get('/:groupId/attendees/:attendeeId/stats', async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const groupId = c.req.param('groupId');
const attendeeId = c.req.param('attendeeId');
const useCase = new GetAttendeeStats();
const result = await useCase.execute(groupId, attendeeId, user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,59 @@
import type { AttendanceStatus, PrismaClient } from '@generated/prisma/client';
import type { AttendeeStats, 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';
type GetAttendeeStatsDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'attendance'>;
};
export class GetAttendeeStats {
constructor(private readonly deps: GetAttendeeStatsDeps = {}) {}
async execute(
groupId: string,
attendeeId: string,
userId: string,
): Promise<Result<AttendeeStats, ProblemDetails>> {
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 },
select: { id: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
const rows = await db.attendance.groupBy({
by: ['status'],
where: { attendeeId },
_count: { _all: true },
});
const countByStatus = (status: AttendanceStatus): number =>
rows.find((row) => row.status === status)?._count._all ?? 0;
const presentCount = countByStatus('PRESENT');
const absentCount = countByStatus('ABSENT');
const excusedCount = countByStatus('EXCUSED');
const totalMarked = presentCount + absentCount + excusedCount;
return ok({
attendeeId,
groupId,
presentCount,
absentCount,
excusedCount,
totalMarked,
attendanceRate: totalMarked > 0 ? Math.round((presentCount / totalMarked) * 100) : 0,
});
}
}

View File

@@ -3,6 +3,8 @@ import analyticsRoutes from '../analytics/routes';
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
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 groupWaitlistRoutes from '../group-waitlist/routes';
import createGroupRoute from './features/create/route';
@@ -23,6 +25,8 @@ routes.route('/', getByIdRoute);
routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes);
routes.route('/', analyticsRoutes);
routes.route('/', getAttendeeRoute);
routes.route('/', getAttendeeStatsRoute);
routes.route('/', removeAttendeeRoute);
export default routes;

View File

@@ -12,7 +12,6 @@ const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
return { status, occurredAt: at(offsetDays) };
}
describe('trailingAbsentStreak', () => {
it('devuelve 0 sin registros', () => {
expect(trailingAbsentStreak([])).toBe(0);
@@ -34,13 +33,14 @@ describe('trailingAbsentStreak', () => {
describe('lastAttendedAt', () => {
it('devuelve la clase PRESENT más reciente', () => {
const now = Date.now();
const result = lastAttendedAt([
entry('PRESENT', 0),
{ status: 'PRESENT', occurredAt: new Date(now) },
entry('ABSENT', 7),
entry('ABSENT', 14),
]);
expect(result).not.toBeNull();
expect(result?.getTime()).toBe(at(0).getTime());
expect(result?.getTime()).toBe(now);
});
it('devuelve null si nunca asistió', () => {

View File

@@ -0,0 +1,105 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import getAttendeeRoute from '@/modules/attendees/features/get-by-id/route';
const userId = 'user-1';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/groups', getAttendeeRoute);
return app;
}
function makeGroup(overrides: Record<string, unknown> = {}) {
return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides };
}
const attendee = {
id: 'a-1',
groupId: 'group-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
};
describe('GET /groups/:groupId/attendees/:attendeeId', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('devuelve el participante del grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(attendee);
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
id: 'a-1',
groupId: 'group-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
notifyToken: 'token-1',
createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z',
});
});
it('devuelve 404 si el participante no pertenece al grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/nope');
expect(res.status).toBe(404);
expect(await res.json()).toMatchObject({ code: 'not_found' });
});
it('devuelve 403 si el usuario no tiene acceso al grupo', async () => {
prisma.group.findUnique.mockResolvedValue(
makeGroup({ createdById: 'otro-user', members: [] }),
);
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
expect(res.status).toBe(403);
expect(await res.json()).toMatchObject({ code: 'group_access_denied' });
});
it('devuelve 401 si no hay sesión', async () => {
const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1');
expect(res.status).toBe(401);
});
});

View File

@@ -0,0 +1,126 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
},
attendance: {
groupBy: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import getAttendeeStatsRoute from '@/modules/attendees/features/get-stats/route';
const userId = 'user-1';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/groups', getAttendeeStatsRoute);
return app;
}
function makeGroup(overrides: Record<string, unknown> = {}) {
return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides };
}
function countRow(status: string, count: number) {
return { status, _count: { _all: count } };
}
describe('GET /groups/:groupId/attendees/:attendeeId/stats', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('cuenta asistencias, ausencias y justificadas con su porcentaje', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' });
prisma.attendance.groupBy.mockResolvedValue([
countRow('PRESENT', 17),
countRow('ABSENT', 2),
countRow('EXCUSED', 1),
]);
const res = await makeApp({ id: userId }).request(
'/groups/group-1/attendees/a-1/stats',
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
attendeeId: 'a-1',
groupId: 'group-1',
presentCount: 17,
absentCount: 2,
excusedCount: 1,
totalMarked: 20,
attendanceRate: 85,
});
});
it('devuelve conteos en cero cuando el participante no tiene registros', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' });
prisma.attendance.groupBy.mockResolvedValue([]);
const res = await makeApp({ id: userId }).request(
'/groups/group-1/attendees/a-1/stats',
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
attendeeId: 'a-1',
groupId: 'group-1',
presentCount: 0,
absentCount: 0,
excusedCount: 0,
totalMarked: 0,
attendanceRate: 0,
});
});
it('devuelve 404 si el participante no pertenece al grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request(
'/groups/group-1/attendees/nope/stats',
);
expect(res.status).toBe(404);
expect(await res.json()).toMatchObject({ code: 'not_found' });
});
it('devuelve 403 si el usuario no tiene acceso al grupo', async () => {
prisma.group.findUnique.mockResolvedValue(
makeGroup({ createdById: 'otro-user', members: [] }),
);
const res = await makeApp({ id: userId }).request(
'/groups/group-1/attendees/a-1/stats',
);
expect(res.status).toBe(403);
expect(await res.json()).toMatchObject({ code: 'group_access_denied' });
});
it('devuelve 401 si no hay sesión', async () => {
const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1/stats');
expect(res.status).toBe(401);
});
});