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:
167
apps/web/test/attention.test.ts
Normal file
167
apps/web/test/attention.test.ts
Normal 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<')
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user