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