Files
gruperly/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts
Jose Selesan 90f31290d4 feat(web): pulido mobile de ficha de grupo, alumno, nuevo grupo y ajustes
- Ficha de grupo: "Agregar miembro" a todo el ancho y debajo Estadísticas,
  Cobrar y Compartir con icono y texto (antes iconos sueltos en mobile).
  Los mensajes automáticos de WhatsApp quedan en una fila plegable que
  arranca cerrada si no hay ninguno activo.
- Historial del alumno: arranca en la primera clase registrada si es
  anterior al alta, como la lista y la regla de riesgo ("1 de 5" en ambos).
- Nuevo grupo: cupo 10 por defecto, precio vacío obligatorio y foco
  inicial en el nombre.
- Ajustes: chevron en Seguridad; el botón de tema del header queda solo
  en desktop (en mobile vive en Apariencia).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:33:37 -03:00

97 lines
3.2 KiB
TypeScript

import type { PrismaClient } from '@generated/prisma/client';
import type {
AttendanceStatus,
AttendeeHistory,
ProblemDetails,
Result,
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
export const HISTORY_SESSIONS_LIMIT = 20;
type GetAttendeeHistoryDeps = {
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
};
export class GetAttendeeHistory {
constructor(private readonly deps: GetAttendeeHistoryDeps = {}) {}
async execute(
groupId: string,
attendeeId: string,
userId: string,
): Promise<Result<AttendeeHistory, 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, fullName: true, createdAt: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
// Same effective join date as the risk rule (`toMemberAttendance`): an
// attendee loaded after their first classes were already recorded starts
// at that first class, not at `createdAt`. Otherwise this screen said
// "1 de 3 clases" while the group list said "1 de 5" for the same person.
const firstAttendance = await db.attendance.findFirst({
where: { attendeeId },
orderBy: { classSession: { startsAt: 'asc' } },
select: { classSession: { select: { startsAt: true } } },
});
const firstClassAt = firstAttendance?.classSession.startsAt;
const since =
firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt;
const sessions = await db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
orderBy: { startsAt: 'desc' },
take: HISTORY_SESSIONS_LIMIT,
select: { id: true, startsAt: true },
});
const sessionIds = sessions.map((session) => session.id);
const attendances = sessionIds.length
? await db.attendance.findMany({
where: { attendeeId, classSessionId: { in: sessionIds } },
select: { classSessionId: true, status: true },
})
: [];
const statusBySession = new Map<string, AttendanceStatus>(
attendances.map((record) => [record.classSessionId, record.status]),
);
const orderedSessions = sessions
.slice()
.reverse()
.map((session) => ({
classSessionId: session.id,
startsAt: session.startsAt.toISOString(),
status: statusBySession.get(session.id) ?? null,
}));
const presentCount = attendances.filter((record) => record.status === 'PRESENT').length;
const attendanceRate =
sessions.length > 0 ? Math.round((presentCount / sessions.length) * 100) : 0;
return ok({
attendeeId: attendee.id,
fullName: attendee.fullName,
groupId,
groupName: access.value.name,
attendanceRate,
sessions: orderedSessions,
});
}
}