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:
@@ -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',
|
||||
}
|
||||
62
apps/web/src/features/groups/AttentionPreview.tsx
Normal file
62
apps/web/src/features/groups/AttentionPreview.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
54
apps/web/src/features/groups/AvatarRow.tsx
Normal file
54
apps/web/src/features/groups/AvatarRow.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
31
apps/web/src/features/groups/NewGroupFab.tsx
Normal file
31
apps/web/src/features/groups/NewGroupFab.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
})),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user