feat: rediseño de Grupos y pantalla "Requiere atención"

- Grupos: subtítulo con resumen (grupos · alumnos · lugares libres),
  sección "Requiere atención" con los 4 alumnos más urgentes y tarjetas
  con avatares (punteados por lugar libre en grupos chicos, superpuestos
  con "+N" en grandes; con alerta primero y anillo de gravedad).
- Pantalla nueva /groups/attention: filtros Todos/Asistencia/Pagos,
  secciones Urgente y A vigilar, Contactar / Enviar recordatorio por
  wa.me y "Resuelto" persistente con update optimista.
- FAB "Nuevo grupo" que se pliega al scrollear (respeta reduced motion);
  los toasts en mobile suben para no quedar debajo.
- Alertas centralizadas en computeStudentAlerts (shared). La regla de
  asistencia pasa a: urgente = 3 seguidas o 4 de las últimas 6; a vigilar
  = 2 de las últimas 4 (sin inactividad por días ni tendencia). Cuotas:
  1 vencida vigilar, 2+ urgente.
- Backend: GET /attention y POST /attention/:attendeeId/resolve; tabla
  attendee_alert_resolutions (la alerta vuelve si cambia la firma).
- Tokens de gravedad para claro y oscuro; se quita el indicador de pills.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-27 16:35:07 -03:00
parent 90f31290d4
commit b99bc4d519
48 changed files with 2333 additions and 1379 deletions

View File

@@ -0,0 +1,20 @@
-- CreateEnum
CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT');
-- CreateTable
CREATE TABLE "attendee_alert_resolutions" (
"id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"kind" "StudentAlertKind" NOT NULL,
"signature" TEXT NOT NULL,
"resolved_by_id" TEXT NOT NULL,
"resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind");
-- AddForeignKey
ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -90,11 +90,34 @@ model Attendee {
attendances Attendance[]
slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[]
@@index([groupId], map: "attendees_groupId_idx")
@@map("attendees")
}
enum StudentAlertKind {
ATTENDANCE
PAYMENT
}
// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
// it hides the alert while its signature (last absence / overdue fees) stays
// the same, so a new absence or a new overdue fee brings it back on its own.
model AttendeeAlertResolution {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
kind StudentAlertKind
signature String
resolvedById String @map("resolved_by_id")
resolvedAt DateTime @default(now()) @map("resolved_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@unique([attendeeId, kind])
@@map("attendee_alert_resolutions")
}
model Payment {
id String @id @default(cuid())
groupId String @map("group_id")

View File

@@ -16,6 +16,7 @@ import {
studentStatusRoutes,
} from './modules/analytics';
import { attendeesRoutes } from './modules/attendees';
import { attentionRoutes } from './modules/attention';
import { authRoutes } from './modules/auth';
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
import { classesRoutes } from './modules/classes';
@@ -65,6 +66,7 @@ api.route('/waitlist', waitlistRoutes);
api.route('/classes', classesRoutes);
api.route('/students', studentStatusRoutes);
api.route('/groups-risk', groupsRiskOverviewRoute);
api.route('/attention', attentionRoutes);
app.notFound((c) => {
return problemJson(c, notFoundProblem(c.req.path));

View File

@@ -3,7 +3,7 @@ import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberCla
/* How many classes we look back per attendee. That is the real ceiling of the
model: `class_sessions` are not created on their own, they get materialized
when someone opens "today's classes", so pulling years of rows makes no
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
sense. 20 classes is enough for the streak, for the 6-class window and for
the attendance rate the card shows. */
export const MEMBER_HISTORY_LIMIT = 20;

View File

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

View File

@@ -0,0 +1,174 @@
import type { Prisma } from '@generated/prisma/client';
import type {
AttendanceStatus,
AttentionGroup,
AttentionMember,
AttentionOverview,
ProblemDetails,
Result,
StudentAlertType,
} from '@gruperly/shared';
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = {
db?: {
group: Prisma.GroupDelegate;
attendee: Prisma.AttendeeDelegate;
classSession: Prisma.ClassSessionDelegate;
attendance: Prisma.AttendanceDelegate;
payment: Prisma.PaymentDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
user: Prisma.UserDelegate;
};
now?: Date;
};
type GroupRow = { id: string; name: string; capacity: number | null };
type AttendeeRow = {
id: string;
groupId: string;
fullName: string;
phone: string | null;
guardianPhone: string | null;
createdAt: Date;
};
type SessionRow = { id: string; groupId: string; startsAt: Date };
type AttendanceRow = {
attendeeId: string;
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
type PaymentRow = {
id: string;
attendeeId: string;
amount: Prisma.Decimal;
currency: string;
dueDate: Date;
checkoutUrl: string | null;
};
type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string };
/* Every ACTIVE member of the user's groups with their alerts ("Requiere
atención"). The list screen draws all the avatars from here, so it returns
members without alerts too. The rule is `computeStudentAlerts` (shared) over
the same attendance input the risk overview builds (`toMemberAttendance`). */
export class GetAttentionOverview {
constructor(private readonly deps: GetAttentionOverviewDeps = {}) {}
async execute(userId: string): Promise<Result<AttentionOverview, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const groups = (await db.group.findMany({
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
select: { id: true, name: true, capacity: true },
orderBy: { createdAt: 'asc' },
})) as GroupRow[];
if (groups.length === 0) {
return ok({ groups: [] });
}
const groupIds = groups.map((group) => group.id);
const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([
// Phones are stored the way people write them (`11 2345-6789`): the
// professor's country settles the calling code, as in the WhatsApp jobs.
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>,
// Past classes only, most recent first: `toMemberAttendance` keeps the
// last 20 per attendee, more than the 6-class window needs.
db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { lte: now } },
select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>,
db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
}) as Promise<AttendanceRow[]>,
db.payment.findMany({
where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' } },
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
orderBy: { dueDate: 'asc' },
}) as Promise<PaymentRow[]>,
db.attendeeAlertResolution.findMany({
where: { attendee: { groupId: { in: groupIds } } },
select: { attendeeId: true, kind: true, signature: true },
}) as Promise<ResolutionRow[]>,
]);
const country = countryCodeSchema.safeParse(owner?.country);
const sessionsByGroup = groupBy(sessions, (session) => session.groupId);
const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId);
const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId);
const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId);
const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId);
const items: AttentionGroup[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
capacity: group.capacity,
members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => {
const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({
id: payment.id,
amount: Number(payment.amount),
currency: payment.currency,
dueDate: payment.dueDate.toISOString(),
checkoutUrl: payment.checkoutUrl,
}));
const alerts = computeStudentAlerts(
{
attendance: toMemberAttendance(
attendee,
sessionsByGroup.get(group.id) ?? [],
attendanceByAttendee.get(attendee.id) ?? [],
),
overduePayments,
},
now,
);
const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({
tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType,
firma: row.signature,
}));
const phone = attendee.phone ?? attendee.guardianPhone;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
phone,
whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null,
alerts: applyResolutions(alerts, resolved),
overduePayments,
};
}),
}));
return ok({ groups: items });
}
}
function groupBy<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
const map = new Map<string, T[]>();
for (const row of rows) {
const list = map.get(key(row)) ?? [];
list.push(row);
map.set(key(row), list);
}
return map;
}

View File

@@ -0,0 +1,23 @@
import type { ResolveAlert } from '@gruperly/shared';
import { ResolveAlertSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { ResolveStudentAlert } from './use-case';
const route = new Hono();
route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const payload = c.req.valid('json') as ResolveAlert;
const useCase = new ResolveStudentAlert();
const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,49 @@
import type { Prisma } from '@generated/prisma/client';
import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind';
type ResolveAlertDeps = {
db?: {
attendee: Prisma.AttendeeDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
};
};
export type ResolveAlertResult = ResolveAlert & { attendeeId: string };
/* "Resuelto": stores the signature of the alert the professor saw. One row per
attendee and type, overwritten on each resolve, so the table never grows past
two rows per attendee. An attendee outside the user's groups is a 404, not a
403: we don't confirm that the id exists. */
export class ResolveStudentAlert {
constructor(private readonly deps: ResolveAlertDeps = {}) {}
async execute(
attendeeId: string,
userId: string,
payload: ResolveAlert,
): Promise<Result<ResolveAlertResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput },
select: { id: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
const kind = ALERT_TYPE_TO_KIND[payload.tipo];
await db.attendeeAlertResolution.upsert({
where: { attendeeId_kind: { attendeeId, kind } },
create: { attendeeId, kind, signature: payload.firma, resolvedById: userId },
update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() },
});
return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma });
}
}

View File

@@ -0,0 +1 @@
export { default as attentionRoutes } from './routes';

View File

@@ -0,0 +1,13 @@
import type { StudentAlertKind } from '@generated/prisma/client';
import type { StudentAlertType } from '@gruperly/shared';
/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */
export const ALERT_KIND_TO_TYPE: Record<StudentAlertKind, StudentAlertType> = {
ATTENDANCE: 'asistencia',
PAYMENT: 'pago',
};
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
asistencia: 'ATTENDANCE',
pago: 'PAYMENT',
};

View File

@@ -0,0 +1,10 @@
import { Hono } from 'hono';
import getOverviewRoute from './features/get-overview/route';
import resolveRoute from './features/resolve/route';
const routes = new Hono();
routes.route('/', getOverviewRoute);
routes.route('/', resolveRoute);
export default routes;

View File

