From b99bc4d5199b825d41f0341dbe5233f402cc5e7a Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 27 Oct 2026 16:35:07 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20redise=C3=B1o=20de=20Grupos=20y=20panta?= =?UTF-8?q?lla=20"Requiere=20atenci=C3=B3n"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- AGENTS.md | 5 +- .../migration.sql | 20 + apps/backend/prisma/models/domain.prisma | 23 + apps/backend/src/app.ts | 2 + .../analytics/lib/member-attendance.ts | 2 +- .../attention/features/get-overview/route.ts | 19 + .../features/get-overview/use-case.ts | 174 +++++ .../attention/features/resolve/route.ts | 23 + .../attention/features/resolve/use-case.ts | 49 ++ apps/backend/src/modules/attention/index.ts | 1 + .../src/modules/attention/lib/alert-kind.ts | 13 + apps/backend/src/modules/attention/routes.ts | 10 + .../test/analytics-groups-risk.test.ts | 31 +- apps/backend/test/attendance-risk.test.ts | 110 +--- apps/backend/test/attention.test.ts | 130 ++++ apps/backend/test/student-alerts.test.ts | 193 ++++++ apps/web/src/components/ui/toast.tsx | 2 +- apps/web/src/features/attention/AlertTag.tsx | 21 + .../src/features/attention/AttentionCard.tsx | 80 +++ .../features/attention/AttentionHeader.tsx | 41 ++ .../features/attention/AttentionProvider.tsx | 82 +++ .../features/attention/AttentionSection.tsx | 45 ++ .../src/features/attention/AttentionView.tsx | 48 ++ .../src/features/attention/EmptyAttention.tsx | 15 + .../src/features/attention/FilterChips.tsx | 37 ++ .../src/features/attention/SeverityAvatar.tsx | 60 ++ apps/web/src/features/attention/attention.ts | 135 ++++ apps/web/src/features/attention/queries.ts | 8 + .../groups/AttendanceCapacityIndicator.tsx | 206 ------ .../src/features/groups/AttentionPreview.tsx | 62 ++ apps/web/src/features/groups/AvatarRow.tsx | 54 ++ apps/web/src/features/groups/GroupCard.tsx | 135 ++-- apps/web/src/features/groups/GroupsView.tsx | 132 ++-- apps/web/src/features/groups/NewGroupFab.tsx | 31 + apps/web/src/features/groups/card.ts | 413 +++--------- apps/web/src/hooks/useCollapseOnScroll.ts | 41 ++ apps/web/src/index.css | 32 + apps/web/src/lib/api.ts | 10 + apps/web/src/lib/immersive-routes.ts | 6 +- apps/web/src/routeTree.gen.ts | 22 + .../_authenticated/groups/attention.tsx | 11 + apps/web/test/attention.test.ts | 167 +++++ apps/web/test/group-card.test.ts | 613 +++--------------- apps/web/test/immersive-routes.test.ts | 5 + packages/shared/src/index.ts | 2 + packages/shared/src/lib/attendance-risk.ts | 125 ++-- packages/shared/src/lib/student-alerts.ts | 194 ++++++ packages/shared/src/schemas/attention.ts | 72 ++ 48 files changed, 2333 insertions(+), 1379 deletions(-) create mode 100644 apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql create mode 100644 apps/backend/src/modules/attention/features/get-overview/route.ts create mode 100644 apps/backend/src/modules/attention/features/get-overview/use-case.ts create mode 100644 apps/backend/src/modules/attention/features/resolve/route.ts create mode 100644 apps/backend/src/modules/attention/features/resolve/use-case.ts create mode 100644 apps/backend/src/modules/attention/index.ts create mode 100644 apps/backend/src/modules/attention/lib/alert-kind.ts create mode 100644 apps/backend/src/modules/attention/routes.ts create mode 100644 apps/backend/test/attention.test.ts create mode 100644 apps/backend/test/student-alerts.test.ts create mode 100644 apps/web/src/features/attention/AlertTag.tsx create mode 100644 apps/web/src/features/attention/AttentionCard.tsx create mode 100644 apps/web/src/features/attention/AttentionHeader.tsx create mode 100644 apps/web/src/features/attention/AttentionProvider.tsx create mode 100644 apps/web/src/features/attention/AttentionSection.tsx create mode 100644 apps/web/src/features/attention/AttentionView.tsx create mode 100644 apps/web/src/features/attention/EmptyAttention.tsx create mode 100644 apps/web/src/features/attention/FilterChips.tsx create mode 100644 apps/web/src/features/attention/SeverityAvatar.tsx create mode 100644 apps/web/src/features/attention/attention.ts create mode 100644 apps/web/src/features/attention/queries.ts delete mode 100644 apps/web/src/features/groups/AttendanceCapacityIndicator.tsx create mode 100644 apps/web/src/features/groups/AttentionPreview.tsx create mode 100644 apps/web/src/features/groups/AvatarRow.tsx create mode 100644 apps/web/src/features/groups/NewGroupFab.tsx create mode 100644 apps/web/src/hooks/useCollapseOnScroll.ts create mode 100644 apps/web/src/routes/_authenticated/groups/attention.tsx create mode 100644 apps/web/test/attention.test.ts create mode 100644 packages/shared/src/lib/student-alerts.ts create mode 100644 packages/shared/src/schemas/attention.ts diff --git a/AGENTS.md b/AGENTS.md index 45f6649..450f840 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/logger.ts` — pino + pino-pretty. - - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. + - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla. - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). @@ -74,13 +74,14 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`). - **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con ``). - **Vistas en `apps/web/src/features//`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use()` y las forms locales mantienen su propio estado. +- **Grupos y "Requiere atención"** comparten la query `['attention']` (`features/attention/queries.ts`): el "Resuelto" es optimista sobre ese caché y por eso los contadores de Grupos se mueven sin refetch. El "Nuevo grupo" de Grupos es un FAB (`NewGroupFab`, se pliega al scrollear con `useCollapseOnScroll`) y por eso los toasts en mobile van a `bottom-[calc(9rem+…)]`. Los colores de gravedad son tokens (`alert-urgent-*`, `alert-watch-*`, `free-fg`) definidos para claro y oscuro en `index.css`. - Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista. - **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `
`, `
` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `
`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar ``; nada más. En las tres pantallas el `

` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos. - **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos. - **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición. - Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`. - **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `
` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa. -- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen. +- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). **Excepción**: `/groups/attention` ("Requiere atención", sin entrada en el nav) muestra su botón Volver también en mobile. Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen. ## Fuentes de contexto diff --git a/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql new file mode 100644 index 0000000..cd6de18 --- /dev/null +++ b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql @@ -0,0 +1,20 @@ +-- CreateEnum +CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT'); + +-- CreateTable +CREATE TABLE "attendee_alert_resolutions" ( + "id" TEXT NOT NULL, + "attendee_id" TEXT NOT NULL, + "kind" "StudentAlertKind" NOT NULL, + "signature" TEXT NOT NULL, + "resolved_by_id" TEXT NOT NULL, + "resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind"); + +-- AddForeignKey +ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index beafc79..0823e24 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -90,11 +90,34 @@ model Attendee { attendances Attendance[] slotReleases SlotRelease[] outboundMessages OutboundMessage[] + alertResolutions AttendeeAlertResolution[] @@index([groupId], map: "attendees_groupId_idx") @@map("attendees") } +enum StudentAlertKind { + ATTENDANCE + PAYMENT +} + +// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind: +// it hides the alert while its signature (last absence / overdue fees) stays +// the same, so a new absence or a new overdue fee brings it back on its own. +model AttendeeAlertResolution { + id String @id @default(cuid()) + attendeeId String @map("attendee_id") + kind StudentAlertKind + signature String + resolvedById String @map("resolved_by_id") + resolvedAt DateTime @default(now()) @map("resolved_at") + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + + @@unique([attendeeId, kind]) + @@map("attendee_alert_resolutions") +} + model Payment { id String @id @default(cuid()) groupId String @map("group_id") diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index ad11aed..a71cf9c 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -16,6 +16,7 @@ import { studentStatusRoutes, } from './modules/analytics'; import { attendeesRoutes } from './modules/attendees'; +import { attentionRoutes } from './modules/attention'; import { authRoutes } from './modules/auth'; import { billingRoutes, planReadOnlyMiddleware } from './modules/billing'; import { classesRoutes } from './modules/classes'; @@ -65,6 +66,7 @@ api.route('/waitlist', waitlistRoutes); api.route('/classes', classesRoutes); api.route('/students', studentStatusRoutes); api.route('/groups-risk', groupsRiskOverviewRoute); +api.route('/attention', attentionRoutes); app.notFound((c) => { return problemJson(c, notFoundProblem(c.req.path)); diff --git a/apps/backend/src/modules/analytics/lib/member-attendance.ts b/apps/backend/src/modules/analytics/lib/member-attendance.ts index 3eb46eb..cc3cd65 100644 --- a/apps/backend/src/modules/analytics/lib/member-attendance.ts +++ b/apps/backend/src/modules/analytics/lib/member-attendance.ts @@ -3,7 +3,7 @@ import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberCla /* How many classes we look back per attendee. That is the real ceiling of the model: `class_sessions` are not created on their own, they get materialized when someone opens "today's classes", so pulling years of rows makes no - sense. 20 classes is enough for the streak, for the 4+4 trend window and for + sense. 20 classes is enough for the streak, for the 6-class window and for the attendance rate the card shows. */ export const MEMBER_HISTORY_LIMIT = 20; diff --git a/apps/backend/src/modules/attention/features/get-overview/route.ts b/apps/backend/src/modules/attention/features/get-overview/route.ts new file mode 100644 index 0000000..1d981ce --- /dev/null +++ b/apps/backend/src/modules/attention/features/get-overview/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttentionOverview } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const useCase = new GetAttentionOverview(); + const result = await useCase.execute(user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attention/features/get-overview/use-case.ts b/apps/backend/src/modules/attention/features/get-overview/use-case.ts new file mode 100644 index 0000000..fe4cb28 --- /dev/null +++ b/apps/backend/src/modules/attention/features/get-overview/use-case.ts @@ -0,0 +1,174 @@ +import type { Prisma } from '@generated/prisma/client'; +import type { + AttendanceStatus, + AttentionGroup, + AttentionMember, + AttentionOverview, + ProblemDetails, + Result, + StudentAlertType, +} from '@gruperly/shared'; +import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; + +type GetAttentionOverviewDeps = { + db?: { + group: Prisma.GroupDelegate; + attendee: Prisma.AttendeeDelegate; + classSession: Prisma.ClassSessionDelegate; + attendance: Prisma.AttendanceDelegate; + payment: Prisma.PaymentDelegate; + attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate; + user: Prisma.UserDelegate; + }; + now?: Date; +}; + +type GroupRow = { id: string; name: string; capacity: number | null }; +type AttendeeRow = { + id: string; + groupId: string; + fullName: string; + phone: string | null; + guardianPhone: string | null; + createdAt: Date; +}; +type SessionRow = { id: string; groupId: string; startsAt: Date }; +type AttendanceRow = { + attendeeId: string; + classSessionId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; +type PaymentRow = { + id: string; + attendeeId: string; + amount: Prisma.Decimal; + currency: string; + dueDate: Date; + checkoutUrl: string | null; +}; +type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string }; + +/* Every ACTIVE member of the user's groups with their alerts ("Requiere + atención"). The list screen draws all the avatars from here, so it returns + members without alerts too. The rule is `computeStudentAlerts` (shared) over + the same attendance input the risk overview builds (`toMemberAttendance`). */ +export class GetAttentionOverview { + constructor(private readonly deps: GetAttentionOverviewDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + + const groups = (await db.group.findMany({ + where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, + select: { id: true, name: true, capacity: true }, + orderBy: { createdAt: 'asc' }, + })) as GroupRow[]; + + if (groups.length === 0) { + return ok({ groups: [] }); + } + + const groupIds = groups.map((group) => group.id); + + const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([ + // Phones are stored the way people write them (`11 2345-6789`): the + // professor's country settles the calling code, as in the WhatsApp jobs. + db.user.findUnique({ where: { id: userId }, select: { country: true } }), + db.attendee.findMany({ + where: { groupId: { in: groupIds }, status: 'ACTIVE' }, + select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true }, + orderBy: { createdAt: 'asc' }, + }) as Promise, + // Past classes only, most recent first: `toMemberAttendance` keeps the + // last 20 per attendee, more than the 6-class window needs. + db.classSession.findMany({ + where: { groupId: { in: groupIds }, startsAt: { lte: now } }, + select: { id: true, groupId: true, startsAt: true }, + orderBy: { startsAt: 'desc' }, + }) as Promise, + db.attendance.findMany({ + where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } }, + select: { + attendeeId: true, + classSessionId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + }) as Promise, + db.payment.findMany({ + where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' } }, + select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true }, + orderBy: { dueDate: 'asc' }, + }) as Promise, + db.attendeeAlertResolution.findMany({ + where: { attendee: { groupId: { in: groupIds } } }, + select: { attendeeId: true, kind: true, signature: true }, + }) as Promise, + ]); + + const country = countryCodeSchema.safeParse(owner?.country); + const sessionsByGroup = groupBy(sessions, (session) => session.groupId); + const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId); + const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId); + const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId); + const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId); + + const items: AttentionGroup[] = groups.map((group) => ({ + groupId: group.id, + groupName: group.name, + capacity: group.capacity, + members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => { + const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({ + id: payment.id, + amount: Number(payment.amount), + currency: payment.currency, + dueDate: payment.dueDate.toISOString(), + checkoutUrl: payment.checkoutUrl, + })); + const alerts = computeStudentAlerts( + { + attendance: toMemberAttendance( + attendee, + sessionsByGroup.get(group.id) ?? [], + attendanceByAttendee.get(attendee.id) ?? [], + ), + overduePayments, + }, + now, + ); + const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({ + tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType, + firma: row.signature, + })); + + const phone = attendee.phone ?? attendee.guardianPhone; + return { + attendeeId: attendee.id, + fullName: attendee.fullName, + phone, + whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null, + alerts: applyResolutions(alerts, resolved), + overduePayments, + }; + }), + })); + + return ok({ groups: items }); + } +} + +function groupBy(rows: T[], key: (row: T) => string): Map { + const map = new Map(); + for (const row of rows) { + const list = map.get(key(row)) ?? []; + list.push(row); + map.set(key(row), list); + } + return map; +} diff --git a/apps/backend/src/modules/attention/features/resolve/route.ts b/apps/backend/src/modules/attention/features/resolve/route.ts new file mode 100644 index 0000000..62ed14e --- /dev/null +++ b/apps/backend/src/modules/attention/features/resolve/route.ts @@ -0,0 +1,23 @@ +import type { ResolveAlert } from '@gruperly/shared'; +import { ResolveAlertSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ResolveStudentAlert } from './use-case'; + +const route = new Hono(); + +route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const payload = c.req.valid('json') as ResolveAlert; + const useCase = new ResolveStudentAlert(); + const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attention/features/resolve/use-case.ts b/apps/backend/src/modules/attention/features/resolve/use-case.ts new file mode 100644 index 0000000..fce1418 --- /dev/null +++ b/apps/backend/src/modules/attention/features/resolve/use-case.ts @@ -0,0 +1,49 @@ +import type { Prisma } from '@generated/prisma/client'; +import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind'; + +type ResolveAlertDeps = { + db?: { + attendee: Prisma.AttendeeDelegate; + attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate; + }; +}; + +export type ResolveAlertResult = ResolveAlert & { attendeeId: string }; + +/* "Resuelto": stores the signature of the alert the professor saw. One row per + attendee and type, overwritten on each resolve, so the table never grows past + two rows per attendee. An attendee outside the user's groups is a 404, not a + 403: we don't confirm that the id exists. */ +export class ResolveStudentAlert { + constructor(private readonly deps: ResolveAlertDeps = {}) {} + + async execute( + attendeeId: string, + userId: string, + payload: ResolveAlert, + ): Promise> { + const db = this.deps.db ?? prisma; + + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput }, + select: { id: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const kind = ALERT_TYPE_TO_KIND[payload.tipo]; + await db.attendeeAlertResolution.upsert({ + where: { attendeeId_kind: { attendeeId, kind } }, + create: { attendeeId, kind, signature: payload.firma, resolvedById: userId }, + update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() }, + }); + + return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma }); + } +} diff --git a/apps/backend/src/modules/attention/index.ts b/apps/backend/src/modules/attention/index.ts new file mode 100644 index 0000000..b7196c4 --- /dev/null +++ b/apps/backend/src/modules/attention/index.ts @@ -0,0 +1 @@ +export { default as attentionRoutes } from './routes'; diff --git a/apps/backend/src/modules/attention/lib/alert-kind.ts b/apps/backend/src/modules/attention/lib/alert-kind.ts new file mode 100644 index 0000000..777e155 --- /dev/null +++ b/apps/backend/src/modules/attention/lib/alert-kind.ts @@ -0,0 +1,13 @@ +import type { StudentAlertKind } from '@generated/prisma/client'; +import type { StudentAlertType } from '@gruperly/shared'; + +/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */ +export const ALERT_KIND_TO_TYPE: Record = { + ATTENDANCE: 'asistencia', + PAYMENT: 'pago', +}; + +export const ALERT_TYPE_TO_KIND: Record = { + asistencia: 'ATTENDANCE', + pago: 'PAYMENT', +}; diff --git a/apps/backend/src/modules/attention/routes.ts b/apps/backend/src/modules/attention/routes.ts new file mode 100644 index 0000000..ba1c069 --- /dev/null +++ b/apps/backend/src/modules/attention/routes.ts @@ -0,0 +1,10 @@ +import { Hono } from 'hono'; +import getOverviewRoute from './features/get-overview/route'; +import resolveRoute from './features/resolve/route'; + +const routes = new Hono(); + +routes.route('/', getOverviewRoute); +routes.route('/', resolveRoute); + +export default routes; diff --git a/apps/backend/test/analytics-groups-risk.test.ts b/apps/backend/test/analytics-groups-risk.test.ts index ecf7b04..99537d1 100644 --- a/apps/backend/test/analytics-groups-risk.test.ts +++ b/apps/backend/test/analytics-groups-risk.test.ts @@ -100,7 +100,7 @@ describe('GET /groups-risk/overview', () => { }); }); - it('cuenta el motivo: faltas seguidas o inactividad, sin repetir alumnos', async () => { + it('cuenta el motivo: faltas seguidas o faltas sueltas, sin repetir alumnos', async () => { prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]); prismaFetchAttendeeFindMany([ attendee('a-1', 'group-1'), @@ -122,10 +122,13 @@ describe('GET /groups-risk/overview', () => { attendance('a-1', 's1', 'ABSENT', at(1)), attendance('a-1', 's2', 'ABSENT', at(2)), attendance('a-1', 's3', 'PRESENT', at(3)), - // A single absence, but 14 days between their last presence and the - // class they missed (the ones in between have no record): inactivity. + // No streak (they came to s2), but 4 of their last 5 classes missed: + // high risk through the window, not through the streak. attendance('a-2', 's1', 'ABSENT', at(1)), - attendance('a-2', 's7', 'PRESENT', at(15)), + attendance('a-2', 's2', 'PRESENT', at(2)), + attendance('a-2', 's3', 'ABSENT', at(3)), + attendance('a-2', 's4', 'ABSENT', at(4)), + attendance('a-2', 's7', 'ABSENT', at(15)), // Ok. attendance('a-3', 's1', 'PRESENT', at(1)), attendance('a-3', 's2', 'PRESENT', at(2)), @@ -268,8 +271,9 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () => { id: 's3', groupId: 'group-1', startsAt: at(3) }, ]); // Absence, unmarked class, absence. Reading only the `Attendance` rows this - // would look like a streak of 2 and the group would land in attention; the - // middle class happened and has no record, so the real streak is 1. + // would look like a streak of 2; the middle class happened and has no + // record, so the real streak is 1. The level is still attention, but because + // of the short window (2 absences in the last marked classes), not the streak. prismaFetchAttendanceFindMany([ attendance('a-1', 's1', 'ABSENT', at(1)), attendance('a-1', 's3', 'ABSENT', at(3)), @@ -280,13 +284,13 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () => expect(res.status).toBe(200); const { items } = (await res.json()) as { items: Record[] }; expect(items[0].riesgoAlto).toBe(0); - expect(items[0].atencion).toBe(0); - expect(items[0].ok).toBe(1); + expect(items[0].atencion).toBe(1); + expect(items[0].absenceStreakCount).toBe(0); expect(items[0].urgentes).toEqual([ { attendeeId: 'a-1', fullName: 'Sofía Díaz', - level: 'ok', + level: 'atencion', consecutiveAbsences: 1, daysSinceLastAttendance: 1, // Both marked classes were absences; the middle one does not go into the average. @@ -340,7 +344,8 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast // recent class (s1) is the one with no record. Since the streak is counted // from the end and "no record" is not an absence, there is no streak: the // asymmetry is there on purpose, because it is the same thing that already - // happens with an excused class. + // happens with an excused class. The two absences still fill the short + // window, so the level is attention without a streak. prismaFetchAttendanceFindMany([ attendance('a-1', 's2', 'ABSENT', at(2)), attendance('a-1', 's3', 'ABSENT', at(3)), @@ -350,14 +355,14 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast expect(res.status).toBe(200); const { items } = (await res.json()) as { items: Record[] }; - expect(items[0].atencion).toBe(0); + expect(items[0].atencion).toBe(1); expect(items[0].riesgoAlto).toBe(0); - expect(items[0].ok).toBe(1); + expect(items[0].absenceStreakCount).toBe(0); expect(items[0].urgentes).toEqual([ { attendeeId: 'a-1', fullName: 'Sofía Díaz', - level: 'ok', + level: 'atencion', consecutiveAbsences: 0, daysSinceLastAttendance: 1, attendanceRate: 0, diff --git a/apps/backend/test/attendance-risk.test.ts b/apps/backend/test/attendance-risk.test.ts index 5710fb0..efa2d52 100644 --- a/apps/backend/test/attendance-risk.test.ts +++ b/apps/backend/test/attendance-risk.test.ts @@ -14,9 +14,7 @@ import { Two test-scaffold helpers: - - `dense` puts the classes on consecutive days, so that "how long since we - saw them" is always close by and the case isolates the rule it claims to - test (one class a week would trip the inactivity threshold almost always). + - `dense` puts the classes on consecutive days. - `series` honors the offsets it is given, for the cases that do need gaps. All dates hang off a fixed `NOW`: the function takes the moment as an @@ -98,83 +96,46 @@ describe('getMemberAttendanceRisk', () => { expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok'); }); - it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => { - // A single absence, the most recent one: the streak doesn't reach. What drives - // the level is the time since they last showed up. - const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]])); + it('4 faltas en las últimas 6 clases dan riesgo alto aunque no haya racha', () => { + const { highWindowAbsences, highWindowSize } = ATTENDANCE_RISK_RULES; + const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT'])); const señales = summarizeMemberAttendance(alumno, NOW); - expect(señales.consecutiveAbsences).toBe(1); - expect(señales.daysSinceLastAttendance).toBe(30); + expect(señales.consecutiveAbsences).toBe(0); + expect(señales.highWindow).toEqual({ absences: highWindowAbsences, classes: highWindowSize }); expect(señales.level).toBe('riesgo_alto'); }); - it('sin faltas después de la última presencia, la inactividad no cuenta', () => { - // The group stopped recording classes (or didn't meet): 30 days since the - // last presence, but the attendee missed nothing. + it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => { + const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + const señales = summarizeMemberAttendance(alumno, NOW); + expect(señales.highWindow.absences).toBe(3); + expect(señales.attentionWindow).toEqual({ absences: 2, classes: 4 }); + expect(señales.level).toBe('atencion'); + }); + + it('2 faltas en las últimas 4 clases dan atención', () => { + const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion'); + }); + + it('una sola falta reciente no alcanza', () => { + const alumno = member(dense(['ABSENT', 'ABSENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT'])); + // The two old absences fall outside the short window (last 4). + expect(summarizeMemberAttendance(alumno, NOW).attentionWindow.absences).toBe(1); + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok'); + }); + + it('los días sin venir se informan pero no mueven el nivel', () => { + // The group stopped recording classes: 30 days since the last presence, + // but the attendee missed nothing. const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]])); const señales = summarizeMemberAttendance(alumno, NOW); - expect(señales.consecutiveAbsences).toBe(0); expect(señales.daysSinceLastAttendance).toBe(30); expect(señales.level).toBe('ok'); }); - it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => { - const { highInactivityDays } = ATTENDANCE_RISK_RULES; - // Two streak absences, the latest one yesterday: attention comes from the - // streak. Inactivity is measured from the last presence to the latest - // missed class, so exactly 10 days there does not move the level. - expect( - getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW), - ).toBe('atencion'); - expect( - getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 2]])), NOW), - ).toBe('riesgo_alto'); - }); - - it('la inactividad se mide contra las clases que faltó, no contra hoy', () => { - // They missed one class 20 days ago and the group hasn't met since: 25 days - // without seeing them, but only 5 of those had a class they skipped. - const alumno = member(series([['ABSENT', 20], ['PRESENT', 25]])); - const señales = summarizeMemberAttendance(alumno, NOW); - expect(señales.daysSinceLastAttendance).toBe(25); - expect(señales.level).toBe('ok'); - }); - - it('una tendencia a la baja da atención', () => { - // 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the - // most recent is a PRESENT: streak 0 and recent attendance, so the trend is - // the only thing that can raise the alert. - const candidato = member(dense([ - 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', - 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', - ])); - const señales = summarizeMemberAttendance(candidato, NOW); - expect(señales.consecutiveAbsences).toBe(0); - expect(señales.daysSinceLastAttendance).toBe(1); - expect(señales.level).toBe('atencion'); - }); - - it('perder una sola clase no es tendencia', () => { - // Same case as the previous one with one class fewer missed in the recent - // window: 3 of 4 against 4 of 4. That's noise, not a drop-off. - const estable = member(dense([ - 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', - 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', - ])); - expect(getMemberAttendanceRisk(estable, NOW)).toBe('ok'); - }); - - it('la tendencia necesita historia para las dos ventanas', () => { - // 5 marked classes: the previous window would be left with a single one, so - // there is nothing to compare against. - const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])); - expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok'); - }); - - it('la racha manda sobre la tendencia', () => { - // 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back - // absences and one attended class. The trend alone would give attention; - // the 3 trailing absences give high risk, which is what has to win. + it('tres faltas seguidas son riesgo alto con buena historia detrás', () => { + // 16 classes at 81%: the 3 trailing absences are what decides the level. const alumno = member(dense([ 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT', @@ -187,13 +148,13 @@ describe('getMemberAttendanceRisk', () => { it('una clase sin registro corta la racha: sin dato no hay ausencia', () => { // Absent, the middle one has no record, absent again. The real streak - // is one, not two. + // is one, not two; the two absences still fill the short window. const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]])); const señales = summarizeMemberAttendance(conHueco, NOW); expect(señales.consecutiveAbsences).toBe(1); expect(señales.markedClasses).toBe(2); expect(señales.attendanceRate).toBe(0); - expect(señales.level).toBe('ok'); + expect(señales.level).toBe('atencion'); }); it('una clase justificada es la clase que no cuenta', () => { @@ -204,13 +165,14 @@ describe('getMemberAttendanceRisk', () => { expect(señales.consecutiveAbsences).toBe(1); expect(señales.markedClasses).toBe(2); expect(señales.attendanceRate).toBe(0); - expect(señales.level).toBe('ok'); + expect(señales.attentionWindow).toEqual({ absences: 2, classes: 2 }); }); it('avisar de la falta tampoco encadena las de alrededor', () => { const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]])); expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0); - expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok'); + // No streak, but the two absences are still recent: attention, not high. + expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion'); }); it('no le importa el orden en que llegan las clases', () => { diff --git a/apps/backend/test/attention.test.ts b/apps/backend/test/attention.test.ts new file mode 100644 index 0000000..db289fb --- /dev/null +++ b/apps/backend/test/attention.test.ts @@ -0,0 +1,130 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { Prisma } from '@generated/prisma/client'; +import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case'; +import { ResolveStudentAlert } from '@/modules/attention/features/resolve/use-case'; + +const NOW = new Date('2026-10-27T20:00:00.000Z'); +const DAY_MS = 24 * 60 * 60 * 1000; +const at = (days: number) => new Date(NOW.getTime() - days * DAY_MS); + +const db = { + group: { findMany: mock() }, + attendee: { findMany: mock(), findFirst: mock() }, + classSession: { findMany: mock() }, + attendance: { findMany: mock() }, + payment: { findMany: mock() }, + attendeeAlertResolution: { findMany: mock(), upsert: mock() }, + user: { findUnique: mock() }, +}; + +function overview() { + return new GetAttentionOverview({ db: db as never, now: NOW }); +} + +beforeEach(() => { + for (const delegate of Object.values(db)) { + for (const fn of Object.values(delegate)) fn.mockReset(); + } +}); + +describe('GetAttentionOverview', () => { + it('sin grupos no consulta nada más', async () => { + db.group.findMany.mockResolvedValue([]); + const result = await overview().execute('user-1'); + expect(result).toEqual({ ok: true, value: { groups: [] } }); + expect(db.attendee.findMany).not.toHaveBeenCalled(); + }); + + it('devuelve todos los miembros con sus alertas, sin las resueltas', async () => { + db.user.findUnique.mockResolvedValue({ country: 'AR' }); + db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]); + db.attendee.findMany.mockResolvedValue([ + { id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) }, + { id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) }, + { id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) }, + ]); + db.classSession.findMany.mockResolvedValue([ + { id: 's1', groupId: 'g1', startsAt: at(1) }, + { id: 's2', groupId: 'g1', startsAt: at(3) }, + { id: 's3', groupId: 'g1', startsAt: at(5) }, + ]); + const row = (attendeeId: string, sessionId: string, status: string, days: number) => ({ + attendeeId, + classSessionId: sessionId, + status, + classSession: { startsAt: at(days) }, + }); + db.attendance.findMany.mockResolvedValue([ + row('a1', 's1', 'ABSENT', 1), + row('a1', 's2', 'ABSENT', 3), + row('a1', 's3', 'ABSENT', 5), + // Valentina missed two classes, but the professor already resolved it. + row('a2', 's1', 'ABSENT', 1), + row('a2', 's2', 'ABSENT', 3), + row('a3', 's1', 'PRESENT', 1), + ]); + db.payment.findMany.mockResolvedValue([ + { + id: 'p1', + attendeeId: 'a2', + amount: new Prisma.Decimal('15000.00'), + currency: 'ARS', + dueDate: new Date('2026-10-10T12:00:00.000Z'), + checkoutUrl: 'https://mp.test/p1', + }, + ]); + db.attendeeAlertResolution.findMany.mockResolvedValue([ + { attendeeId: 'a2', kind: 'ATTENDANCE', signature: 's1' }, + ]); + + const result = await overview().execute('user-1'); + if (!result.ok) throw new Error('expected ok'); + + const [group] = result.value.groups; + expect(group).toMatchObject({ groupId: 'g1', groupName: 'Natación', capacity: 30 }); + expect(group.members.map((member) => member.attendeeId)).toEqual(['a1', 'a2', 'a3']); + + const [agustina, valentina, felipe] = group.members; + expect(agustina.phone).toBe('1155550000'); + expect(agustina.whatsappPhone).toBe('+5491155550000'); + expect(agustina.alerts).toMatchObject([{ tipo: 'asistencia', gravedad: 'urgente', etiqueta: '3 seguidas' }]); + + expect(valentina.phone).toBe('1166660000'); + expect(valentina.alerts).toMatchObject([{ tipo: 'pago', gravedad: 'vigilar', etiqueta: 'Cuota vencida' }]); + expect(valentina.overduePayments).toEqual([ + { id: 'p1', amount: 15000, currency: 'ARS', dueDate: '2026-10-10T12:00:00.000Z', checkoutUrl: 'https://mp.test/p1' }, + ]); + + expect(felipe.alerts).toEqual([]); + }); +}); + +describe('ResolveStudentAlert', () => { + it('guarda la firma con upsert por alumno y tipo', async () => { + db.attendee.findFirst.mockResolvedValue({ id: 'a1' }); + const result = await new ResolveStudentAlert({ db: db as never }).execute('a1', 'user-1', { + tipo: 'pago', + firma: 'p1,p2', + }); + + expect(result).toEqual({ ok: true, value: { attendeeId: 'a1', tipo: 'pago', firma: 'p1,p2' } }); + expect(db.attendeeAlertResolution.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + where: { attendeeId_kind: { attendeeId: 'a1', kind: 'PAYMENT' } }, + create: expect.objectContaining({ signature: 'p1,p2', resolvedById: 'user-1' }), + }), + ); + }); + + it('un alumno de un grupo ajeno es 404 y no escribe nada', async () => { + db.attendee.findFirst.mockResolvedValue(null); + const result = await new ResolveStudentAlert({ db: db as never }).execute('a9', 'user-1', { + tipo: 'asistencia', + firma: 's1', + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(404); + expect(db.attendeeAlertResolution.upsert).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/student-alerts.test.ts b/apps/backend/test/student-alerts.test.ts new file mode 100644 index 0000000..d3a32ea --- /dev/null +++ b/apps/backend/test/student-alerts.test.ts @@ -0,0 +1,193 @@ +import { describe, expect, it } from 'bun:test'; +import { + applyResolutions, + compareByWorstAlert, + computeStudentAlerts, + type MemberAttendance, + type MemberClassSession, + STUDENT_ALERT_RULES, + type StudentAlert, + worstAlert, +} from '@gruperly/shared'; + +/* The single source of the "Requiere atención" alerts. These tests pin the + thresholds (attendance through the shared risk rule, fees through + `STUDENT_ALERT_RULES`), the copy the screens show and the order. */ + +const DAY_MS = 24 * 60 * 60 * 1000; +const NOW = new Date('2026-10-27T20:00:00.000Z'); +const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString(); + +type Status = MemberClassSession['status']; + +/** Classes on consecutive days, oldest first; the last one is `ses_1`. */ +function attendance(statuses: Status[]): MemberAttendance { + return { + attendeeId: 'at_1', + fullName: 'Agustina Pérez', + enrolledAt: daysAgo(365), + sessions: statuses.map((status, index) => ({ + sessionId: `ses_${statuses.length - index}`, + startsAt: daysAgo(statuses.length - index), + status, + })), + }; +} + +const fee = (id: string, dueDate: string) => ({ id, dueDate }); + +function alertsFor(statuses: Status[], fees: { id: string; dueDate: string }[] = []) { + return computeStudentAlerts({ attendance: attendance(statuses), overduePayments: fees }, NOW); +} + +describe('computeStudentAlerts: asistencia', () => { + it('sin faltas ni cuotas no hay alertas', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT'])).toEqual([]); + }); + + it('3 faltas seguidas son urgentes y lo dicen así', () => { + const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']); + expect(alert).toMatchObject({ + tipo: 'asistencia', + gravedad: 'urgente', + etiqueta: '3 seguidas', + detalle: 'No viene hace 3 clases seguidas.', + firma: 'ses_1', + }); + }); + + it('4 de las últimas 6 sin racha son urgentes', () => { + const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']); + expect(alert).toMatchObject({ + gravedad: 'urgente', + etiqueta: '4 faltas', + detalle: 'Faltó a 4 de las últimas 6 clases.', + firma: 'ses_2', + }); + }); + + it('2 faltas recientes son "a vigilar"', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])[0]).toMatchObject({ + gravedad: 'vigilar', + etiqueta: '2 faltas', + detalle: 'Faltó a las últimas 2 clases.', + }); + expect(alertsFor(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])[0]).toMatchObject({ + gravedad: 'vigilar', + detalle: 'Faltó a 2 de las últimas 4 clases.', + }); + }); + + it('una sola falta no alcanza', () => { + expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])).toEqual([]); + }); + + it('las justificadas y las clases sin registro no cuentan como faltas', () => { + expect(alertsFor(['PRESENT', 'EXCUSED', 'ABSENT', null, 'EXCUSED'])).toEqual([]); + }); +}); + +describe('computeStudentAlerts: pagos', () => { + it('1 cuota vencida es "a vigilar" con su fecha', () => { + expect(alertsFor([], [fee('pay_1', '2026-10-10T12:00:00.000Z')])).toEqual([ + { + tipo: 'pago', + gravedad: 'vigilar', + etiqueta: 'Cuota vencida', + detalle: 'La cuota de octubre venció el 10/10.', + firma: 'pay_1', + peso: 1, + }, + ]); + }); + + it(`${STUDENT_ALERT_RULES.urgentOverdue} o más cuotas vencidas son urgentes y nombran los meses`, () => { + const [alert] = alertsFor( + [], + [fee('pay_b', '2026-10-10T12:00:00.000Z'), fee('pay_a', '2026-09-10T12:00:00.000Z')], + ); + expect(alert).toMatchObject({ + gravedad: 'urgente', + etiqueta: '2 cuotas', + detalle: 'Debe las cuotas de septiembre y octubre.', + firma: 'pay_a,pay_b', + }); + }); + + it('con tres meses los separa con coma y "y"', () => { + const [alert] = alertsFor( + [], + [ + fee('p1', '2026-08-10T12:00:00.000Z'), + fee('p2', '2026-09-10T12:00:00.000Z'), + fee('p3', '2026-10-10T12:00:00.000Z'), + ], + ); + expect(alert.detalle).toBe('Debe las cuotas de agosto, septiembre y octubre.'); + }); + + it('dos cuotas del mismo mes caen al conteo', () => { + const [alert] = alertsFor([], [fee('p1', '2026-10-01T12:00:00.000Z'), fee('p2', '2026-10-20T12:00:00.000Z')]); + expect(alert.detalle).toBe('Debe 2 cuotas vencidas.'); + }); +}); + +describe('orden por gravedad', () => { + it('con varias alertas, la urgente va primero', () => { + const alerts = alertsFor( + ['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'], + [fee('p1', '2026-09-10T12:00:00.000Z'), fee('p2', '2026-10-10T12:00:00.000Z')], + ); + expect(alerts.map((alert) => [alert.tipo, alert.gravedad])).toEqual([ + ['pago', 'urgente'], + ['asistencia', 'vigilar'], + ]); + expect(worstAlert(alerts)?.tipo).toBe('pago'); + }); + + it('ordena alumnos por su peor alerta, después por la fuerza y por nombre', () => { + const alert = (gravedad: StudentAlert['gravedad'], peso: number): StudentAlert => ({ + tipo: 'asistencia', + gravedad, + etiqueta: '', + detalle: '', + firma: 'x', + peso, + }); + const students = [ + { fullName: 'Zoe', alerts: [] }, + { fullName: 'Martina', alerts: [alert('vigilar', 2)] }, + { fullName: 'Tomás', alerts: [alert('urgente', 3)] }, + { fullName: 'Agustina', alerts: [alert('urgente', 4)] }, + { fullName: 'Bruno', alerts: [alert('vigilar', 2)] }, + ]; + expect([...students].sort(compareByWorstAlert).map((student) => student.fullName)).toEqual([ + 'Agustina', + 'Tomás', + 'Bruno', + 'Martina', + 'Zoe', + ]); + }); +}); + +describe('applyResolutions', () => { + const statuses: Status[] = ['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']; + + it('oculta la alerta resuelta mientras la firma sea la misma', () => { + const alerts = alertsFor(statuses); + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }])).toEqual([]); + }); + + it('una falta nueva cambia la firma y la alerta vuelve', () => { + const alerts = alertsFor([...statuses, 'ABSENT']); + expect(alerts[0].firma).toBe('ses_1'); + // The resolution was stored when the last absence was `ses_2`. + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_2' }])).toHaveLength(1); + }); + + it('resolver la asistencia no oculta los pagos', () => { + const alerts = alertsFor(statuses, [fee('p1', '2026-10-10T12:00:00.000Z')]); + expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }]).map((a) => a.tipo)).toEqual(['pago']); + }); +}); diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 8d3e070..c3378f3 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -88,7 +88,7 @@ export function ToastProvider({ children }: { children: ReactNode }) { {/* Toast Container */}
{toasts.map((toast) => (
= { + 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 ( + + {children} + + ) +} diff --git a/apps/web/src/features/attention/AttentionCard.tsx b/apps/web/src/features/attention/AttentionCard.tsx new file mode 100644 index 0000000..6e325e0 --- /dev/null +++ b/apps/web/src/features/attention/AttentionCard.tsx @@ -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 ( +
+
+ +
+ + {student.fullName} + +

{student.groupName}

+
+ {alert.etiqueta} +
+ +

{alert.detalle}

+ +
+ {href ? ( + + {actionLabel} + + ) : ( + + )} + +
+
+ ) +} diff --git a/apps/web/src/features/attention/AttentionHeader.tsx b/apps/web/src/features/attention/AttentionHeader.tsx new file mode 100644 index 0000000..69e1ea2 --- /dev/null +++ b/apps/web/src/features/attention/AttentionHeader.tsx @@ -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 = ( +
+ +
+ ) + + return host ? createPortal(bar, host) : bar +} diff --git a/apps/web/src/features/attention/AttentionProvider.tsx b/apps/web/src/features/attention/AttentionProvider.tsx new file mode 100644 index 0000000..c988e84 --- /dev/null +++ b/apps/web/src/features/attention/AttentionProvider.tsx @@ -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(null) + +export function AttentionProvider({ children }: { children: ReactNode }) { + const queryClient = useQueryClient() + const toast = useToast() + const [filter, setFilter] = useState('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(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 ( + void attentionQuery.refetch(), + filter, + setFilter, + resolve: (attendeeId, alert) => resolveMutation.mutate({ attendeeId, alert }), + }} + > + {children} + + ) +} + +export function useAttention() { + const context = useContext(AttentionContext) + if (!context) throw new Error('useAttention must be used inside AttentionProvider') + return context +} diff --git a/apps/web/src/features/attention/AttentionSection.tsx b/apps/web/src/features/attention/AttentionSection.tsx new file mode 100644 index 0000000..cefebfe --- /dev/null +++ b/apps/web/src/features/attention/AttentionSection.tsx @@ -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 = { + 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 ( +
+

+

+
+ {items.map((item) => ( + onResolve(item)} + /> + ))} +
+
+ ) +} diff --git a/apps/web/src/features/attention/AttentionView.tsx b/apps/web/src/features/attention/AttentionView.tsx new file mode 100644 index 0000000..8a20037 --- /dev/null +++ b/apps/web/src/features/attention/AttentionView.tsx @@ -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 ( +
+ + + {/* The chips stay under the bar (56px) while the cards scroll. */} +
+ +
+ + {isPending ? ( +
+
+ ) : isError ? ( +
+

No pudimos cargar las alertas.

+ +
+ ) : visible.length === 0 ? ( + + ) : ( + <> + + + + )} +
+ ) +} diff --git a/apps/web/src/features/attention/EmptyAttention.tsx b/apps/web/src/features/attention/EmptyAttention.tsx new file mode 100644 index 0000000..f14d1f0 --- /dev/null +++ b/apps/web/src/features/attention/EmptyAttention.tsx @@ -0,0 +1,15 @@ +import { Check } from 'lucide-react' + +export function EmptyAttention() { + return ( +
+ + +

Todo en orden

+

+ No hay alumnos que requieran atención en este filtro. +

+
+ ) +} diff --git a/apps/web/src/features/attention/FilterChips.tsx b/apps/web/src/features/attention/FilterChips.tsx new file mode 100644 index 0000000..ad6938c --- /dev/null +++ b/apps/web/src/features/attention/FilterChips.tsx @@ -0,0 +1,37 @@ +import { cn } from '../../lib/utils' +import { ATTENTION_FILTERS, type AttentionFilter } from './attention' + +type FilterChipsProps = { + value: AttentionFilter + counts: Record + onChange: (filter: AttentionFilter) => void +} + +export function FilterChips({ value, counts, onChange }: FilterChipsProps) { + return ( +
+ {ATTENTION_FILTERS.map((filter) => { + const active = filter.id === value + return ( + + ) + })} +
+ ) +} diff --git a/apps/web/src/features/attention/SeverityAvatar.tsx b/apps/web/src/features/attention/SeverityAvatar.tsx new file mode 100644 index 0000000..7671062 --- /dev/null +++ b/apps/web/src/features/attention/SeverityAvatar.tsx @@ -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 = { + 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 ( +