Files
gruperly/apps/backend/src/modules/attendees/features/get-stats/use-case.ts
Jose Selesan 02af5e3c11 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.
2026-09-28 16:16:21 -03:00

60 lines
1.8 KiB
TypeScript

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