@@ -100,7 +100,7 @@ describe('GET /groups-risk/overview', () => {
});
});
it('cuenta el motivo: faltas seguidas o inactividad, sin repetir alumnos', async () => {
it('cuenta el motivo: faltas seguidas o faltas sueltas, sin repetir alumnos', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
prismaFetchAttendeeFindMany([
attendee('a-1', 'group-1'),
@@ -122,10 +122,13 @@ describe('GET /groups-risk/overview', () => {
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'PRESENT', at(3)),
// A single absence, but 14 days between their last presence and the
// class they missed (the ones in between have no record): inactivity.
// No streak (they came to s2), but 4 of their last 5 classes missed:
// high risk through the window, not through the streak.
attendance('a-2', 's1', 'ABSENT', at(1)),
attendance('a-2', 's7', 'PRESENT', at(15)),
attendance('a-2', 's2', 'PRESENT', at(2)),
attendance('a-2', 's3', 'ABSENT', at(3)),
attendance('a-2', 's4', 'ABSENT', at(4)),
attendance('a-2', 's7', 'ABSENT', at(15)),
// Ok.
attendance('a-3', 's1', 'PRESENT', at(1)),
attendance('a-3', 's2', 'PRESENT', at(2)),
@@ -268,8 +271,9 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
// would look like a streak of 2 and the group would land in attention; the
// middle class happened and has no record, so the real streak is 1.
// would look like a streak of 2; the middle class happened and has no
// record, so the real streak is 1. The level is still attention, but because
// of the short window (2 absences in the last marked classes), not the streak.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's3', 'ABSENT', at(3)),
@@ -280,13 +284,13 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].atencion).toBe(0);
expect(items[0].ok).toBe(1);
expect(items[0].atencion).toBe(1);
expect(items[0].absenceStreakCount).toBe(0);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'ok',
level: 'atencion',
consecutiveAbsences: 1,
daysSinceLastAttendance: 1,
// Both marked classes were absences; the middle one does not go into the average.
@@ -340,7 +344,8 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
// recent class (s1) is the one with no record. Since the streak is counted
// from the end and "no record" is not an absence, there is no streak: the
// asymmetry is there on purpose, because it is the same thing that already
// happens with an excused class.
// happens with an excused class. The two absences still fill the short
// window, so the level is attention without a streak.
prismaFetchAttendanceFindMany([
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
@@ -350,14 +355,14 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(0);
expect(items[0].atencion).toBe(1);
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].ok).toBe(1);
expect(items[0].absenceStreakCount).toBe(0);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'ok',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 0,

View File

@@ -14,9 +14,7 @@ import {
Two test-scaffold helpers:
- `dense` puts the classes on consecutive days, so that "how long since we
saw them" is always close by and the case isolates the rule it claims to
test (one class a week would trip the inactivity threshold almost always).
- `dense` puts the classes on consecutive days.
- `series` honors the offsets it is given, for the cases that do need gaps.
All dates hang off a fixed `NOW`: the function takes the moment as an
@@ -98,83 +96,46 @@ describe('getMemberAttendanceRisk', () => {
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok');
});
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
// A single absence, the most recent one: the streak doesn't reach. What drives
// the level is the time since they last showed up.
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
it('4 faltas en las últimas 6 clases dan riesgo alto aunque no haya racha', () => {
const { highWindowAbsences, highWindowSize } = ATTENDANCE_RISK_RULES;
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.daysSinceLastAttendance).toBe(30);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.highWindow).toEqual({ absences: highWindowAbsences, classes: highWindowSize });
expect(señales.level).toBe('riesgo_alto');
});
it('sin faltas después de la última presencia, la inactividad no cuenta', () => {
// The group stopped recording classes (or didn't meet): 30 days since the
// last presence, but the attendee missed nothing.
it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => {
const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.highWindow.absences).toBe(3);
expect(señales.attentionWindow).toEqual({ absences: 2, classes: 4 });
expect(señales.level).toBe('atencion');
});
it('2 faltas en las últimas 4 clases dan atención', () => {
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion');
});
it('una sola falta reciente no alcanza', () => {
const alumno = member(dense(['ABSENT', 'ABSENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT']));
// The two old absences fall outside the short window (last 4).
expect(summarizeMemberAttendance(alumno, NOW).attentionWindow.absences).toBe(1);
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
});
it('los días sin venir se informan pero no mueven el nivel', () => {
// The group stopped recording classes: 30 days since the last presence,
// but the attendee missed nothing.
const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.daysSinceLastAttendance).toBe(30);
expect(señales.level).toBe('ok');
});
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
// Two streak absences, the latest one yesterday: attention comes from the
// streak. Inactivity is measured from the last presence to the latest
// missed class, so exactly 10 days there does not move the level.
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
).toBe('atencion');
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 2]])), NOW),
).toBe('riesgo_alto');
});
it('la inactividad se mide contra las clases que faltó, no contra hoy', () => {
// They missed one class 20 days ago and the group hasn't met since: 25 days
// without seeing them, but only 5 of those had a class they skipped.
const alumno = member(series([['ABSENT', 20], ['PRESENT', 25]]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.daysSinceLastAttendance).toBe(25);
expect(señales.level).toBe('ok');
});
it('una tendencia a la baja da atención', () => {
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
// the only thing that can raise the alert.
const candidato = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
]));
const señales = summarizeMemberAttendance(candidato, NOW);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.daysSinceLastAttendance).toBe(1);
expect(señales.level).toBe('atencion');
});
it('perder una sola clase no es tendencia', () => {
// Same case as the previous one with one class fewer missed in the recent
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
const estable = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
]));
expect(getMemberAttendanceRisk(estable, NOW)).toBe('ok');
});
it('la tendencia necesita historia para las dos ventanas', () => {
// 5 marked classes: the previous window would be left with a single one, so
// there is nothing to compare against.
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
});
it('la racha manda sobre la tendencia', () => {
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
// absences and one attended class. The trend alone would give attention;
// the 3 trailing absences give high risk, which is what has to win.
it('tres faltas seguidas son riesgo alto con buena historia detrás', () => {
// 16 classes at 81%: the 3 trailing absences are what decides the level.
const alumno = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
@@ -187,13 +148,13 @@ describe('getMemberAttendanceRisk', () => {
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
// Absent, the middle one has no record, absent again. The real streak
// is one, not two.
// is one, not two; the two absences still fill the short window.
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(conHueco, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
expect(señales.level).toBe('atencion');
});
it('una clase justificada es la clase que no cuenta', () => {
@@ -204,13 +165,14 @@ describe('getMemberAttendanceRisk', () => {
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
expect(señales.attentionWindow).toEqual({ absences: 2, classes: 2 });
});
it('avisar de la falta tampoco encadena las de alrededor', () => {
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0);
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
// No streak, but the two absences are still recent: attention, not high.
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion');
});
it('no le importa el orden en que llegan las clases', () => {

View File

@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { Prisma } from '@generated/prisma/client';
import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case';
import { ResolveStudentAlert } from '@/modules/attention/features/resolve/use-case';
const NOW = new Date('2026-10-27T20:00:00.000Z');
const DAY_MS = 24 * 60 * 60 * 1000;
const at = (days: number) => new Date(NOW.getTime() - days * DAY_MS);
const db = {
group: { findMany: mock() },
attendee: { findMany: mock(), findFirst: mock() },
classSession: { findMany: mock() },
attendance: { findMany: mock() },
payment: { findMany: mock() },
attendeeAlertResolution: { findMany: mock(), upsert: mock() },
user: { findUnique: mock() },
};
function overview() {
return new GetAttentionOverview({ db: db as never, now: NOW });
}
beforeEach(() => {
for (const delegate of Object.values(db)) {
for (const fn of Object.values(delegate)) fn.mockReset();
}
});
describe('GetAttentionOverview', () => {
it('sin grupos no consulta nada más', async () => {
db.group.findMany.mockResolvedValue([]);
const result = await overview().execute('user-1');
expect(result).toEqual({ ok: true, value: { groups: [] } });
expect(db.attendee.findMany).not.toHaveBeenCalled();
});
it('devuelve todos los miembros con sus alertas, sin las resueltas', async () => {
db.user.findUnique.mockResolvedValue({ country: 'AR' });
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
db.attendee.findMany.mockResolvedValue([
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) },
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) },
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) },
]);
db.classSession.findMany.mockResolvedValue([
{ id: 's1', groupId: 'g1', startsAt: at(1) },
{ id: 's2', groupId: 'g1', startsAt: at(3) },
{ id: 's3', groupId: 'g1', startsAt: at(5) },
]);
const row = (attendeeId: string, sessionId: string, status: string, days: number) => ({
attendeeId,
classSessionId: sessionId,
status,
classSession: { startsAt: at(days) },
});
db.attendance.findMany.mockResolvedValue([
row('a1', 's1', 'ABSENT', 1),
row('a1', 's2', 'ABSENT', 3),
row('a1', 's3', 'ABSENT', 5),
// Valentina missed two classes, but the professor already resolved it.
row('a2', 's1', 'ABSENT', 1),
row('a2', 's2', 'ABSENT', 3),
row('a3', 's1', 'PRESENT', 1),
]);
db.payment.findMany.mockResolvedValue([
{
id: 'p1',
attendeeId: 'a2',
amount: new Prisma.Decimal('15000.00'),
currency: 'ARS',
dueDate: new Date('2026-10-10T12:00:00.000Z'),
checkoutUrl: 'https://mp.test/p1',
},
]);
db.attendeeAlertResolution.findMany.mockResolvedValue([
{ attendeeId: 'a2', kind: 'ATTENDANCE', signature: 's1' },
]);
const result = await overview().execute('user-1');
if (!result.ok) throw new Error('expected ok');
const [group] = result.value.groups;
expect(group).toMatchObject({ groupId: 'g1', groupName: 'Natación', capacity: 30 });
expect(group.members.map((member) => member.attendeeId)).toEqual(['a1', 'a2', 'a3']);
const [agustina, valentina, felipe] = group.members;
expect(agustina.phone).toBe('1155550000');
expect(agustina.whatsappPhone).toBe('+5491155550000');
expect(agustina.alerts).toMatchObject([{ tipo: 'asistencia', gravedad: 'urgente', etiqueta: '3 seguidas' }]);
expect(valentina.phone).toBe('1166660000');
expect(valentina.alerts).toMatchObject([{ tipo: 'pago', gravedad: 'vigilar', etiqueta: 'Cuota vencida' }]);
expect(valentina.overduePayments).toEqual([
{ id: 'p1', amount: 15000, currency: 'ARS', dueDate: '2026-10-10T12:00:00.000Z', checkoutUrl: 'https://mp.test/p1' },
]);
expect(felipe.alerts).toEqual([]);
});
});
describe('ResolveStudentAlert', () => {
it('guarda la firma con upsert por alumno y tipo', async () => {
db.attendee.findFirst.mockResolvedValue({ id: 'a1' });
const result = await new ResolveStudentAlert({ db: db as never }).execute('a1', 'user-1', {
tipo: 'pago',
firma: 'p1,p2',
});
expect(result).toEqual({ ok: true, value: { attendeeId: 'a1', tipo: 'pago', firma: 'p1,p2' } });
expect(db.attendeeAlertResolution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { attendeeId_kind: { attendeeId: 'a1', kind: 'PAYMENT' } },
create: expect.objectContaining({ signature: 'p1,p2', resolvedById: 'user-1' }),
}),
);
});
it('un alumno de un grupo ajeno es 404 y no escribe nada', async () => {
db.attendee.findFirst.mockResolvedValue(null);
const result = await new ResolveStudentAlert({ db: db as never }).execute('a9', 'user-1', {
tipo: 'asistencia',
firma: 's1',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.status).toBe(404);
expect(db.attendeeAlertResolution.upsert).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,193 @@
import { describe, expect, it } from 'bun:test';
import {
applyResolutions,
compareByWorstAlert,
computeStudentAlerts,
type MemberAttendance,
type MemberClassSession,
STUDENT_ALERT_RULES,
type StudentAlert,
worstAlert,
} from '@gruperly/shared';
/* The single source of the "Requiere atención" alerts. These tests pin the
thresholds (attendance through the shared risk rule, fees through
`STUDENT_ALERT_RULES`), the copy the screens show and the order. */
const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = new Date('2026-10-27T20:00:00.000Z');
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
type Status = MemberClassSession['status'];
/** Classes on consecutive days, oldest first; the last one is `ses_1`. */
function attendance(statuses: Status[]): MemberAttendance {
return {
attendeeId: 'at_1',
fullName: 'Agustina Pérez',
enrolledAt: daysAgo(365),
sessions: statuses.map((status, index) => ({
sessionId: `ses_${statuses.length - index}`,
startsAt: daysAgo(statuses.length - index),
status,
})),
};
}
const fee = (id: string, dueDate: string) => ({ id, dueDate });
function alertsFor(statuses: Status[], fees: { id: string; dueDate: string }[] = []) {
return computeStudentAlerts({ attendance: attendance(statuses), overduePayments: fees }, NOW);
}
describe('computeStudentAlerts: asistencia', () => {
it('sin faltas ni cuotas no hay alertas', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT'])).toEqual([]);
});
it('3 faltas seguidas son urgentes y lo dicen así', () => {
const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']);
expect(alert).toMatchObject({
tipo: 'asistencia',
gravedad: 'urgente',
etiqueta: '3 seguidas',
detalle: 'No viene hace 3 clases seguidas.',
firma: 'ses_1',
});
});
it('4 de las últimas 6 sin racha son urgentes', () => {
const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']);
expect(alert).toMatchObject({
gravedad: 'urgente',
etiqueta: '4 faltas',
detalle: 'Faltó a 4 de las últimas 6 clases.',
firma: 'ses_2',
});
});
it('2 faltas recientes son "a vigilar"', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])[0]).toMatchObject({
gravedad: 'vigilar',
etiqueta: '2 faltas',
detalle: 'Faltó a las últimas 2 clases.',
});
expect(alertsFor(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])[0]).toMatchObject({
gravedad: 'vigilar',
detalle: 'Faltó a 2 de las últimas 4 clases.',
});
});
it('una sola falta no alcanza', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])).toEqual([]);
});
it('las justificadas y las clases sin registro no cuentan como faltas', () => {
expect(alertsFor(['PRESENT', 'EXCUSED', 'ABSENT', null, 'EXCUSED'])).toEqual([]);
});
});
describe('computeStudentAlerts: pagos', () => {
it('1 cuota vencida es "a vigilar" con su fecha', () => {
expect(alertsFor([], [fee('pay_1', '2026-10-10T12:00:00.000Z')])).toEqual([
{
tipo: 'pago',
gravedad: 'vigilar',
etiqueta: 'Cuota vencida',
detalle: 'La cuota de octubre venció el 10/10.',
firma: 'pay_1',
peso: 1,
},
]);
});
it(`${STUDENT_ALERT_RULES.urgentOverdue} o más cuotas vencidas son urgentes y nombran los meses`, () => {
const [alert] = alertsFor(
[],
[fee('pay_b', '2026-10-10T12:00:00.000Z'), fee('pay_a', '2026-09-10T12:00:00.000Z')],
);
expect(alert).toMatchObject({
gravedad: 'urgente',
etiqueta: '2 cuotas',
detalle: 'Debe las cuotas de septiembre y octubre.',
firma: 'pay_a,pay_b',
});
});
it('con tres meses los separa con coma y "y"', () => {
const [alert] = alertsFor(
[],
[
fee('p1', '2026-08-10T12:00:00.000Z'),
fee('p2', '2026-09-10T12:00:00.000Z'),
fee('p3', '2026-10-10T12:00:00.000Z'),
],
);
expect(alert.detalle).toBe('Debe las cuotas de agosto, septiembre y octubre.');
});
it('dos cuotas del mismo mes caen al conteo', () => {
const [alert] = alertsFor([], [fee('p1', '2026-10-01T12:00:00.000Z'), fee('p2', '2026-10-20T12:00:00.000Z')]);
expect(alert.detalle).toBe('Debe 2 cuotas vencidas.');
});
});
describe('orden por gravedad', () => {
it('con varias alertas, la urgente va primero', () => {
const alerts = alertsFor(
['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'],
[fee('p1', '2026-09-10T12:00:00.000Z'), fee('p2', '2026-10-10T12:00:00.000Z')],
);
expect(alerts.map((alert) => [alert.tipo, alert.gravedad])).toEqual([
['pago', 'urgente'],
['asistencia', 'vigilar'],
]);
expect(worstAlert(alerts)?.tipo).toBe('pago');
});
it('ordena alumnos por su peor alerta, después por la fuerza y por nombre', () => {
const alert = (gravedad: StudentAlert['gravedad'], peso: number): StudentAlert => ({
tipo: 'asistencia',
gravedad,
etiqueta: '',
detalle: '',
firma: 'x',
peso,
});
const students = [
{ fullName: 'Zoe', alerts: [] },
{ fullName: 'Martina', alerts: [alert('vigilar', 2)] },
{ fullName: 'Tomás', alerts: [alert('urgente', 3)] },
{ fullName: 'Agustina', alerts: [alert('urgente', 4)] },
{ fullName: 'Bruno', alerts: [alert('vigilar', 2)] },
];
expect([...students].sort(compareByWorstAlert).map((student) => student.fullName)).toEqual([
'Agustina',
'Tomás',
'Bruno',
'Martina',
'Zoe',
]);
});
});
describe('applyResolutions', () => {
const statuses: Status[] = ['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'];
it('oculta la alerta resuelta mientras la firma sea la misma', () => {
const alerts = alertsFor(statuses);
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }])).toEqual([]);
});
it('una falta nueva cambia la firma y la alerta vuelve', () => {
const alerts = alertsFor([...statuses, 'ABSENT']);
expect(alerts[0].firma).toBe('ses_1');
// The resolution was stored when the last absence was `ses_2`.
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_2' }])).toHaveLength(1);
});
it('resolver la asistencia no oculta los pagos', () => {
const alerts = alertsFor(statuses, [fee('p1', '2026-10-10T12:00:00.000Z')]);
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }]).map((a) => a.tipo)).toEqual(['pago']);
});
});

View File

@@ -88,7 +88,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
{/* Toast Container */}
<div
aria-live="polite"
className="fixed bottom-[calc(6rem+env(safe-area-inset-bottom))] right-4 z-50 lg:bottom-4 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
className="fixed bottom-[calc(9rem+env(safe-area-inset-bottom))] right-4 z-50 lg:bottom-4 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
>
{toasts.map((toast) => (
<div

View File

@@ -0,0 +1,21 @@
import type { StudentAlertSeverity } from '@gruperly/shared'
import { cn } from '../../lib/utils'
const TONES: Record<StudentAlertSeverity, string> = {
urgente: 'bg-alert-urgent-soft text-alert-urgent-fg',
vigilar: 'bg-alert-watch-soft text-alert-watch-fg',
}
/** The short reason of an alert ("4 faltas", "Cuota vencida"). */
export function AlertTag({ severity, children }: { severity: StudentAlertSeverity; children: string }) {
return (
<span
className={cn(
'inline-flex shrink-0 items-center rounded-full px-2.5 py-1 text-xs leading-none font-semibold whitespace-nowrap',
TONES[severity],
)}
>
{children}
</span>
)
}

View File

@@ -0,0 +1,80 @@
import { Link } from '@tanstack/react-router'
import { Check } from 'lucide-react'
import { cn } from '../../lib/utils'
import { AlertTag } from './AlertTag'
import { reminderMessage, whatsappLink, type AttentionItem } from './attention'
import { SeverityAvatar } from './SeverityAvatar'
const ACTION_CLASS =
'inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-xl px-3 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none motion-reduce:transition-none'
type AttentionCardProps = {
item: AttentionItem
onResolve: () => void
}
export function AttentionCard({ item, onResolve }: AttentionCardProps) {
const { student, alert } = item
const urgent = alert.gravedad === 'urgente'
const isPayment = alert.tipo === 'pago'
const actionLabel = isPayment ? 'Enviar recordatorio' : 'Contactar'
const href = whatsappLink(student, isPayment ? reminderMessage(student) : undefined)
// Urgent: light fill, the strongest action on screen. To watch: subtle gray.
const primaryTone = urgent
? 'bg-primary text-background hover:bg-primary/90'
: 'bg-primary-soft text-primary hover:bg-border'
return (
<article className="rounded-2xl border border-border bg-surface p-4">
<div className="flex items-start gap-3">
<SeverityAvatar name={student.fullName} seed={student.attendeeId} severity={alert.gravedad} size="md" />
<div className="min-w-0 flex-1">
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId: student.groupId, attendeeId: student.attendeeId }}
className="block truncate font-semibold text-primary hover:underline focus-visible:underline focus-visible:outline-none"
>
{student.fullName}
</Link>
<p className="truncate text-sm text-secondary">{student.groupName}</p>
</div>
<AlertTag severity={alert.gravedad}>{alert.etiqueta}</AlertTag>
</div>
<p className="mt-3 text-sm text-primary">{alert.detalle}</p>
<div className="mt-3 grid grid-cols-2 gap-2">
{href ? (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={`${actionLabel} a ${student.fullName} por WhatsApp`}
className={cn(ACTION_CLASS, primaryTone)}
>
{actionLabel}
</a>
) : (
<button
type="button"
disabled
aria-label={`${actionLabel}: ${student.fullName} no tiene teléfono cargado`}
className={cn(ACTION_CLASS, primaryTone, 'cursor-not-allowed opacity-45')}
>
{actionLabel}
</button>
)}
<button
type="button"
onClick={onResolve}
aria-label={`Marcar como resuelto: ${student.fullName}, ${alert.etiqueta}`}
className={cn(ACTION_CLASS, 'border border-border text-primary hover:bg-primary-soft')}
>
<Check className="size-4" aria-hidden="true" />
Resuelto
</button>
</div>
</article>
)
}

View File

@@ -0,0 +1,41 @@
import { Link } from '@tanstack/react-router'
import { ArrowLeft, ListFilter } from 'lucide-react'
import { createPortal } from 'react-dom'
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
/* Compact bar of "Requiere atención". Unlike the other immersive screens the
"Volver" button also shows on mobile: this screen has no entry in the nav,
so without it the only way out would be the back gesture (agreed exception
to the repo rule, noted in AGENTS.md). Mounted by portal in the layout's
sticky box, like `LargeTitle`. */
export function AttentionHeader({ subtitle }: { subtitle: string }) {
const host = useImmersiveBarHost()
const bar = (
<div className="flex h-full items-center gap-1 border-b border-border bg-background/90 px-2 backdrop-blur-md lg:px-0">
<Link
to="/groups"
aria-label="Volver"
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-primary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
>
<ArrowLeft className="size-5" aria-hidden="true" />
</Link>
<div className="min-w-0 flex-1 px-1">
<h1 className="truncate text-base leading-tight font-semibold text-primary">Requiere atención</h1>
<p className="truncate text-xs text-secondary" aria-live="polite">
{subtitle}
</p>
</div>
{/* TODO: ordenar/filtrar por grupo. Por ahora no hace nada. */}
<button
type="button"
aria-label="Ordenar y filtrar"
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-secondary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
>
<ListFilter className="size-5" aria-hidden="true" />
</button>
</div>
)
return host ? createPortal(bar, host) : bar
}

View File

@@ -0,0 +1,82 @@
import { createContext, useContext, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { AttentionOverview, StudentAlert } from '@gruperly/shared'
import { useToast } from '../../components/ui'
import { resolveAlert } from '../../lib/api'
import {
attentionItems,
flaggedStudents,
withoutAlert,
type AttentionFilter,
type AttentionItem,
} from './attention'
import { attentionQueryOptions } from './queries'
type AttentionContextValue = {
/** Every alert as a card, most urgent first (unfiltered). */
items: AttentionItem[]
isPending: boolean
isError: boolean
retry: () => void
filter: AttentionFilter
setFilter: (filter: AttentionFilter) => void
resolve: (attendeeId: string, alert: StudentAlert) => void
}
const AttentionContext = createContext<AttentionContextValue | null>(null)
export function AttentionProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
const toast = useToast()
const [filter, setFilter] = useState<AttentionFilter>('todos')
const attentionQuery = useQuery(attentionQueryOptions)
/* "Resuelto" removes the card right away (optimistic) from the cache that
Grupos reads too, so its counters move without a refetch. On error the
previous snapshot comes back. */
const resolveMutation = useMutation({
mutationFn: ({ attendeeId, alert }: { attendeeId: string; alert: StudentAlert }) =>
resolveAlert(attendeeId, { tipo: alert.tipo, firma: alert.firma }),
onMutate: async ({ attendeeId, alert }) => {
await queryClient.cancelQueries({ queryKey: attentionQueryOptions.queryKey })
const previous = queryClient.getQueryData<AttentionOverview>(attentionQueryOptions.queryKey)
if (previous) {
queryClient.setQueryData(attentionQueryOptions.queryKey, withoutAlert(previous, attendeeId, alert.tipo))
}
return { previous }
},
onError: (_error, _variables, context) => {
if (context?.previous) queryClient.setQueryData(attentionQueryOptions.queryKey, context.previous)
toast.error('No pudimos marcarlo como resuelto. Probá de nuevo.')
},
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: attentionQueryOptions.queryKey })
},
})
const items = useMemo(() => attentionItems(flaggedStudents(attentionQuery.data)), [attentionQuery.data])
return (
<AttentionContext.Provider
value={{
items,
isPending: attentionQuery.isPending,
isError: attentionQuery.isError,
retry: () => void attentionQuery.refetch(),
filter,
setFilter,
resolve: (attendeeId, alert) => resolveMutation.mutate({ attendeeId, alert }),
}}
>
{children}
</AttentionContext.Provider>
)
}
export function useAttention() {
const context = useContext(AttentionContext)
if (!context) throw new Error('useAttention must be used inside AttentionProvider')
return context
}

