feat(api): add timezone support for group fetching and increase page size

feat(attendance): refactor attendance summary logic and update tests

feat(analytics): extend GroupRiskSummary schema with absence and attendance counts

feat(groups): enhance group schema with attendee and waitlist counts

chore(skills): add frontend design skill with guidelines and license

feat(attendee-detail): implement AttendeePhoneLine component for phone display

feat(groups): create AttendanceBadge and CapacityIndicator components for group cards

feat(groups): add card utility functions for attendance alerts and capacity summaries

test(groups): implement tests for attendance alert and capacity summary logic
This commit is contained in:
Jose Selesan
2026-09-30 17:39:13 -03:00
parent 4e86096653
commit 454f20ed25
31 changed files with 1323 additions and 250 deletions

View File

@@ -12,6 +12,8 @@ import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import {
classifyRisk,
MIN_RISK_ABSENCE_STREAK,
MIN_RISK_MONTHLY_RATE,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
@@ -38,7 +40,8 @@ type AttendanceRow = {
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
// alguno en riesgo moderado y NONE en caso contrario.
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -90,6 +93,12 @@ export class GetGroupsRiskOverview {
const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
// a racha y aun así quedan por debajo del mínimo de asistencia.
const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>();
for (const attendee of attendees) {
const groupId = attendeeGroup.get(attendee.id)!;
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
@@ -106,6 +115,12 @@ export class GetGroupsRiskOverview {
continue;
}
if (streak >= MIN_RISK_ABSENCE_STREAK) {
bump(absenceStreakCountByGroup, groupId);
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
bump(lowAttendanceCountByGroup, groupId);
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if (
riskLevel === 'HIGH' ||
@@ -119,12 +134,18 @@ export class GetGroupsRiskOverview {
groupId: group.id,
groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
}));
return ok({ items });
}
}
function bump(counter: Map<string, number>, key: string) {
counter.set(key, (counter.get(key) ?? 0) + 1);
}
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) {

View File

@@ -5,6 +5,12 @@ export type AttendanceStreamEntry = {
export type RiskLevel = 'HIGH' | 'MEDIUM';
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
export const MIN_RISK_ABSENCE_STREAK = 2;
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
export const MIN_RISK_MONTHLY_RATE = 50;
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
@@ -46,10 +52,10 @@ export function classifyRisk(
consecutiveAbsences: number,
monthlyRate: number,
): RiskLevel | null {
if (consecutiveAbsences >= 3) {
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
return 'HIGH';
}
if (consecutiveAbsences === 2 || monthlyRate < 50) {
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
return 'MEDIUM';
}
return null;

View File

@@ -8,17 +8,30 @@ import type {
import { ok } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma';
import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler';
import {
buildGroupWhereForUser,
type GroupDb,
type GroupRecord,
toGroupDto,
type GroupListRecord,
toGroupListItemDto,
} from '../../lib';
type ListGroupsDeps = {
db?: Pick<GroupDb, 'group'>;
now?: Date;
};
const OCCUPANCY_COUNT_INCLUDE = {
_count: {
select: {
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
attendees: true,
// Lista de espera: los que todavía esperan cupo (los revisados salen).
waitlist: { where: { status: 'PENDING' as const } },
},
},
} satisfies Prisma.GroupInclude;
export class ListGroups {
constructor(private readonly deps: ListGroupsDeps = {}) {}
@@ -27,21 +40,59 @@ export class ListGroups {
userId: string,
): Promise<Result<GroupList, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
const [records, total] = await Promise.all([
db.group.findMany({
where,
skip: getPaginationOffset(query),
take: query.pageSize,
orderBy: { createdAt: 'desc' },
}),
db.group.count({ where }),
]);
// Traemos los grupos del usuario con sus contadores y los ordenamos acá:
// la próxima clase se deriva de días + hora, no hay columna por la que
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la
// zona horaria de la persona (o la del servidor si no viaja).
const records: GroupListRecord[] = await db.group.findMany({
where,
include: OCCUPANCY_COUNT_INCLUDE,
});
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;
const withNextClass = records.map((record) => ({
record,
nextAt: nextOccurrenceAt(record, now, timeZone),
}));
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
que era el criterio anterior de la lista. */
const ordered = withNextClass.sort((a, b) => {
if (a.nextAt !== null && b.nextAt !== null) {
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();
}
if (a.nextAt !== null) {
return -1;
}
if (b.nextAt !== null) {
return 1;
}
return b.record.createdAt.getTime() - a.record.createdAt.getTime();
});
const offset = getPaginationOffset(query);
const page = ordered.slice(offset, offset + query.pageSize);
return ok({
data: records.map((record: GroupRecord) => toGroupDto(record)),
pagination: getPaginationMetadata(query, total),
data: page.map(({ record }) => toGroupListItemDto(record)),
pagination: getPaginationMetadata(query, ordered.length),
});
}
}
}
function nextOccurrenceAt(record: GroupListRecord, now: Date, timeZone: string): number | null {
if (!record.days?.length || !record.time) {
return null;
}
const occurrence = nextClassOccurrence({
days: record.days,
time: record.time,
now,
timeZone,
});
return occurrence ? occurrence.occurrenceAt.getTime() : null;
}

View File

@@ -1,5 +1,5 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingType, GroupDto, WeekDay } from '@gruperly/shared';
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
@@ -21,6 +21,14 @@ export type GroupRecord = {
inviteToken?: string | null;
};
/* El listado suma los contadores de ocupación a cada grupo para que la card los
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de
espera solo los que siguen esperando cupo (PENDING). */
export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number };
};
export function toGroupDto(record: GroupRecord): GroupDto {
return {
id: record.id,
@@ -39,6 +47,14 @@ export function toGroupDto(record: GroupRecord): GroupDto {
};
}
export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
return {
...toGroupDto(record),
attendeesCount: record._count?.attendees ?? 0,
waitlistCount: record._count?.waitlist ?? 0,
};
}
export function buildGroupWhereForUser(userId: string) {
return {
OR: [