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