View File

@@ -0,0 +1,45 @@
import type { StudentAlertSeverity } from '@gruperly/shared'
import { cn } from '../../lib/utils'
import { AttentionCard } from './AttentionCard'
import type { AttentionItem } from './attention'
const SECTIONS: Record<StudentAlertSeverity, { title: string; dot: string; text: string }> = {
urgente: { title: 'Urgente', dot: 'bg-alert-urgent-ring', text: 'text-alert-urgent-fg' },
vigilar: { title: 'A vigilar', dot: 'bg-alert-watch-ring', text: 'text-alert-watch-fg' },
}
type AttentionSectionProps = {
severity: StudentAlertSeverity
items: AttentionItem[]
onResolve: (item: AttentionItem) => void
}
/** One severity block. Not rendered when it is empty. */
export function AttentionSection({ severity, items, onResolve }: AttentionSectionProps) {
if (items.length === 0) return null
const section = SECTIONS[severity]
const headingId = `attention-${severity}`
return (
<section aria-labelledby={headingId} className="mt-4 first:mt-1">
<h2
id={headingId}
className={cn('flex items-center gap-2 text-xs font-semibold tracking-wider uppercase', section.text)}
>
<span className={cn('size-2 rounded-full', section.dot)} aria-hidden="true" />
{section.title}
<span aria-hidden="true">·</span>
<span className="tabular-nums">{items.length}</span>
</h2>
<div className="mt-2 grid gap-3">
{items.map((item) => (
<AttentionCard
key={`${item.student.attendeeId}-${item.alert.tipo}`}
item={item}
onResolve={() => onResolve(item)}
/>
))}
</div>
</section>
)
}

View File

@@ -0,0 +1,48 @@
import { Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { AttentionHeader } from './AttentionHeader'
import { AttentionSection } from './AttentionSection'
import { attentionSubtitle, filterCounts, filterItems, itemsBySeverity } from './attention'
import { useAttention } from './AttentionProvider'
import { EmptyAttention } from './EmptyAttention'
import { FilterChips } from './FilterChips'
export function AttentionView() {
const { items, isPending, isError, retry, filter, setFilter, resolve } = useAttention()
const visible = filterItems(items, filter)
const { urgente, vigilar } = itemsBySeverity(visible)
const onResolve = (item: (typeof items)[number]) => resolve(item.student.attendeeId, item.alert)
return (
<section className="pb-6">
<AttentionHeader subtitle={isPending ? 'Cargando…' : attentionSubtitle(items)} />
{/* The chips stay under the bar (56px) while the cards scroll. */}
<div className="sticky top-14 z-30 -mx-4 bg-background px-4 lg:mx-0 lg:px-0">
<FilterChips value={filter} counts={filterCounts(items)} onChange={setFilter} />
</div>
{isPending ? (
<div className="flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">Cargando alertas</span>
</div>
) : isError ? (
<div className="mt-4 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>No pudimos cargar las alertas.</p>
<Button variant="outline" size="sm" onClick={retry}>
Reintentar
</Button>
</div>
) : visible.length === 0 ? (
<EmptyAttention />
) : (
<>
<AttentionSection severity="urgente" items={urgente} onResolve={onResolve} />
<AttentionSection severity="vigilar" items={vigilar} onResolve={onResolve} />
</>
)}
</section>
)
}

View File

@@ -0,0 +1,15 @@
import { Check } from 'lucide-react'
export function EmptyAttention() {
return (
<div className="mt-10 flex flex-col items-center px-6 text-center" role="status">
<span className="flex size-14 items-center justify-center rounded-full bg-success-soft text-success">
<Check className="size-7" strokeWidth={2.5} aria-hidden="true" />
</span>
<p className="mt-4 text-base font-semibold text-primary">Todo en orden</p>
<p className="mt-1 max-w-[32ch] text-sm text-secondary">
No hay alumnos que requieran atención en este filtro.
</p>
</div>
)
}

View File

@@ -0,0 +1,37 @@
import { cn } from '../../lib/utils'
import { ATTENTION_FILTERS, type AttentionFilter } from './attention'
type FilterChipsProps = {
value: AttentionFilter
counts: Record<AttentionFilter, number>
onChange: (filter: AttentionFilter) => void
}
export function FilterChips({ value, counts, onChange }: FilterChipsProps) {
return (
<div role="group" aria-label="Filtrar alertas" className="flex gap-2 overflow-x-auto py-3">
{ATTENTION_FILTERS.map((filter) => {
const active = filter.id === value
return (
<button
key={filter.id}
type="button"
aria-pressed={active}
onClick={() => onChange(filter.id)}
className={cn(
'inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-full border px-4 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none motion-reduce:transition-none',
active
? 'border-primary bg-primary text-background'
: 'border-border bg-surface text-primary hover:bg-primary-soft',
)}
>
{filter.label}
<span className={cn('tabular-nums', active ? 'text-background/70' : 'text-secondary')}>
{counts[filter.id]}
</span>
</button>
)
})}
</div>
)
}

View File

@@ -0,0 +1,60 @@
import type { StudentAlertSeverity } from '@gruperly/shared'
import { Avatar } from '../../components/ui'
import { cn } from '../../lib/utils'
/* Neutral fills for students without alerts, picked by id so the same person
keeps their color across screens. All of them are existing token pairs, so
both themes keep their text contrast. */
const NEUTRAL_TONES = [
'bg-accent-soft text-accent-fg',
'bg-success-soft text-success',
'bg-primary-soft text-primary',
'bg-warning-strong-soft text-warning-strong',
]
const SEVERITY_TONES: Record<StudentAlertSeverity, string> = {
urgente: 'border-2 border-alert-urgent-ring bg-alert-urgent-soft text-alert-urgent-fg',
vigilar: 'border-2 border-alert-watch-ring bg-alert-watch-soft text-alert-watch-fg',
}
const SIZES = {
sm: 'size-8 text-[11px]',
md: 'size-10 text-xs',
}
type SeverityAvatarProps = {
name: string
/** Stable seed for the neutral color (the attendee id). */
seed: string
severity: StudentAlertSeverity | null
size?: keyof typeof SIZES
/** Overlapped row: a ring in the card's color separates each face. */
stacked?: boolean
className?: string
}
/** Round avatar with initials and, when there is an alert, its severity ring.
* The ring is never the only signal: the row next to it always names the reason. */
export function SeverityAvatar({ name, seed, severity, size = 'sm', stacked, className }: SeverityAvatarProps) {
return (
<Avatar
name={name}
aria-hidden="true"
className={cn(
'rounded-full font-bold tracking-tight',
SIZES[size],
severity ? SEVERITY_TONES[severity] : NEUTRAL_TONES[hash(seed) % NEUTRAL_TONES.length],
stacked && 'ring-2 ring-surface',
className,
)}
/>
)
}
function hash(value: string): number {
let result = 0
for (let index = 0; index < value.length; index += 1) {
result = (result * 31 + value.charCodeAt(index)) >>> 0
}
return result
}

View File

@@ -0,0 +1,135 @@
import type {
AttentionGroup,
AttentionMember,
AttentionOverview,
StudentAlert,
StudentAlertSeverity,
StudentAlertType,
} from '@gruperly/shared'
import { compareAlerts, compareByWorstAlert, worstAlert } from '@gruperly/shared'
import { formatPrice } from '../../lib/format'
/* Derivations for "Requiere atención" (the Grupos preview and the "Ver todos"
screen). The alerts themselves come computed from `GET /attention`
(`computeStudentAlerts` in shared); here they are only flattened, counted and
filtered, so the components just lay them out. */
export type AttentionFilter = 'todos' | StudentAlertType
export const ATTENTION_FILTERS: { id: AttentionFilter; label: string }[] = [
{ id: 'todos', label: 'Todos' },
{ id: 'asistencia', label: 'Asistencia' },
{ id: 'pago', label: 'Pagos' },
]
/** A student with at least one alert, with their group. */
export type FlaggedStudent = AttentionMember & {
groupId: string
groupName: string
/** The alert that represents them where only one fits. */
worst: StudentAlert
}
/** One card on the "Ver todos" screen: a student and one of their alerts. */
export type AttentionItem = {
student: FlaggedStudent
alert: StudentAlert
}
/** Students with alerts across every group, most urgent first. */
export function flaggedStudents(overview: AttentionOverview | undefined): FlaggedStudent[] {
const students: FlaggedStudent[] = []
for (const group of overview?.groups ?? []) {
for (const member of group.members) {
const worst = worstAlert(member.alerts)
if (worst) students.push({ ...member, groupId: group.groupId, groupName: group.groupName, worst })
}
}
return students.sort(compareByWorstAlert)
}
/** Every alert as its own card: a student behind on both shows up twice. */
export function attentionItems(students: FlaggedStudent[]): AttentionItem[] {
return students
.flatMap((student) => student.alerts.map((alert) => ({ student, alert })))
.sort((a, b) => compareAlerts(a.alert, b.alert) || a.student.fullName.localeCompare(b.student.fullName, 'es'))
}
export function filterItems(items: AttentionItem[], filter: AttentionFilter): AttentionItem[] {
return filter === 'todos' ? items : items.filter((item) => item.alert.tipo === filter)
}
export function filterCounts(items: AttentionItem[]): Record<AttentionFilter, number> {
return {
todos: items.length,
asistencia: items.filter((item) => item.alert.tipo === 'asistencia').length,
pago: items.filter((item) => item.alert.tipo === 'pago').length,
}
}
export function itemsBySeverity(items: AttentionItem[]): Record<StudentAlertSeverity, AttentionItem[]> {
return {
urgente: items.filter((item) => item.alert.gravedad === 'urgente'),
vigilar: items.filter((item) => item.alert.gravedad === 'vigilar'),
}
}
/** "7 alumnos · 3 urgentes", or "Nada pendiente". Students, not cards. */
export function attentionSubtitle(items: AttentionItem[]): string {
const students = new Set(items.map((item) => item.student.attendeeId))
if (students.size === 0) return 'Nada pendiente'
const urgent = new Set(
items.filter((item) => item.alert.gravedad === 'urgente').map((item) => item.student.attendeeId),
)
const parts = [`${students.size} ${students.size === 1 ? 'alumno' : 'alumnos'}`]
if (urgent.size > 0) parts.push(`${urgent.size} ${urgent.size === 1 ? 'urgente' : 'urgentes'}`)
return parts.join(' · ')
}
/** Removes one alert from the cached overview (optimistic "Resuelto"). */
export function withoutAlert(
overview: AttentionOverview,
attendeeId: string,
tipo: StudentAlertType,
): AttentionOverview {
return {
groups: overview.groups.map((group): AttentionGroup => ({
...group,
members: group.members.map((member) =>
member.attendeeId === attendeeId
? { ...member, alerts: member.alerts.filter((alert) => alert.tipo !== tipo) }
: member,
),
})),
}
}
/** `wa.me` link, with an optional prefilled message. `null` without a phone. */
export function whatsappLink(student: Pick<AttentionMember, 'whatsappPhone'>, text?: string): string | null {
const digits = student.whatsappPhone?.replace(/\D/g, '')
if (!digits) return null
return text ? `https://wa.me/${digits}?text=${encodeURIComponent(text)}` : `https://wa.me/${digits}`
}
/** The payment reminder the professor sends from their own WhatsApp. */
export function reminderMessage(student: FlaggedStudent): string {
const firstName = student.fullName.trim().split(/\s+/)[0] || student.fullName
const payments = student.overduePayments
const total = payments.reduce((sum, payment) => sum + payment.amount, 0)
const amount = formatPrice(total, payments[0]?.currency)
const owed =
payments.length === 1
? `la cuota de ${student.groupName} (${amount}) que venció el ${shortDate(payments[0].dueDate)}`
: `${payments.length} cuotas de ${student.groupName} (${amount} en total)`
const link = payments.find((payment) => payment.checkoutUrl)?.checkoutUrl
return (
`¡Hola ${firstName}! 👋 Te escribo para recordarte que quedó pendiente ${owed}.` +
(link ? ` Podés pagar acá: ${link}` : '') +
' Cualquier cosa, avisame.'
)
}
function shortDate(iso: string): string {
const date = new Date(iso)
return `${date.getUTCDate()}/${date.getUTCMonth() + 1}`
}

View File

@@ -0,0 +1,8 @@
import { queryOptions } from '@tanstack/react-query'
import { getAttention } from '../../lib/api'
/** One cache for both screens: resolving on "Ver todos" updates Grupos too. */
export const attentionQueryOptions = queryOptions({
queryKey: ['attention'],
queryFn: getAttention,
})

View File

@@ -1,206 +0,0 @@
import type { CapacityCounts, RiskTone } from './card'
import { cn } from '../../lib/utils'
/**
* Single capacity and attendance indicator: one bar that joins "how many people
* there are" with "how those people are doing". It replaces the low attendance
* badge and the occupancy bar, which counted two different things and competed
* for the same spot on the card.
*
* ── What is being measured ──────────────────────────────────────────────────
* `capacity` is the total the blocks are split against, and `places` says whether
* that total is spots of the capacity or the roster. With no declared capacity the
* group has no spots, but it does have people at risk, so the bar measures the
* members (`places: false`) instead of disappearing.
*
* ── Two modes ───────────────────────────────────────────────────────────────
* With a small total (<= `SEGMENTED_CAPACITY_MAX`) there is one segment per unit
* and you see exactly which positions are occupied and in what color. With a large
* total that is no longer distinguishable, so it switches to proportional blocks.
* Both modes keep the same visual measure so the list can be scanned vertically;
* the proportion is what matters, not that small groups end up tiny.
*
* ── Width ───────────────────────────────────────────────────────────────────
* The bar splits the available width and never exceeds it: that is the rule that
* stops the card from overflowing the screen on a phone. That is why the segment
* goes `flex-1 max-w-[50px]` and not with a fixed width. A `w-[50px] shrink-0`
* looks harmless, but at 10 segments it is 554px (plus the gaps) against the
* ~288px the card leaves on a 402px viewport: the `shrink-0` children spill out
* of the already-shrunk box and, with nothing clipping them, push the document
* into a horizontal scroll. With `flex-1` each segment takes its share of the real
* space, and the `max-w` keeps the desktop width (50px). The container's
* `overflow-hidden` is the safety net: it clips instead of overflowing if one day
* something bigger than the space shows up again.
*
* Note: splitting the width is not enough on its own. A very narrow segment
* stops telling its color apart from its neighbor and the bar becomes a line of
* dots. That is why the width ceded to the bar matters as much as the split: the
* card's label says "4/5" on mobile instead of "4/5 miembros" precisely so that
* capacity 10 is left with ~24px per pill instead of ~19px.
* See `SEGMENTED_CAPACITY_MAX` for the rest of the accounting.
*
* ── Reading ─────────────────────────────────────────────────────────────────
* Color alone is not enough. The block carries `role="img"` and an `aria-label`
* that says everything ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en
* atención"), which is what the screen reader reads; and the card repeats the
* essentials in text ("3 en riesgo alto · 4 en atención") below. The three levels
* always go in the same order, worst to best, so the bar reads the same on every
* card and the eye learns to scan them.
*
* ── Contrast ────────────────────────────────────────────────────────────────
* Everything comes from tokens, nothing hardcoded. The fills measure 5.74:1 (red),
* 4.58:1 (amber) and 6.20:1 (blue) against the card in the light theme, and 5.44,
* 10.15 and 7.10:1 in dark: all three pass the 3:1 WCAG asks of non-text content
* and the 4.5:1 the accompanying text line needs. The red uses `danger-fg` and not
* `danger` precisely for that: `danger` in the light theme gives 3.35:1 and would
* not do as text.
*
* The outline of the free spots can NOT use `border`, which in the dark theme is
* the same as the card (1.00:1 and invisible); it uses `foreground` at 70%, which
* gives 3.42:1 in light and 3.55:1 in dark.
*/
type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'>
/* Worst to best. This is the bar's fixed order: if a level is ever added it goes
in this list and the component does not have to change. */
const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres']
const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok']
/* The free spot is not a state of the person: it is the absence of people. That
is why it is the only one with no fill. */
const FILL: Record<Level, string> = {
riesgoAlto: 'bg-attendance-high',
atencion: 'bg-attendance-attention',
ok: 'bg-attendance-ok',
libres: '',
}
const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50'
/** The `aria-label`'s long phrase: all of the block's information in one line. */
export function capacityIndicatorLabel(
counts: CapacityCounts,
capacity: number,
places = true,
): string {
const { riesgoAlto, atencion, ok, libres } = counts
const ocupados = riesgoAlto + atencion + ok
const niveles = [
`${riesgoAlto} en riesgo alto`,
`${atencion} en atención`,
`${ok} en ok`,
].filter((parte, index) => {
const valor = [riesgoAlto, atencion, ok][index]
return valor > 0
})
const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : ''
/* With no declared capacity there are no spots to fill and no free ones to
count: the bar is a split of the roster, and saying it with those words
would invent a capacity the group does not have. */
if (!places) {
return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}`
}
const libresTexto = libres > 0 ? `, ${libres} libre${libres === 1 ? '' : 's'}` : ''
return `${ocupados} de ${capacity} lugares ocupados${detalle}${libresTexto}`
}
export function AttendanceCapacityIndicator({
counts,
capacity,
segmented,
places = true,
className,
}: {
counts: CapacityCounts
/** The total the bar is split against: the capacity, or the roster if the
* group has no declared capacity. */
capacity: number
/** `true` when the total is small and goes one segment per unit. */
segmented: boolean
/** `false` when `capacity` is members and not spots of the capacity. */
places?: boolean
className?: string
}) {
const label = capacityIndicatorLabel(counts, capacity, places)
if (segmented) {
return (
<span
role="img"
aria-label={label}
title={label}
className={cn(
'flex h-3.5 min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
className,
)}
>
{Array.from({ length: capacity }, (_, index) => (
<LevelSegment
key={index}
level={levelAt(counts, index)}
className="h-3.5 min-w-0 flex-1 max-w-[50px]"
/>
))}
</span>
)
}
return (
<span
role="img"
aria-label={label}
title={label}
className={cn(
'flex h-3.5 min-w-0 flex-1 items-stretch overflow-hidden rounded-full bg-surface',
OUTLINE,
className,
)}
>
{OCCUPIED_LEVELS.map((level) =>
counts[level] > 0 ? (
<span
key={level}
className={cn('h-full min-w-1.5', FILL[level])}
style={{ width: capacitySegmentWidth(counts[level], capacity) }}
/>
) : null,
)}
</span>
)
}
export function capacitySegmentWidth(count: number, capacity: number): string {
if (capacity <= 0) return '0%'
return `${((count / capacity) * 100).toFixed(4)}%`
}
/** A segment is a person: the color is that of the level of this spot. */
function LevelSegment({ level, className }: { level: Level; className?: string }) {
if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} />
return <span className={cn('rounded-full', FILL[level], className)} />
}
/** The person of the worst level that still fits occupies the `index` spot. */
function levelAt(counts: CapacityCounts, index: number): Level {
let restante = index
for (const level of LEVELS) {
if (restante < counts[level]) return level
restante -= counts[level]
}
return 'libres'
}
/** Text color by worst level: the status line cannot end up misaligned with the
* bar. `danger-fg` and not `danger` because the first is the legible version
* (5.7:1 in light, 5.4:1 in dark) and the second stays at 3.35:1 as text. */
export const TONE_TEXT: Record<RiskTone, string> = {
riesgo_alto: 'text-danger-fg',
atencion: 'text-warning',
ok: 'text-secondary',
}

View File

@@ -0,0 +1,62 @@
import { Link } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react'
import { AlertTag } from '../attention/AlertTag'
import type { FlaggedStudent } from '../attention/attention'
import { SeverityAvatar } from '../attention/SeverityAvatar'
const PREVIEW_LIMIT = 4
/** "Requiere atención" on Grupos: the most urgent students, one row each. */
export function AttentionPreview({ students }: { students: FlaggedStudent[] }) {
if (students.length === 0) return null
return (
<section aria-labelledby="attention-preview-title" className="mt-6">
<div className="flex items-center justify-between gap-3">
<h2
id="attention-preview-title"
className="flex items-center gap-2 text-xs font-semibold tracking-wider text-alert-urgent-fg uppercase"
>
Requiere atención
<span className="inline-flex min-w-5 items-center justify-center rounded-full bg-alert-urgent-soft px-1.5 py-0.5 text-[11px] leading-none tabular-nums">
<span className="sr-only">: </span>
{students.length}
<span className="sr-only"> {students.length === 1 ? 'alumno' : 'alumnos'}</span>
</span>
</h2>
<Link
to="/groups/attention"
className="-mr-2 inline-flex min-h-11 items-center gap-0.5 rounded-xl px-2 text-sm font-medium text-accent-fg hover:underline focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
>
Ver todos
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
</div>
<ul className="mt-2 divide-y divide-alert-urgent-edge overflow-hidden rounded-2xl border border-alert-urgent-edge bg-alert-urgent-surface">
{students.slice(0, PREVIEW_LIMIT).map((student) => (
<li key={student.attendeeId}>
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId: student.groupId, attendeeId: student.attendeeId }}
className="flex min-h-[60px] items-center gap-3 px-3 py-2.5 transition-colors hover:bg-alert-urgent-soft/50 focus-visible:bg-alert-urgent-soft/50 focus-visible:outline-none motion-reduce:transition-none"
>
<SeverityAvatar
name={student.fullName}
seed={student.attendeeId}
severity={student.worst.gravedad}
size="md"
/>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-primary">{student.fullName}</span>
<span className="block truncate text-sm text-secondary">{student.groupName}</span>
</span>
<span className="sr-only">{student.worst.gravedad === 'urgente' ? 'Urgente:' : 'A vigilar:'}</span>
<AlertTag severity={student.worst.gravedad}>{student.worst.etiqueta}</AlertTag>
</Link>
</li>
))}
</ul>
</section>
)
}

View File

@@ -0,0 +1,54 @@
import type { AttentionMember } from '@gruperly/shared'
import { cn } from '../../lib/utils'
import { SeverityAvatar } from '../attention/SeverityAvatar'
import { avatarRow } from './card'
type AvatarRowProps = {
members: AttentionMember[]
capacity: number | null
occupied: number
}
/** The members of a group as faces: the same language for any size. */
export function AvatarRow({ members, capacity, occupied }: AvatarRowProps) {
const { stacked, slots } = avatarRow(members, capacity, occupied)
return (
<div className={cn('flex min-w-0 items-center', stacked ? '' : 'gap-2')} aria-hidden="true">
{slots.map((slot, index) => {
const overlap = stacked && index > 0 && '-ml-1.5'
if (slot.kind === 'member') {
return (
<SeverityAvatar
key={slot.member.attendeeId}
name={slot.member.fullName}
seed={slot.member.attendeeId}
severity={slot.severity}
stacked={stacked}
className={cn(overlap || undefined)}
/>
)
}
if (slot.kind === 'free') {
return (
<span
key={slot.key}
className="size-8 shrink-0 rounded-full border border-dashed border-foreground/60"
/>
)
}
return (
<span
key="more"
className={cn(
'flex size-8 shrink-0 items-center justify-center rounded-full bg-primary-soft text-[11px] font-semibold text-secondary ring-2 ring-surface',
overlap,
)}
>
+{slot.count}
</span>
)
})}
</div>
)
}

View File

@@ -1,103 +1,64 @@
import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared'
import type { AttentionMember, GroupListItem } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { TriangleAlert } from 'lucide-react'
import { AttendanceCapacityIndicator } from './AttendanceCapacityIndicator'
import {
SEGMENTED_CAPACITY_MAX,
alertTextFromMembers,
capacityCountsFromMembers,
membersFromGroupAndRisk,
type GroupMember,
} from './card'
import { cn } from '../../lib/utils'
import { AvatarRow } from './AvatarRow'
import { groupStatus, type GroupStatus } from './card'
const CARD_CLASS_NAME =
'block rounded-2xl border border-border/80 bg-surface px-5 py-5 shadow-none transition-[border-color,background-color,transform] duration-150 ease-out hover:border-accent/35 hover:bg-primary-soft/35 focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:scale-[0.995] active:bg-primary-soft/55 sm:px-7'
'block rounded-2xl border border-border/80 bg-surface px-4 py-4 transition-[border-color,background-color,transform] duration-150 ease-out hover:border-accent/35 focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:scale-[0.995] motion-reduce:transition-none motion-reduce:active:scale-100 sm:px-5'
export type GroupCardProps = {
id?: string
name?: string
capacity?: number
members?: GroupMember[]
group?: GroupListItem
risk?: GroupRiskSummary | undefined
link?: boolean
const STATUS_TONES: Record<NonNullable<GroupStatus>['tone'], string> = {
urgente: 'text-alert-urgent-fg',
vigilar: 'text-alert-watch-fg',
free: 'text-free-fg',
full: 'text-secondary',
}
export function GroupCard({ link = true, ...props }: GroupCardProps) {
const linkId = props.id ?? props.group?.id
if (link && linkId) {
return (
<Link
to="/groups/$groupId"
params={{ groupId: linkId }}
className={CARD_CLASS_NAME}
>
<GroupCardContent {...props} />
</Link>
)
}
return (
<div className={CARD_CLASS_NAME}>
<GroupCardContent {...props} />
</div>
)
type GroupCardProps = {
group: GroupListItem
/** ACTIVE members with their alerts; `undefined` while they load, `null`
* if they could not be loaded (the card keeps the occupancy). */
members: AttentionMember[] | undefined | null
}
export function GroupCardContent(props: GroupCardProps) {
const name = props.name ?? props.group?.name ?? ''
const members =
props.members ??
(props.group ? membersFromGroupAndRisk(props.group, props.risk) : [])
const capacity =
props.capacity ??
props.group?.capacity ??
props.group?.attendeesCount ??
members.length
const counts = capacityCountsFromMembers(members, capacity)
const alertText = alertTextFromMembers(members)
const segmented = capacity <= SEGMENTED_CAPACITY_MAX
export function GroupCard({ group, members }: GroupCardProps) {
const status = members ? groupStatus(members, group.capacity, group.attendeesCount) : null
const occupancy =
group.capacity === null
? `${group.attendeesCount} ${group.attendeesCount === 1 ? 'alumno' : 'alumnos'}`
: `${group.attendeesCount} de ${group.capacity} lugares ocupados`
return (
<>
<h3 className="min-w-0 text-xl leading-tight font-semibold tracking-tight text-primary sm:text-2xl">
{name}
</h3>
<div className="mt-5 flex min-w-0 items-center gap-3">
<AttendanceCapacityIndicator
counts={counts}
capacity={capacity}
segmented={segmented}
places={true}
/>
{/* The word "miembros" takes ~60px that the bar needs on a phone. On
mobile only the "4/5" goes, which already reads on a capacity card
and loses nothing: the indicator's `aria-label` still counts
everything ("4 de 5 lugares ocupados: 2 en riesgo alto..."). */}
<span className="shrink-0 whitespace-nowrap text-base tabular-nums text-secondary">
{members.length}/{capacity}
<span className="hidden sm:inline">
{' '}
{capacity === 1 ? 'miembro' : 'miembros'}
</span>
<Link
to="/groups/$groupId"
params={{ groupId: group.id }}
aria-label={[group.name, occupancy, status?.text].filter(Boolean).join(', ')}
className={CARD_CLASS_NAME}
>
<div className="flex items-baseline justify-between gap-3">
<h3 className="min-w-0 truncate text-lg leading-tight font-semibold tracking-tight text-primary">
{group.name}
</h3>
<span className="shrink-0 text-sm tabular-nums text-secondary">
<span className="font-bold text-primary">{group.attendeesCount}</span>
{group.capacity !== null ? ` / ${group.capacity}` : null}
</span>
</div>
{alertText ? (
<p className="mt-3 flex min-w-0 items-center gap-2.5 text-sm leading-6 font-medium text-[#8B1A1A] dark:text-[#f87171]">
<TriangleAlert
className="size-4 shrink-0 text-[#8B1A1A] dark:text-[#f87171]"
strokeWidth={2}
aria-hidden="true"
/>
<span className="min-w-0">{alertText}</span>
</p>
{members !== null ? (
<div className="mt-3 flex min-h-8 items-center justify-between gap-3">
{members ? (
<AvatarRow members={members} capacity={group.capacity} occupied={group.attendeesCount} />
) : (
<span className="h-8 w-32 animate-pulse rounded-full bg-primary-soft motion-reduce:animate-none" />
)}
{status ? (
<span className={cn('shrink-0 text-sm font-semibold whitespace-nowrap', STATUS_TONES[status.tone])}>
{status.text}
</span>
) : null}
</div>
) : null}
</>
</Link>
)
}

View File

@@ -1,11 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui'
import { getGroups, getGroupsRiskOverview } from '../../lib/api'
import { getGroups } from '../../lib/api'
import { flaggedStudents } from '../attention/attention'
import { attentionQueryOptions } from '../attention/queries'
import { AttentionPreview } from './AttentionPreview'
import { GroupCard } from './GroupCard'
import { MOCK_TEST_CASES } from './card'
import { groupsSummary, membersOf } from './card'
import { NewGroupFab } from './NewGroupFab'
export function GroupsView() {
const navigate = useNavigate()
@@ -13,49 +16,16 @@ export function GroupsView() {
queryKey: ['groups'],
queryFn: getGroups,
})
const riskQuery = useQuery({
queryKey: ['groups-risk-overview'],
queryFn: getGroupsRiskOverview,
})
const attentionQuery = useQuery(attentionQueryOptions)
const [showExamples, setShowExamples] = useState(() => {
if (typeof window !== 'undefined') {
return new URLSearchParams(window.location.search).get('mock') === 'true'
}
return false
})
const riskByGroup = new Map(
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item]),
)
const hasGroups = groupsQuery.isSuccess && groupsQuery.data.data.length > 0
const groups = groupsQuery.data?.data ?? []
const hasGroups = groupsQuery.isSuccess && groups.length > 0
return (
<section>
<div className="flex items-center justify-between gap-3">
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
<div className="flex items-center gap-2">
{!hasGroups && groupsQuery.isSuccess ? (
<Button
variant="outline"
size="sm"
className="h-11"
onClick={() => setShowExamples((prev) => !prev)}
>
{showExamples ? 'Ocultar ejemplos' : 'Ver ejemplos'}
</Button>
) : null}
<Button
variant="primary"
className="h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Nuevo grupo
</Button>
</div>
</div>
// The FAB floats over the last card: 88px of room so it can be read.
<section className="pb-[88px]">
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
{hasGroups ? <p className="mt-1 text-sm text-secondary">{groupsSummary(groups)}</p> : null}
{groupsQuery.isPending ? (
<div className="mt-8 flex items-center justify-center py-16" role="status">
@@ -73,15 +43,7 @@ export function GroupsView() {
</div>
) : null}
{showExamples ? (
<div className="mt-6 grid gap-4">
{MOCK_TEST_CASES.map((group) => (
<GroupCard key={group.id} {...group} />
))}
</div>
) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
{groupsQuery.isSuccess && groups.length === 0 ? (
/* A single icon, one focal point, and the text in secondary: the empty
state competes with the action and must not win. */
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
@@ -92,38 +54,48 @@ export function GroupsView() {
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
</p>
<div className="mt-6 flex items-center justify-center gap-3">
<Button
variant="outline"
className="h-11"
onClick={() => setShowExamples(true)}
>
Ver tarjetas de ejemplo
</Button>
<Button
variant="primary"
className="h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Crear primer grupo
</Button>
</div>
<Button
variant="primary"
className="mt-6 h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Crear primer grupo
</Button>
</div>
) : null}
{hasGroups && !showExamples ? (
<div className="mt-6 grid gap-4">
{groupsQuery.data.data.map((group) => (
<GroupCard
key={group.id}
group={group}
risk={riskByGroup.get(group.id)}
/>
))}
</div>
{hasGroups ? (
<>
<AttentionPreview students={flaggedStudents(attentionQuery.data)} />
<section aria-labelledby="my-groups-title" className="mt-6">
<h2
id="my-groups-title"
className="text-xs font-semibold tracking-wider text-secondary uppercase"
>
Mis grupos
</h2>
<div className="mt-2 grid gap-3 lg:grid-cols-2">
{groups.map((group) => (
<GroupCard
key={group.id}
group={group}
members={
attentionQuery.isSuccess
? (membersOf(attentionQuery.data.groups, group.id) ?? [])
: attentionQuery.isError
? null
: undefined
}
/>
))}
</div>
</section>
</>
) : null}
<NewGroupFab />
</section>
)
}

View File

@@ -0,0 +1,31 @@
import { Link } from '@tanstack/react-router'
import { Plus } from 'lucide-react'
import { useCollapseOnScroll } from '../../hooks/useCollapseOnScroll'
import { cn } from '../../lib/utils'
/* Floating "Nuevo grupo". On mobile it sits 16px above the BottomNav (56px +
safe area); on desktop there is no nav, so it goes to the corner. While the
user scrolls down the label folds away and only the "+" stays; the
accessible name never changes. `motion-reduce` swaps without animating. */
export function NewGroupFab() {
const collapsed = useCollapseOnScroll()
return (
<Link
to="/groups/new"
aria-label="Nuevo grupo"
className="fixed right-4 bottom-[calc(3.5rem+env(safe-area-inset-bottom)+1rem)] z-40 inline-flex h-14 items-center rounded-[18px] bg-accent px-4 font-semibold text-on-accent shadow-[0_10px_28px_-8px_rgb(37_68_234/0.65)] transition-colors hover:bg-accent-strong focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none lg:right-8 lg:bottom-8"
>
<Plus className="size-6 shrink-0" strokeWidth={2.25} aria-hidden="true" />
<span
aria-hidden="true"
className={cn(
'overflow-hidden whitespace-nowrap transition-[max-width,opacity,margin] duration-[220ms] ease-out motion-reduce:transition-none',
collapsed ? 'ml-0 max-w-0 opacity-0' : 'ml-2 max-w-40 opacity-100',
)}
>
Nuevo grupo
</span>
</Link>
)
}

View File

@@ -1,292 +1,115 @@
import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
import type { AttentionGroup, AttentionMember, GroupListItem, StudentAlertSeverity, UrgentMemberSummary } from '@gruperly/shared'
import { compareByWorstAlert, worstAlert } from '@gruperly/shared'
/* Derivations for the group listing card. The card queries nothing: it decides
here what is shown, with what tone and with what visual weight, so the JSX only
builds the layout and the rules can be tested on their own.
here what is shown and in what order, so the JSX only builds the layout and
the rules can be tested on their own.
The per-level counts and the urgent attendees are not computed on the client:
they come from `GET /groups-risk/overview`, which runs the same domain function
(`getGroupAttendanceSummary` in packages/shared) that the follow-up section on
Home will use. Here we only adapt that response to what the card needs to paint,
and we decide how it reads. */
The faces come from `GET /attention` (ACTIVE members with their alerts, the
same data as the "Requiere atención" screen); the occupancy from the group
listing (`attendeesCount`, which is what the capacity checks count). */
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
/** With this many spots or fewer the whole group fits in one line of 32px
* avatars next to the status text on a ~360px phone: one face per member and
* a dashed circle per free spot. Above it, faces overlap and end in "+N". */
export const INLINE_SLOTS_MAX = 6
/** From this capacity on, the indicator stops being one segment per spot and
* switches to proportional blocks.
*
* The threshold is set by the width, not by a round number. The bar has to fit
* in a phone's card: ~291px on a 402px viewport, after discounting `<main>`'s
* padding, the card's and the occupancy label. With the 6px gap, ten segments
* come out at ~24px each: narrow but still a pill with its own color. That number
* depends on two card decisions that are not obvious: the label says "4/5" on
* mobile and not "4/5 miembros" (the word took ~60px), and the segment splits
* the width instead of measuring a fixed 50px. With either of the two the other
* way, capacity 10 becomes unreadable again.
*
* From the seventh on the pill narrows gradually, and on a 320px viewport
* capacity 10 drops to ~15px, which already reads more like a dot than a color.
* We prefer it anyway: seeing which spot is free and what level each one is still
* says more than a proportional bar, and the flexible split plus `overflow-hidden`
* guarantee it never overflows the screen. */
export const SEGMENTED_CAPACITY_MAX = 10
/** Faces drawn before the "+N" when the row overlaps. */
export const STACKED_FACES = 4
export type MemberStatus = 'high_risk' | 'attention' | 'ok'
export type AvatarSlot =
| { kind: 'member'; member: AttentionMember; severity: StudentAlertSeverity | null }
| { kind: 'free'; key: string }
| { kind: 'more'; count: number }
export type GroupMember = {
id: string
name: string
status: MemberStatus
absences: number
/** Why they are on the alert line ("3 faltas", "12 días sin venir"). When
* missing, the absences are used. */
reason?: string
}
export type CapacityCounts = {
riesgoAlto: number
atencion: number
ok: number
libres: number
}
export type AvatarRowModel = { stacked: boolean; slots: AvatarSlot[] }
/**
* Counts derived directly from a member list and the capacity.
*/
export function capacityCountsFromMembers(
members: GroupMember[],
capacity: number,
): CapacityCounts {
let riesgoAlto = 0
let atencion = 0
let ok = 0
for (const m of members) {
if (m.status === 'high_risk') riesgoAlto++
else if (m.status === 'attention') atencion++
else ok++
}
const libres = Math.max(capacity - members.length, 0)
return {
riesgoAlto,
atencion,
ok,
libres,
}
}
/**
* Alert text rules derived from the members:
* - 1 at high risk: "{Nombre}: {N} faltas" + (if attention > 0) " · {K} en atención"
* - 2 or more at high risk: "{N} en riesgo alto" + (if attention > 0) " · {K} en atención"
* - 0 at high risk but attention > 0: "{K} en atención"
* - None: null
*/
export function alertTextFromMembers(members: GroupMember[]): string | null {
const highRisk = members.filter((m) => m.status === 'high_risk')
const attention = members.filter((m) => m.status === 'attention')
const kAtencion = attention.length > 0 ? ` · ${attention.length} en atención` : ''
if (highRisk.length === 1) {
const first = highRisk[0]
const nombre = firstName(first.name)
const motivo = first.reason ?? `${first.absences} ${first.absences === 1 ? 'falta' : 'faltas'}`
return `${nombre}: ${motivo}${kAtencion}`
}
if (highRisk.length >= 2) {
return `${highRisk.length} en riesgo alto${kAtencion}`
}
if (attention.length > 0) {
return `${attention.length} en atención`
}
return null
}
/**
* Turns a GroupListItem and GroupRiskSummary into a list of GroupMember to unify
* the internal representation.
*/
export function membersFromGroupAndRisk(
group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>,
risk: GroupRiskSummary | undefined,
): GroupMember[] {
const members: GroupMember[] = []
const urgentes = risk?.urgentes ?? []
for (const u of urgentes) {
if (u.level === 'riesgo_alto') {
members.push({
id: u.attendeeId,
name: u.fullName,
status: 'high_risk',
absences: u.consecutiveAbsences,
reason: absenceReason(u) ?? undefined,
})
} else if (u.level === 'atencion') {
members.push({
id: u.attendeeId,
name: u.fullName,
status: 'attention',
absences: u.consecutiveAbsences,
reason: absenceReason(u) ?? undefined,
})
}
}
const currentHigh = members.filter((m) => m.status === 'high_risk').length
const remainingHigh = Math.max((risk?.riesgoAlto ?? 0) - currentHigh, 0)
for (let i = 0; i < remainingHigh; i++) {
members.push({
id: `high-risk-extra-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'high_risk',
absences: 1,
})
}
const currentAttention = members.filter((m) => m.status === 'attention').length
const remainingAttention = Math.max((risk?.atencion ?? 0) - currentAttention, 0)
for (let i = 0; i < remainingAttention; i++) {
members.push({
id: `attention-extra-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'attention',
absences: 0,
})
}
const remainingOk = Math.max(group.attendeesCount - members.length, 0)
for (let i = 0; i < remainingOk; i++) {
members.push({
id: `ok-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'ok',
absences: 0,
})
}
return members
}
/**
* Counts consumed by the capacity and attendance indicator.
* The avatar row of a card. Students with an alert go first (worst first) and
* carry their severity ring; the rest keep the order they joined in.
*
* `ok` is the remainder, not a number from the API: the risk summary only names
* the ones worth watching, and the rest of the roster is what is doing fine. It
* is clamped to 0 because the summary counts active members while the card shows
* all of them.
*
* With no summary yet (or if the query fails) every member falls into `ok`. It is
* the calm state: the summary can still be loading and the card has to be able
* to paint anyway.
* - Fits in a line and has free spots: every face plus a dashed circle per spot.
* - Otherwise (big or full group): overlapped faces, the last circle is "+N".
*/
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
const riesgoAlto = risk?.riesgoAlto ?? 0
const atencion = risk?.atencion ?? 0
const libres = group.capacity === null ? 0 : Math.max(group.capacity - group.attendeesCount, 0)
export function avatarRow(
members: AttentionMember[],
capacity: number | null,
occupied: number = members.length,
): AvatarRowModel {
const ordered = [...members].sort((a, b) => {
const flagged = Number(b.alerts.length > 0) - Number(a.alerts.length > 0)
return flagged !== 0 ? flagged : a.alerts.length > 0 ? compareByWorstAlert(a, b) : 0
})
const faces = ordered.map(
(member): AvatarSlot => ({ kind: 'member', member, severity: worstAlert(member.alerts)?.gravedad ?? null }),
)
const free = freeSpots(capacity, occupied)
return {
riesgoAlto,
atencion,
ok: Math.max(group.attendeesCount - riesgoAlto - atencion, 0),
libres,
}
}
/** Tone of the status line and of the indicator: the worst level present. */
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
export function riskTone(counts: CapacityCounts): RiskTone {
if (counts.riesgoAlto > 0) return 'riesgo_alto'
if (counts.atencion > 0) return 'atencion'
return 'ok'
}
export type StatusLine = {
text: string
tone: RiskTone
}
/**
* The card's fourth row: what is going on with attendance.
*
* With a single person at high risk it shows their name and absence count. With
* two or more it summarizes by level. When there is nothing to report, the
* component leaves this line out entirely.
*/
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
const counts = capacityCounts(group, risk)
const tone = riskTone(counts)
const urgentes = risk?.urgentes.filter((miembro) => miembro.level !== 'ok') ?? []
if (tone !== 'ok') {
const conNombre = counts.riesgoAlto === 1 ? namedHighRiskMember(urgentes, counts) : ''
return { text: conNombre || countedLevels(counts), tone }
if (capacity !== null && capacity <= INLINE_SLOTS_MAX && free > 0) {
const dashed = Array.from({ length: free }, (_, index): AvatarSlot => ({ kind: 'free', key: `free-${index}` }))
return { stacked: false, slots: [...faces, ...dashed] }
}
if (risk?.asistencia != null) return { text: `Asistencia ${risk.asistencia}%`, tone: 'ok' }
return { text: 'Sin clases registradas', tone: 'ok' }
// "+N" only when it saves at least two faces: "+1" takes the same room as
// the face it hides.
if (occupied <= STACKED_FACES + 1) {
return { stacked: true, slots: faces }
}
const shown = faces.slice(0, STACKED_FACES)
return { stacked: true, slots: [...shown, { kind: 'more', count: occupied - shown.length }] }
}
/**
* The total the indicator is measured against.
*
* When the group has no declared capacity the bar does not disappear: it goes on
* measuring the roster, one segment (or block) per member, with the free spots
* at zero. A group with no capacity has no "free spots" to show, but it does have
* people at risk, and that is exactly the signal the bar exists to communicate.
* What does disappear is the bar of an empty group: with no members there is
* nothing to split.
*/
export function barCapacity(group: GroupLike): number {
return group.capacity ?? group.attendeesCount
export type GroupStatus =
| { tone: StudentAlertSeverity; text: string }
| { tone: 'free'; text: string }
| { tone: 'full'; text: string }
| null
/** Text to the right of the avatars: risk first, then free spots, then full. */
export function groupStatus(
members: AttentionMember[],
capacity: number | null,
occupied: number = members.length,
): GroupStatus {
const flagged = members.filter((member) => member.alerts.length > 0)
if (flagged.length > 0) {
const urgent = flagged.some((member) => member.alerts.some((alert) => alert.gravedad === 'urgente'))
return { tone: urgent ? 'urgente' : 'vigilar', text: `${flagged.length} en riesgo` }
}
if (capacity === null) return null
const free = freeSpots(capacity, occupied)
if (free > 0) return { tone: 'free', text: `${free} ${free === 1 ? 'libre' : 'libres'}` }
return { tone: 'full', text: 'Completo' }
}
/** Does the indicator go with one segment per spot, or with proportional blocks? */
export function isSegmentedCapacity(capacity: number): boolean {
return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX
/** "4 grupos · 37 alumnos · 7 lugares libres" under the page title. */
export function groupsSummary(groups: Pick<GroupListItem, 'attendeesCount' | 'capacity'>[]): string {
const students = groups.reduce((total, group) => total + group.attendeesCount, 0)
const free = groups.reduce((total, group) => total + freeSpots(group.capacity, group.attendeesCount), 0)
return [
plural(groups.length, 'grupo', 'grupos'),
plural(students, 'alumno', 'alumnos'),
plural(free, 'lugar libre', 'lugares libres'),
].join(' · ')
}
/** "5/10 miembros", or "5 miembros" when the group has no defined capacity. */
export function occupancyLabel(group: GroupLike): string {
if (group.capacity === null) return membersLabel(group.attendeesCount)
return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}`
/** The members of a group in the attention overview, or none while it loads. */
export function membersOf(attention: AttentionGroup[] | undefined, groupId: string): AttentionMember[] | undefined {
return attention?.find((group) => group.groupId === groupId)?.members
}
/** Names the single person at high risk and adds the attention total. */
function namedHighRiskMember(
urgentes: UrgentMemberSummary[],
counts: CapacityCounts,
): string {
const urgente = urgentes.find((miembro) => miembro.level === 'riesgo_alto')
if (!urgente) return ''
const motivo = absenceReason(urgente)
if (!motivo) return ''
const nombre = `${firstName(urgente.fullName)}: ${motivo}`
return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre
function freeSpots(capacity: number | null, occupied: number): number {
return capacity === null ? 0 : Math.max(capacity - occupied, 0)
}
/** Big group: the per-level counts, and only for the ones with something to say. */
function countedLevels(counts: CapacityCounts): string {
const partes: string[] = []
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
if (counts.atencion > 0) partes.push(`${counts.atencion} en atención`)
return partes.join(' · ')
function plural(count: number, one: string, many: string): string {
return `${count} ${count === 1 ? one : many}`
}
/* The reason that best explains why someone is on the status line, in the order
the rule considers them: first a streak of absences (something that is going
away), then the time since last showing up, and last the attendance rate. A
single absence only names them when nothing else does: someone at high risk
for inactivity reads better as "12 días sin venir" than as "1 falta". */
/* The reason Home shows next to an at-risk student: first a streak of absences
(something that is going away), then the time since last showing up, and
last the attendance rate. A single absence only names them when nothing else
does. */
export function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
@@ -296,67 +119,3 @@ export function absenceReason(miembro: UrgentMemberSummary): string | null {
if (asistencia != null && asistencia < 100) return `asistencia ${asistencia}%`
return null
}
/* First name only: on a 360px line "Sofía Ramírez: 4 faltas" does not fit, and
between two people with the same name the detail page tells them apart. */
function firstName(fullName: string): string {
return fullName.trim().split(/\s+/)[0] || fullName
}
function membersLabel(count: number): string {
return count === 1 ? '1 miembro' : `${count} miembros`
}
/**
* Test cases requested for verification against the reference image.
*/
export const MOCK_TEST_CASES = [
{
id: 'mock-tai-chi',
name: 'Tai Chi Martes',
capacity: 5,
members: [
{ id: 'tc-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
{ id: 'tc-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
{ id: 'tc-3', name: 'Martín Paz', status: 'ok' as const, absences: 0 },
{ id: 'tc-4', name: 'Elena Gómez', status: 'ok' as const, absences: 0 },
],
},
{
id: 'mock-pilates',
name: 'Pilates Sábado',
capacity: 15,
members: [
{ id: 'p-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
{ id: 'p-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
{ id: 'p-3', name: 'Mateo Díaz', status: 'attention' as const, absences: 1 },
...Array.from({ length: 9 }, (_, i) => ({
id: `p-ok-${i}`,
name: `Alumno ${i + 1}`,
status: 'ok' as const,
absences: 0,
})),
],
},
{
id: 'mock-natacion',
name: 'Natación Adultos',
capacity: 30,
members: [
{ id: 'n-1', name: 'Alumno 1', status: 'high_risk' as const, absences: 3 },
{ id: 'n-2', name: 'Alumno 2', status: 'high_risk' as const, absences: 2 },
{ id: 'n-3', name: 'Alumno 3', status: 'high_risk' as const, absences: 4 },
{ id: 'n-4', name: 'Alumno 4', status: 'attention' as const, absences: 1 },
{ id: 'n-5', name: 'Alumno 5', status: 'attention' as const, absences: 1 },
{ id: 'n-6', name: 'Alumno 6', status: 'attention' as const, absences: 2 },
{ id: 'n-7', name: 'Alumno 7', status: 'attention' as const, absences: 1 },
...Array.from({ length: 15 }, (_, i) => ({
id: `n-ok-${i}`,
name: `Alumno ${i + 8}`,
status: 'ok' as const,
absences: 0,
})),
],
},
]

View File

@@ -0,0 +1,41 @@
import { useEffect, useState } from 'react'
type CollapseOptions = {
/** Scroll from the top before collapsing is allowed. */
threshold?: number
/** Time without scrolling after which it expands again. */
idleMs?: number
}
/**
* `true` while the user scrolls down past `threshold`; `false` when they scroll
* up, stop for `idleMs`, or are back at the top. For a FAB that shrinks to its
* icon so it doesn't cover the content being read.
*/
export function useCollapseOnScroll({ threshold = 24, idleMs = 700 }: CollapseOptions = {}) {
const [collapsed, setCollapsed] = useState(false)
useEffect(() => {
let lastY = window.scrollY
let idleTimer: ReturnType<typeof setTimeout> | undefined
const onScroll = () => {
const y = window.scrollY
if (y <= threshold) setCollapsed(false)
else if (y > lastY) setCollapsed(true)
else if (y < lastY) setCollapsed(false)
lastY = y
clearTimeout(idleTimer)
idleTimer = setTimeout(() => setCollapsed(false), idleMs)
}
window.addEventListener('scroll', onScroll, { passive: true })
return () => {
window.removeEventListener('scroll', onScroll)
clearTimeout(idleTimer)
}
}, [threshold, idleMs])
return collapsed
}

View File

@@ -70,6 +70,17 @@
--color-attendance-high: var(--attendance-high);
--color-attendance-attention: var(--attendance-attention);
--color-attendance-ok: var(--attendance-ok);
/* "Requiere atención": severity of a student alert (ring, text, pill and the
container of the Grupos preview) and the "N libres" green. */
--color-alert-urgent-ring: var(--alert-urgent-ring);
--color-alert-urgent-fg: var(--alert-urgent-fg);
--color-alert-urgent-soft: var(--alert-urgent-soft);
--color-alert-urgent-surface: var(--alert-urgent-surface);
--color-alert-urgent-edge: var(--alert-urgent-edge);
--color-alert-watch-ring: var(--alert-watch-ring);
--color-alert-watch-fg: var(--alert-watch-fg);
--color-alert-watch-soft: var(--alert-watch-soft);
--color-free-fg: var(--free-fg);
/* Default border radius */
--radius-xl: 0.75rem;
@@ -157,6 +168,18 @@
--attendance-high: #d63b3b;
--attendance-attention: #f5a623;
--attendance-ok: #2b7bd6;
/* Alert severities. Text on its pill: urgent #b91c1c on #fee2e2 is 5.4:1,
watch #92400e on #fef3c7 is 6.4:1; the free green #15803d is 5.0:1 on the
card. The rings are fills (3:1 is enough), always next to a text label. */
--alert-urgent-ring: #dc2626;
--alert-urgent-fg: #b91c1c;
--alert-urgent-soft: #fee2e2;
--alert-urgent-surface: #fef2f2;
--alert-urgent-edge: #fecaca;
--alert-watch-ring: #d97706;
--alert-watch-fg: #92400e;
--alert-watch-soft: #fef3c7;
--free-fg: #15803d;
}
.dark {
@@ -194,6 +217,15 @@
/* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
more than enough as a fill, so there's nothing to move here. */
--danger-fg: var(--danger);
--alert-urgent-ring: #f87171;
--alert-urgent-fg: #fca5a5;
--alert-urgent-soft: #2e1419;
--alert-urgent-surface: #15111a;
--alert-urgent-edge: #3a2028;
--alert-watch-ring: #fbbf24;
--alert-watch-fg: #fde68a;
--alert-watch-soft: #2b220f;
--free-fg: #86efac;
}
@layer base {

View File

@@ -31,6 +31,8 @@ import type {
GroupPreRegistrationList,
GroupRiskSummary,
GroupsRiskOverview,
AttentionOverview,
ResolveAlert,
GroupWaitlistEntryDto,
GroupWaitlistList,
HomeSummaryDto,
@@ -376,6 +378,14 @@ export const getStudentsAtRisk = (groupId: string) =>
export const getGroupsRiskOverview = () => apiFetch<GroupsRiskOverview>('/api/v1/groups-risk/overview')
export const getAttention = () => apiFetch<AttentionOverview>('/api/v1/attention')
export const resolveAlert = (attendeeId: string, body: ResolveAlert) =>
apiFetch<ResolveAlert & { attendeeId: string }>(`/api/v1/attention/${attendeeId}/resolve`, {
method: 'POST',
body: JSON.stringify(body),
})
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)

View File

@@ -8,6 +8,7 @@
still uses the global header. */
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
['groups', 'attention'],
['groups', ':id'],
['groups', ':id', 'analytics'],
['groups', ':id', 'attendees', ':attendeeId'],
@@ -16,8 +17,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
/* Static routes that sit where a param would go. Without this list
`/groups/new` (create group) would be taken for a group detail page and would
lose the global header. */
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
lose the global header, and `/groups/attention/...` for a group's children.
(`/groups/attention` itself is immersive through its own pattern.) */
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new', 'attention'])
export function isImmersiveRoute(pathname: string) {
const segments = pathname.split('/').filter(Boolean)

View File

@@ -27,6 +27,7 @@ import { Route as AdminIndexRouteImport } from './routes/admin/index'
import { Route as JoinTokenRouteImport } from './routes/join.$token'
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index'
import { Route as AuthenticatedGroupsAttentionRouteImport } from './routes/_authenticated/groups/attention'
import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new'
import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accounts.$accountId'
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
@@ -125,6 +126,12 @@ const AuthenticatedGroupsIndexRoute =
path: '/groups/',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedGroupsAttentionRoute =
AuthenticatedGroupsAttentionRouteImport.update({
id: '/groups/attention',
path: '/groups/attention',
getParentRoute: () => AuthenticatedRoute,
} as any)
const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({
id: '/groups/new',
path: '/groups/new',
@@ -183,6 +190,7 @@ export interface FileRoutesByFullPath {
'/join/$token': typeof JoinTokenRoute
'/report-absence/$token': typeof ReportAbsenceTokenRoute
'/admin/': typeof AdminIndexRoute
'/groups/attention': typeof AuthenticatedGroupsAttentionRoute
'/groups/new': typeof AuthenticatedGroupsNewRoute
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
'/groups/': typeof AuthenticatedGroupsIndexRoute
@@ -208,6 +216,7 @@ export interface FileRoutesByTo {
'/report-absence/$token': typeof ReportAbsenceTokenRoute
'/': typeof AuthenticatedIndexRoute
'/admin': typeof AdminIndexRoute
'/groups/attention': typeof AuthenticatedGroupsAttentionRoute
'/groups/new': typeof AuthenticatedGroupsNewRoute
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
'/groups': typeof AuthenticatedGroupsIndexRoute
@@ -236,6 +245,7 @@ export interface FileRoutesById {
'/report-absence/$token': typeof ReportAbsenceTokenRoute
'/_authenticated/': typeof AuthenticatedIndexRoute
'/admin/': typeof AdminIndexRoute
'/_authenticated/groups/attention': typeof AuthenticatedGroupsAttentionRoute
'/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
'/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute
@@ -264,6 +274,7 @@ export interface FileRouteTypes {
| '/join/$token'
| '/report-absence/$token'
| '/admin/'
| '/groups/attention'
| '/groups/new'
| '/admin/accounts/$accountId'
| '/groups/'
@@ -289,6 +300,7 @@ export interface FileRouteTypes {
| '/report-absence/$token'
| '/'
| '/admin'
| '/groups/attention'
| '/groups/new'
| '/admin/accounts/$accountId'
| '/groups'
@@ -316,6 +328,7 @@ export interface FileRouteTypes {
| '/report-absence/$token'
| '/_authenticated/'
| '/admin/'
| '/_authenticated/groups/attention'
| '/_authenticated/groups/new'
| '/admin/accounts/$accountId'
| '/_authenticated/groups/'
@@ -467,6 +480,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedGroupsIndexRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/groups/attention': {
id: '/_authenticated/groups/attention'
path: '/groups/attention'
fullPath: '/groups/attention'
preLoaderRoute: typeof AuthenticatedGroupsAttentionRouteImport
parentRoute: typeof AuthenticatedRoute
}
'/_authenticated/groups/new': {
id: '/_authenticated/groups/new'
path: '/groups/new'
@@ -526,6 +546,7 @@ interface AuthenticatedRouteChildren {
AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute
AuthenticatedSettingsRoute: typeof AuthenticatedSettingsRoute
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
AuthenticatedGroupsAttentionRoute: typeof AuthenticatedGroupsAttentionRoute
AuthenticatedGroupsNewRoute: typeof AuthenticatedGroupsNewRoute
AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
@@ -542,6 +563,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
AuthenticatedSecurityRoute: AuthenticatedSecurityRoute,
AuthenticatedSettingsRoute: AuthenticatedSettingsRoute,
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
AuthenticatedGroupsAttentionRoute: AuthenticatedGroupsAttentionRoute,
AuthenticatedGroupsNewRoute: AuthenticatedGroupsNewRoute,
AuthenticatedGroupsIndexRoute: AuthenticatedGroupsIndexRoute,
AuthenticatedClassSessionIdAttendanceRoute:

View File

@@ -0,0 +1,11 @@
import { createFileRoute } from '@tanstack/react-router'
import { AttentionProvider } from '../../../features/attention/AttentionProvider'
import { AttentionView } from '../../../features/attention/AttentionView'
export const Route = createFileRoute('/_authenticated/groups/attention')({
component: () => (
<AttentionProvider>
<AttentionView />
</AttentionProvider>
),
})

View File

@@ -0,0 +1,167 @@
import { describe, expect, test } from 'bun:test'
import type { AttentionMember, AttentionOverview, StudentAlert } from '@gruperly/shared'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import {
attentionItems,
attentionSubtitle,
filterCounts,
filterItems,
flaggedStudents,
itemsBySeverity,
reminderMessage,
whatsappLink,
withoutAlert,
} from '../src/features/attention/attention'
import { FilterChips } from '../src/features/attention/FilterChips'
/* "Requiere atención" recibe las alertas calculadas: acá se prueba cómo se
aplanan en tarjetas, se cuentan por filtro y gravedad, y qué mensaje sale. */
const alerta = (tipo: StudentAlert['tipo'], gravedad: StudentAlert['gravedad'], peso = 2): StudentAlert => ({
tipo,
gravedad,
etiqueta: tipo === 'pago' ? 'Cuota vencida' : `${peso} faltas`,
detalle: '',
firma: `${tipo}-firma`,
peso,
})
const miembro = (id: string, fullName: string, alerts: StudentAlert[], extra: Partial<AttentionMember> = {}) => ({
attendeeId: id,
fullName,
phone: '11 5555-0000',
whatsappPhone: '+5491155550000',
alerts,
overduePayments: [],
...extra,
})
const overview: AttentionOverview = {
groups: [
{
groupId: 'g1',
groupName: 'Natación',
capacity: 30,
members: [
miembro('a1', 'Agustina', [alerta('asistencia', 'urgente', 4)]),
miembro('a2', 'Bruno', [alerta('pago', 'vigilar', 1)]),
miembro('a3', 'Felipe', []),
// Dos alertas: aparece en dos tarjetas, pero cuenta como un alumno.
miembro('a4', 'Valentina', [alerta('pago', 'urgente', 2), alerta('asistencia', 'vigilar')]),
],
},
{
groupId: 'g2',
groupName: 'Tai Chi Martes',
capacity: 4,
members: [miembro('b1', 'Martina', [alerta('asistencia', 'vigilar')])],
},
],
}
describe('flaggedStudents', () => {
test('solo los alumnos con alerta, el más urgente primero, con su peor alerta', () => {
const students = flaggedStudents(overview)
expect(students.map((student) => [student.fullName, student.worst.gravedad])).toEqual([
['Agustina', 'urgente'],
['Valentina', 'urgente'],
['Martina', 'vigilar'],
['Bruno', 'vigilar'],
])
expect(students[2].groupName).toBe('Tai Chi Martes')
})
test('sin datos no hay alumnos', () => {
expect(flaggedStudents(undefined)).toEqual([])
})
})
describe('tarjetas, filtros y contadores', () => {
const items = attentionItems(flaggedStudents(overview))
test('una tarjeta por alerta, urgentes primero', () => {
expect(items.map((item) => `${item.student.fullName}:${item.alert.tipo}`)).toEqual([
'Agustina:asistencia',
'Valentina:pago',
'Martina:asistencia',
'Valentina:asistencia',
'Bruno:pago',
])
})
test('cuenta por filtro', () => {
expect(filterCounts(items)).toEqual({ todos: 5, asistencia: 3, pago: 2 })
expect(filterItems(items, 'pago').map((item) => item.student.fullName)).toEqual(['Valentina', 'Bruno'])
})
test('separa por gravedad', () => {
const { urgente, vigilar } = itemsBySeverity(items)
expect(urgente).toHaveLength(2)
expect(vigilar).toHaveLength(3)
})
test('el subtítulo cuenta alumnos, no tarjetas', () => {
expect(attentionSubtitle(items)).toBe('4 alumnos · 2 urgentes')
expect(attentionSubtitle(filterItems(items, 'asistencia').slice(2))).toBe('1 alumno')
expect(attentionSubtitle([])).toBe('Nada pendiente')
})
test('"Resuelto" saca solo esa alerta del caché', () => {
const next = withoutAlert(overview, 'a4', 'pago')
const valentina = next.groups[0].members.find((member) => member.attendeeId === 'a4')
expect(valentina?.alerts.map((alert) => alert.tipo)).toEqual(['asistencia'])
expect(filterCounts(attentionItems(flaggedStudents(next)))).toEqual({ todos: 4, asistencia: 3, pago: 1 })
})
})
describe('WhatsApp', () => {
test('arma el link con el E.164 y el texto', () => {
expect(whatsappLink({ whatsappPhone: '+5491155550000' })).toBe('https://wa.me/5491155550000')
expect(whatsappLink({ whatsappPhone: '+5491155550000' }, 'Hola')).toBe('https://wa.me/5491155550000?text=Hola')
expect(whatsappLink({ whatsappPhone: null })).toBeNull()
})
test('el recordatorio nombra la cuota, la fecha y el link de pago', () => {
const [student] = flaggedStudents({
groups: [
{
groupId: 'g1',
groupName: 'Natación',
capacity: 30,
members: [
miembro('a1', 'Nicolás Gómez', [alerta('pago', 'vigilar', 1)], {
overduePayments: [
{
id: 'p1',
amount: 15000,
currency: 'ARS',
dueDate: '2026-10-10T12:00:00.000Z',
checkoutUrl: 'https://mpago.la/abc',
},
],
}),
],
},
],
})
const message = reminderMessage(student)
expect(message).toStartWith('¡Hola Nicolás!')
expect(message).toContain('la cuota de Natación')
expect(message).toContain('venció el 10/10')
expect(message).toContain('https://mpago.la/abc')
})
})
test('los chips marcan el activo con aria-pressed y muestran su contador', () => {
const markup = renderToStaticMarkup(
createElement(FilterChips, {
value: 'asistencia',
counts: { todos: 7, asistencia: 4, pago: 3 },
onChange: () => undefined,
}),
)
expect(markup.match(/aria-pressed="true"/g)).toHaveLength(1)
expect(markup).toMatch(/aria-pressed="true"[^>]*>Asistencia/)
expect(markup).toContain('>7<')
})

View File

@@ -1,544 +1,145 @@
import { describe, expect, test } from 'bun:test'
import type { GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
import type { AttentionMember, StudentAlert } from '@gruperly/shared'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { AvatarRow } from '../src/features/groups/AvatarRow'
import {
alertTextFromMembers,
barCapacity,
capacityCounts,
capacityCountsFromMembers,
isSegmentedCapacity,
MOCK_TEST_CASES,
occupancyLabel,
riskTone,
SEGMENTED_CAPACITY_MAX,
statusLine,
type GroupMember,
avatarRow,
groupStatus,
groupsSummary,
INLINE_SLOTS_MAX,
membersOf,
STACKED_FACES,
} from '../src/features/groups/card'
import {
capacityIndicatorLabel,
capacitySegmentWidth,
} from '../src/features/groups/AttendanceCapacityIndicator'
import { GroupCard, GroupCardContent } from '../src/features/groups/GroupCard'
/* La tarjeta del listado no calcula el riesgo: lo recibe de
`GET /groups-risk/overview`, que corre la función de dominio del backend. Lo
que se prueba acá es la traducción de esa respuesta a la tarjeta: qué se
cuenta, qué se nombra y cuándo la card se tiñe. Todo sin montar React. */
/* La tarjeta del listado no calcula alertas: las recibe de `GET /attention`,
que corre `computeStudentAlerts` (shared). Acá se prueba cómo se dibujan:
qué caras van, en qué orden, cuándo se superponen y qué estado se nombra. */
const risk = (
riesgoAlto: number,
atencion: number,
extra: Partial<GroupRiskSummary> = {},
): GroupRiskSummary => ({
groupId: 'grp_1',
groupName: 'Pilates',
riskLevel: riesgoAlto > 0 ? 'HIGH' : atencion > 0 ? 'MEDIUM' : 'NONE',
absenceStreakCount: riesgoAlto,
lowAttendanceCount: atencion,
riesgoAlto,
atencion,
ok: 0,
libres: 0,
enEspera: 0,
asistencia: 100,
urgentes: [],
...extra,
const alerta = (gravedad: StudentAlert['gravedad'], peso = 2): StudentAlert => ({
tipo: 'asistencia',
gravedad,
etiqueta: `${peso} faltas`,
detalle: '',
firma: 'ses_1',
peso,
})
const urgente = (extra: Partial<UrgentMemberSummary> = {}): UrgentMemberSummary => ({
attendeeId: 'at_1',
fullName: 'Sofía Ramírez',
level: 'riesgo_alto',
consecutiveAbsences: 0,
daysSinceLastAttendance: null,
attendanceRate: null,
...extra,
const miembro = (id: string, alerts: StudentAlert[] = []): AttentionMember => ({
attendeeId: id,
fullName: `Alumno ${id}`,
phone: null,
whatsappPhone: null,
alerts,
overduePayments: [],
})
const grupo = (attendeesCount: number, capacity: number | null) => ({ attendeesCount, capacity })
const miembros = (count: number) => Array.from({ length: count }, (_, index) => miembro(`m${index + 1}`))
describe('GroupCard - Casos de prueba de referencia', () => {
test('Caso 1: Tai Chi Martes (cupo 5, 4/5 miembros, 5 píldoras, alerta Sofía)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[0], link: false }))
// Fila 1: el nombre solo. El cupo no se repite: ya está en el "4/5"
expect(markup).toContain('Tai Chi Martes')
// Fila 2: 4/5 en una sola línea y 5 píldoras individuales. La palabra
// "miembros" va en un span oculto en móvil: se lleva ~60px que la barra
// necesita para que las píldoras sigan siendo píldoras.
expect(markup).toContain('4/5')
expect(markup).toContain('shrink-0 whitespace-nowrap text-base tabular-nums text-secondary">4/5<span')
expect(markup).toContain('hidden sm:inline">')
// Píldoras individuales (Modo A: cupo <= 10)
// 1 rojo (high), 1 ámbar (attention), 2 azul (ok), 1 vacía (libres)
expect(markup).toContain('min-w-0 flex-1 max-w-[50px]')
expect(markup).toContain('bg-attendance-high')
expect(markup).toContain('bg-attendance-attention')
expect(markup).toContain('bg-attendance-ok')
// Fila 3: alerta roja con ícono de cuadrado
expect(markup).toContain('Sofía: 4 faltas · 1 en atención')
expect(markup).toContain('text-[#8B1A1A]')
describe('avatarRow', () => {
test('grupo chico: una cara por alumno y un círculo punteado por lugar libre', () => {
const row = avatarRow(miembros(1), 4)
expect(row.stacked).toBe(false)
expect(row.slots.map((slot) => slot.kind)).toEqual(['member', 'free', 'free', 'free'])
})
test('Caso 2: Pilates Sábado (cupo 15, 12/15 miembros, barra continua, alerta Sofía)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[1], link: false }))
// Fila 1: el nombre solo
expect(markup).toContain('Pilates Sábado')
// Fila 2
expect(markup).toContain('12/15<span')
// Modo B: barra continua (overflow-hidden rounded-full)
expect(markup).toContain('overflow-hidden rounded-full')
// Fila 3: alerta
expect(markup).toContain('Sofía: 4 faltas · 2 en atención')
expect(markup).toContain('text-[#8B1A1A]')
test(`hasta ${INLINE_SLOTS_MAX} lugares entra en una línea`, () => {
expect(avatarRow(miembros(2), INLINE_SLOTS_MAX).stacked).toBe(false)
expect(avatarRow(miembros(2), INLINE_SLOTS_MAX + 1).stacked).toBe(true)
})
test('Caso 3: Natación Adultos (cupo 30, 22/30 miembros, barra continua, alerta múltiple)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[2], link: false }))
// Fila 1: el nombre solo
expect(markup).toContain('Natación Adultos')
// Fila 2
expect(markup).toContain('22/30<span')
// Modo B: barra continua
expect(markup).toContain('overflow-hidden rounded-full')
// Fila 3: alerta con 3 en riesgo alto y 4 en atención
expect(markup).toContain('3 en riesgo alto · 4 en atención')
expect(markup).toContain('text-[#8B1A1A]')
test('grupo grande: caras superpuestas y un "+N" con el resto', () => {
const row = avatarRow(miembros(30), 30)
expect(row.stacked).toBe(true)
expect(row.slots).toHaveLength(STACKED_FACES + 1)
expect(row.slots.at(-1)).toEqual({ kind: 'more', count: 30 - STACKED_FACES })
})
})
/* La barra segmentada se llevaba el ancho con un `w-[50px] shrink-0` por
segmento. Con 10 segmentos eso son 554px (más los gaps) contra los ~197px que
deja la tarjeta en un viewport de 402px: los hijos `shrink-0` se salían de la
caja y arrastraban al documento a un scroll horizontal en el iPhone. Estos
tests fijan la forma del arreglo — la barra reparte el ancho disponible y lo
recorta — para que nadie vuelva a poner un ancho fijo acá. */
describe('GroupCard - la barra nunca desborda la tarjeta', () => {
const markupDeCupo = (capacity: number) =>
renderToStaticMarkup(
createElement(GroupCardContent, {
name: 'Tai Chi Martes',
capacity,
members: [{ id: 'a1', name: 'Sofía', status: 'ok', absences: 0 }],
}),
test('el "+N" cuenta la ocupación del grupo, no solo los activos', () => {
// 28 activos con cara, pero 30 lugares ocupados (2 en pausa).
const row = avatarRow(miembros(28), 30, 30)
expect(row.slots.at(-1)).toEqual({ kind: 'more', count: 26 })
})
test('un grupo chico completo se superpone sin "+N"', () => {
const row = avatarRow(miembros(5), 5)
expect(row.stacked).toBe(true)
expect(row.slots.map((slot) => slot.kind)).toEqual(['member', 'member', 'member', 'member', 'member'])
})
test('los alumnos con alerta van primero, el más grave adelante, con su gravedad', () => {
const row = avatarRow(
[miembro('ok-1'), miembro('vig', [alerta('vigilar')]), miembro('ok-2'), miembro('urg', [alerta('urgente', 3)])],
30,
)
/* Las clases llegan sueltas en el markup, así que se tokenizan: un `w-[50px]`
suelto es el bug y un `max-w-[50px]` es el arreglo, y un regex que busque
"w-[50px]" no distingue uno del otro. */
const clasesDe = (markup: string): string[] =>
[...markup.matchAll(/class="([^"]*)"/g)].flatMap(([, clases]) => clases.split(/\s+/))
test('el segmento no tiene ancho fijo: se reparte con flex y solo se topa', () => {
const clases = clasesDe(markupDeCupo(SEGMENTED_CAPACITY_MAX))
// `max-w` sí: un tope no desborda, el ancho disponible sigue mandando.
expect(clases).toContain('max-w-[50px]')
// `w-[...]` no: es lo que empujaba la pantalla. Cubre todo ancho fijo, no
// solo el de 50px que tenía antes. Ojo que `shrink-0` sí sigue en el
// markup, pero solo en el label ("N/M miembros" no puede partirse en dos
// líneas); lo que no puede volver es un ancho fijo en el segmento.
expect(clases.filter((clase) => /^w-\[/.test(clase))).toEqual([])
const caras = row.slots.flatMap((slot) => (slot.kind === 'member' ? [[slot.member.attendeeId, slot.severity]] : []))
expect(caras).toEqual([
['urg', 'urgente'],
['vig', 'vigilar'],
['ok-1', null],
['ok-2', null],
])
})
test('el contenedor de la barra segmentada recorta en vez de desbordar', () => {
expect(markupDeCupo(SEGMENTED_CAPACITY_MAX)).toContain('gap-1.5 overflow-hidden')
})
test('el render marca los lugares libres y el resto', () => {
const chico = renderToStaticMarkup(createElement(AvatarRow, { members: miembros(1), capacity: 3, occupied: 1 }))
expect(chico.match(/border-dashed/g)).toHaveLength(2)
test('un grupo completo conserva ancho para mostrar todos sus segmentos', () => {
const members = Array.from({ length: 5 }, (_, index) => ({
id: `a${index}`,
name: `Miembro ${index + 1}`,
status: 'ok' as const,
absences: 0,
}))
const markup = renderToStaticMarkup(
createElement(GroupCardContent, {
name: 'Grupo de Prueba',
capacity: 5,
members,
}),
)
expect(markup).toContain(
'flex h-3.5 min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
)
})
test('el peor caso (cupo 10) no introduce ancho fijo ni scroll propio', () => {
const markup = markupDeCupo(SEGMENTED_CAPACITY_MAX)
const clases = clasesDe(markup)
expect(clases.filter((clase) => /^w-\[/.test(clase))).toEqual([])
// Un contenedor con overflow horizontal propio scrollea; la tarjeta no
// debe tener ninguno: el desborde tiene que resolverse repartiendo el ancho.
expect(markup).not.toContain('overflow-x-auto')
expect(markup).not.toContain('overflow-scroll')
})
test('la barra continua (cupo > 10) también se queda dentro de la tarjeta', () => {
const markup = markupDeCupo(SEGMENTED_CAPACITY_MAX + 1)
expect(markup).toContain('flex-1 items-stretch overflow-hidden rounded-full')
expect(clasesDe(markup).filter((clase) => /^w-\[/.test(clase))).toEqual([])
})
/* Todo el rango segmentado (hasta 10) se dibuja con una píldora por lugar,
aunque en el tope la píldora quede angosta. Ver cuál está libre y de qué
nivel es cada uno informa más que una barra proporcional, así que el
umbral baja a 7-10 no es una opción: lo que tiene que garantizarse es que
la píldora angosta entre igual, sin ancho fijo y sin desbordar. */
test('los cupos 7-10 conservan la píldora por lugar', () => {
for (const capacity of [7, 8, 9, 10]) {
const markup = markupDeCupo(capacity)
expect(markup).toContain('max-w-[50px]')
expect(markup).not.toContain('flex-1 items-stretch overflow-hidden rounded-full')
}
})
test('un cupo bajo conserva la píldora por lugar', () => {
for (const capacity of [3, 4, 5, 6]) {
const markup = markupDeCupo(capacity)
expect(markup).toContain('max-w-[50px]')
expect(markup).not.toContain('flex-1 items-stretch overflow-hidden rounded-full')
}
const grande = renderToStaticMarkup(createElement(AvatarRow, { members: miembros(30), capacity: 30, occupied: 30 }))
expect(grande).toContain('+26')
expect(grande).toContain('-ml-1.5')
})
})
describe('alertTextFromMembers', () => {
test('con exactamente 1 miembro en riesgo alto muestra su nombre y faltas', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía Ramírez', status: 'high_risk', absences: 4 },
{ id: '2', name: 'Lucas', status: 'attention', absences: 1 },
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('Sofía: 4 faltas · 1 en atención')
describe('groupStatus', () => {
test('con alertas dice cuántos están en riesgo, con el tono de la peor', () => {
expect(groupStatus([miembro('a', [alerta('vigilar')]), miembro('b')], 4)).toEqual({
tone: 'vigilar',
text: '1 en riesgo',
})
expect(groupStatus([miembro('a', [alerta('vigilar')]), miembro('b', [alerta('urgente')])], 2)).toEqual({
tone: 'urgente',
text: '2 en riesgo',
})
})
test('con exactamente 1 miembro en riesgo alto y sin atención', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 1 },
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('Sofía: 1 falta')
test('sin alertas muestra los lugares libres, y si no hay, "Completo"', () => {
expect(groupStatus(miembros(1), 4)).toEqual({ tone: 'free', text: '3 libres' })
expect(groupStatus(miembros(3), 4)).toEqual({ tone: 'free', text: '1 libre' })
expect(groupStatus(miembros(4), 4)).toEqual({ tone: 'full', text: 'Completo' })
})
test('con 2 o más en riesgo alto resume por cantidad', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 4 },
{ id: '2', name: 'Mateo', status: 'high_risk', absences: 2 },
{ id: '3', name: 'Lucas', status: 'attention', absences: 1 },
]
expect(alertTextFromMembers(members)).toBe('2 en riesgo alto · 1 en atención')
})
test('sin riesgo alto pero con atención muestra solo atención', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Lucas', status: 'attention', absences: 1 },
{ id: '2', name: 'Elena', status: 'attention', absences: 1 },
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('2 en atención')
})
test('sin riesgo alto ni atención devuelve null y no renderiza fila de alerta', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Lucas', status: 'ok', absences: 0 },
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBeNull()
const markup = renderToStaticMarkup(
createElement(GroupCard, {
name: 'Yoga Tranquilo',
capacity: 10,
members,
}),
)
expect(markup).not.toContain('text-[#8B1A1A]')
test('sin cupo definido y sin alertas no hay estado', () => {
expect(groupStatus(miembros(3), null)).toBeNull()
})
})
describe('capacityCounts', () => {
test('los lugares libres son los que faltan del cupo', () => {
expect(capacityCounts(grupo(4, 5), undefined).libres).toBe(1)
expect(capacityCounts(grupo(12, 20), undefined).libres).toBe(8)
describe('groupsSummary', () => {
test('suma grupos, alumnos y lugares libres', () => {
expect(
groupsSummary([
{ attendeesCount: 1, capacity: 4 },
{ attendeesCount: 1, capacity: 5 },
{ attendeesCount: 30, capacity: 30 },
{ attendeesCount: 5, capacity: 5 },
]),
).toBe('4 grupos · 37 alumnos · 7 lugares libres')
})
test('lleno o de más da 0 libres, nunca negativos', () => {
expect(capacityCounts(grupo(5, 5), undefined).libres).toBe(0)
expect(capacityCounts(grupo(7, 5), undefined).libres).toBe(0)
})
test('sin cupo definido no hay lugares que repartir', () => {
expect(capacityCounts(grupo(3, null), undefined).libres).toBe(0)
})
test('ok es la diferencia: el resumen solo nombra a los que hay que mirar', () => {
const counts = capacityCounts(grupo(10, 20), risk(2, 3))
expect(counts).toEqual({ riesgoAlto: 2, atencion: 3, ok: 5, libres: 10 })
})
test('sin resumen, todo el grupo queda en calma y la barra se puede pintar', () => {
expect(capacityCounts(grupo(4, 5), undefined)).toEqual({
riesgoAlto: 0,
atencion: 0,
ok: 4,
libres: 1,
})
})
test('ok no se vuelve negativo si el resumen contara más gente que la matrícula', () => {
expect(capacityCounts(grupo(2, 5), risk(3, 1)).ok).toBe(0)
test('singular y grupos sin cupo o sobrecargados', () => {
expect(groupsSummary([{ attendeesCount: 1, capacity: 2 }])).toBe('1 grupo · 1 alumno · 1 lugar libre')
expect(
groupsSummary([
{ attendeesCount: 3, capacity: null },
{ attendeesCount: 6, capacity: 5 },
]),
).toBe('2 grupos · 9 alumnos · 0 lugares libres')
})
})
describe('isSegmentedCapacity', () => {
test('hasta 10 lugares va un segmento por lugar', () => {
expect(isSegmentedCapacity(4)).toBe(true)
expect(isSegmentedCapacity(5)).toBe(true)
expect(isSegmentedCapacity(6)).toBe(true)
// 7-10 también: aunque la píldora queda angosta, ver qué lugar está libre
// informa más que una barra proporcional.
expect(isSegmentedCapacity(7)).toBe(true)
expect(isSegmentedCapacity(10)).toBe(true)
})
test('de 11 para arriba pasa a bloques proporcionales', () => {
expect(isSegmentedCapacity(11)).toBe(false)
expect(isSegmentedCapacity(30)).toBe(false)
expect(isSegmentedCapacity(100)).toBe(false)
})
test('sin matrícula ni cupo no hay nada que repartir', () => {
expect(isSegmentedCapacity(0)).toBe(false)
})
})
describe('barCapacity', () => {
test('con cupo declarado, el indicador mide los lugares del cupo', () => {
expect(barCapacity(grupo(4, 5))).toBe(5)
expect(barCapacity(grupo(0, 30))).toBe(30)
})
test('sin cupo, el indicador mide a la matrícula en vez de desaparecer', () => {
expect(barCapacity(grupo(4, null))).toBe(4)
expect(barCapacity(grupo(30, null))).toBe(30)
})
test('un grupo sin cupo y sin gente no inventa un total', () => {
expect(barCapacity(grupo(0, null))).toBe(0)
expect(isSegmentedCapacity(barCapacity(grupo(0, null)))).toBe(false)
})
})
describe('riskTone', () => {
test('manda el peor nivel presente', () => {
expect(riskTone({ riesgoAlto: 1, atencion: 4, ok: 0, libres: 0 })).toBe('riesgo_alto')
expect(riskTone({ riesgoAlto: 0, atencion: 1, ok: 0, libres: 0 })).toBe('atencion')
expect(riskTone({ riesgoAlto: 0, atencion: 0, ok: 9, libres: 0 })).toBe('ok')
})
})
describe('statusLine', () => {
test('grupo chico: nombra al caso más urgente y resume los demás', () => {
const resumen = risk(1, 1, {
urgentes: [
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
urgente({
attendeeId: 'at_2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 2,
}),
],
})
expect(statusLine(grupo(4, 5), resumen)).toEqual({
text: 'Sofía: 4 faltas · 1 en atención',
tone: 'riesgo_alto',
})
})
test('con tres personas en riesgo alto resume el total aunque el grupo sea chico', () => {
const resumen = risk(3, 0, {
urgentes: [
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
urgente({ attendeeId: 'at_2', fullName: 'Diego Soto', consecutiveAbsences: 3 }),
urgente({ attendeeId: 'at_3', fullName: 'Ana Ruiz', consecutiveAbsences: 3 }),
],
})
expect(statusLine(grupo(4, 5), resumen).text).toBe('3 en riesgo alto')
})
test('grupo grande: el conteo por nivel en vez de nombres', () => {
const resumen = risk(3, 4, { urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })] })
expect(statusLine(grupo(18, 20), resumen)).toEqual({
text: '3 en riesgo alto · 4 en atención',
tone: 'riesgo_alto',
})
})
test('con exactamente una persona en riesgo alto la nombra, sin importar el cupo', () => {
const resumen = risk(1, 2, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(12, 15), resumen).text).toBe('Sofía: 4 faltas · 2 en atención')
})
test('con dos personas en riesgo alto resume por cantidad', () => {
const resumen = risk(2, 3, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(12, 15), resumen).text).toBe('2 en riesgo alto · 3 en atención')
})
test('el singular se corrige solo', () => {
expect(statusLine(grupo(18, 20), risk(1, 0)).text).toBe('1 en riesgo alto')
})
test('un grupo chico sin cupo también nombra a la gente', () => {
// Sin cupo la barra mide a la matrícula, así que 4 miembros dan 4 segmentos
// y la línea puede usar nombres igual que un grupo con cupo chico.
const resumen = risk(1, 0, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(4, null), resumen)).toEqual({
text: 'Sofía: 4 faltas',
tone: 'riesgo_alto',
})
})
test('un grupo grande sin cupo cae al conteo', () => {
const resumen = risk(3, 4, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(18, null), resumen).text).toBe('3 en riesgo alto · 4 en atención')
})
test('el motivo más útil va primero: las faltas, después el tiempo, después la asistencia', () => {
const resumen = risk(2, 1, {
urgentes: [
urgente({ consecutiveAbsences: 2, daysSinceLastAttendance: 30, attendanceRate: 40 }),
urgente({
attendeeId: 'at_2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 14,
attendanceRate: 60,
}),
urgente({
attendeeId: 'at_3',
fullName: 'Ana Ruiz',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 0,
attendanceRate: 55,
}),
],
})
expect(statusLine(grupo(4, 5), resumen).text).toBe('2 en riesgo alto · 1 en atención')
})
test('sin riesgo la línea se apaga con la asistencia', () => {
const resumen = risk(0, 0, { asistencia: 94 })
expect(statusLine(grupo(18, 20), resumen)).toEqual({ text: 'Asistencia 94%', tone: 'ok' })
})
test('un grupo sin clases registradas no muestra un 100% inventado', () => {
expect(statusLine(grupo(4, 5), risk(0, 0, { asistencia: null })).text).toBe('Sin clases registradas')
// Todavía sin resumen: la tarjeta tiene que poder pintar igual.
expect(statusLine(grupo(4, 5), undefined).text).toBe('Sin clases registradas')
})
test('si el resumen no trajo a quién nombrar, el grupo chico cae al conteo', () => {
// Los urgentes vienen truncados a 5: si hay más gente en riesgo que eso,
// la línea no puede quedarse en blanco.
expect(statusLine(grupo(4, 5), risk(2, 0, { urgentes: [] })).text).toBe('2 en riesgo alto')
})
})
describe('occupancyLabel', () => {
test('con cupo muestra el uso sobre el total', () => {
expect(occupancyLabel(grupo(4, 5))).toBe('4/5 miembros')
expect(occupancyLabel(grupo(12, 20))).toBe('12/20 miembros')
})
test('1/5 se lee en plural: la unidad es el lugar, no la persona', () => {
expect(occupancyLabel(grupo(1, 5))).toBe('1/5 miembros')
})
test('sin cupo el texto es el conteo, y el singular se corrige', () => {
expect(occupancyLabel(grupo(3, null))).toBe('3 miembros')
expect(occupancyLabel(grupo(1, null))).toBe('1 miembro')
expect(occupancyLabel(grupo(0, null))).toBe('0 miembros')
})
test('un grupo vacío con cupo se lee como cualquier otro', () => {
expect(occupancyLabel(grupo(0, 5))).toBe('0/5 miembros')
})
})
describe('capacitySegmentWidth', () => {
test('calcula cada segmento sobre el cupo y conserva el espacio libre', () => {
expect(capacitySegmentWidth(2, 15)).toBe('13.3333%')
expect(capacitySegmentWidth(3, 15)).toBe('20.0000%')
expect(capacitySegmentWidth(7, 15)).toBe('46.6667%')
})
})
describe('capacityIndicatorLabel', () => {
test('el aria-label repite toda la información de la barra', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 2, atencion: 2, ok: 0, libres: 1 }, 5)).toBe(
'4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención, 1 libre',
)
})
test('omite los niveles que están en cero y el plural de libre', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 0, ok: 3, libres: 1 }, 5)).toBe(
'4 de 5 lugares ocupados: 1 en riesgo alto, 3 en ok, 1 libre',
)
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 5, libres: 0 }, 5)).toBe(
'5 de 5 lugares ocupados: 5 en ok',
)
})
test('un grupo vacío se anuncia sin niveles, no como un error', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 10 }, 10)).toBe(
'0 de 10 lugares ocupados, 10 libres',
)
})
test('sin cupo declarado se anuncia por miembros, no por lugares inventados', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 2, ok: 1, libres: 0 }, 4, false)).toBe(
'4 miembros: 1 en riesgo alto, 2 en atención, 1 en ok',
)
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 1, libres: 0 }, 1, false)).toBe(
'1 miembro: 1 en ok',
)
})
test('membersOf busca el grupo en el resumen de atención', () => {
const groups = [{ groupId: 'g1', groupName: 'Yoga', capacity: 4, members: miembros(2) }]
expect(membersOf(groups, 'g1')).toHaveLength(2)
expect(membersOf(groups, 'g2')).toBeUndefined()
expect(membersOf(undefined, 'g1')).toBeUndefined()
})

View File

@@ -11,6 +11,11 @@ describe('isImmersiveRoute', () => {
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
})
test('"Requiere atención" arma su propia barra', () => {
expect(isImmersiveRoute('/groups/attention')).toBe(true)
expect(isImmersiveRoute('/groups/attention/analytics')).toBe(false)
})
test('el detalle de miembro también es immersive', () => {
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(true)
})