feat/improve-ui #11
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `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`).
|
- `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/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).
|
- `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`).
|
- **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 `<Outlet />`).
|
- **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 `<Outlet />`).
|
||||||
- **Vistas en `apps/web/src/features/<feature>/`**: 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<Feature>()` y las forms locales mantienen su propio estado.
|
- **Vistas en `apps/web/src/features/<feature>/`**: 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<Feature>()` 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.
|
- 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 `<Header />`, `<main>` 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 `<main>`. (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 `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` 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.
|
- **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 `<Header />`, `<main>` 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 `<main>`. (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 `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` 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.
|
- **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.
|
- **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+`.
|
- 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 `<main>` 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.
|
- **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 `<main>` 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
|
## Fuentes de contexto
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -90,11 +90,34 @@ model Attendee {
|
|||||||
attendances Attendance[]
|
attendances Attendance[]
|
||||||
slotReleases SlotRelease[]
|
slotReleases SlotRelease[]
|
||||||
outboundMessages OutboundMessage[]
|
outboundMessages OutboundMessage[]
|
||||||
|
alertResolutions AttendeeAlertResolution[]
|
||||||
|
|
||||||
@@index([groupId], map: "attendees_groupId_idx")
|
@@index([groupId], map: "attendees_groupId_idx")
|
||||||
@@map("attendees")
|
@@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 {
|
model Payment {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
groupId String @map("group_id")
|
groupId String @map("group_id")
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
studentStatusRoutes,
|
studentStatusRoutes,
|
||||||
} from './modules/analytics';
|
} from './modules/analytics';
|
||||||
import { attendeesRoutes } from './modules/attendees';
|
import { attendeesRoutes } from './modules/attendees';
|
||||||
|
import { attentionRoutes } from './modules/attention';
|
||||||
import { authRoutes } from './modules/auth';
|
import { authRoutes } from './modules/auth';
|
||||||
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
||||||
import { classesRoutes } from './modules/classes';
|
import { classesRoutes } from './modules/classes';
|
||||||
@@ -65,6 +66,7 @@ api.route('/waitlist', waitlistRoutes);
|
|||||||
api.route('/classes', classesRoutes);
|
api.route('/classes', classesRoutes);
|
||||||
api.route('/students', studentStatusRoutes);
|
api.route('/students', studentStatusRoutes);
|
||||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||||
|
api.route('/attention', attentionRoutes);
|
||||||
|
|
||||||
app.notFound((c) => {
|
app.notFound((c) => {
|
||||||
return problemJson(c, notFoundProblem(c.req.path));
|
return problemJson(c, notFoundProblem(c.req.path));
|
||||||
|
|||||||
@@ -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
|
/* 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
|
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
|
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. */
|
the attendance rate the card shows. */
|
||||||
export const MEMBER_HISTORY_LIMIT = 20;
|
export const MEMBER_HISTORY_LIMIT = 20;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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<Result<AttentionOverview, ProblemDetails>> {
|
||||||
|
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<AttendeeRow[]>,
|
||||||
|
// 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<SessionRow[]>,
|
||||||
|
db.attendance.findMany({
|
||||||
|
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
|
||||||
|
select: {
|
||||||
|
attendeeId: true,
|
||||||
|
classSessionId: true,
|
||||||
|
status: true,
|
||||||
|
classSession: { select: { startsAt: true } },
|
||||||
|
},
|
||||||
|
}) as Promise<AttendanceRow[]>,
|
||||||
|
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<PaymentRow[]>,
|
||||||
|
db.attendeeAlertResolution.findMany({
|
||||||
|
where: { attendee: { groupId: { in: groupIds } } },
|
||||||
|
select: { attendeeId: true, kind: true, signature: true },
|
||||||
|
}) as Promise<ResolutionRow[]>,
|
||||||
|
]);
|
||||||
|
|
||||||
|
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<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
|
||||||
|
const map = new Map<string, T[]>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const list = map.get(key(row)) ?? [];
|
||||||
|
list.push(row);
|
||||||
|
map.set(key(row), list);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
@@ -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;
|
||||||
@@ -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<Result<ResolveAlertResult, ProblemDetails>> {
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
1
apps/backend/src/modules/attention/index.ts
Normal file
1
apps/backend/src/modules/attention/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { default as attentionRoutes } from './routes';
|
||||||
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
@@ -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<StudentAlertKind, StudentAlertType> = {
|
||||||
|
ATTENDANCE: 'asistencia',
|
||||||
|
PAYMENT: 'pago',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
|
||||||
|
asistencia: 'ATTENDANCE',
|
||||||
|
pago: 'PAYMENT',
|
||||||
|
};
|
||||||
10
apps/backend/src/modules/attention/routes.ts
Normal file
10
apps/backend/src/modules/attention/routes.ts
Normal file
@@ -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;
|
||||||
@@ -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')]);
|
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
||||||
prismaFetchAttendeeFindMany([
|
prismaFetchAttendeeFindMany([
|
||||||
attendee('a-1', 'group-1'),
|
attendee('a-1', 'group-1'),
|
||||||
@@ -122,10 +122,13 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||||
attendance('a-1', 's3', 'PRESENT', at(3)),
|
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||||
// A single absence, but 14 days between their last presence and the
|
// No streak (they came to s2), but 4 of their last 5 classes missed:
|
||||||
// class they missed (the ones in between have no record): inactivity.
|
// high risk through the window, not through the streak.
|
||||||
attendance('a-2', 's1', 'ABSENT', at(1)),
|
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.
|
// Ok.
|
||||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||||
attendance('a-3', 's2', 'PRESENT', at(2)),
|
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) },
|
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||||
]);
|
]);
|
||||||
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
|
// 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
|
// would look like a streak of 2; the middle class happened and has no
|
||||||
// middle class happened and has no record, so the real streak is 1.
|
// 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([
|
prismaFetchAttendanceFindMany([
|
||||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
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);
|
expect(res.status).toBe(200);
|
||||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||||
expect(items[0].riesgoAlto).toBe(0);
|
expect(items[0].riesgoAlto).toBe(0);
|
||||||
expect(items[0].atencion).toBe(0);
|
expect(items[0].atencion).toBe(1);
|
||||||
expect(items[0].ok).toBe(1);
|
expect(items[0].absenceStreakCount).toBe(0);
|
||||||
expect(items[0].urgentes).toEqual([
|
expect(items[0].urgentes).toEqual([
|
||||||
{
|
{
|
||||||
attendeeId: 'a-1',
|
attendeeId: 'a-1',
|
||||||
fullName: 'Sofía Díaz',
|
fullName: 'Sofía Díaz',
|
||||||
level: 'ok',
|
level: 'atencion',
|
||||||
consecutiveAbsences: 1,
|
consecutiveAbsences: 1,
|
||||||
daysSinceLastAttendance: 1,
|
daysSinceLastAttendance: 1,
|
||||||
// Both marked classes were absences; the middle one does not go into the average.
|
// 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
|
// 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
|
// 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
|
// 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([
|
prismaFetchAttendanceFindMany([
|
||||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
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);
|
expect(res.status).toBe(200);
|
||||||
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
|
||||||
expect(items[0].atencion).toBe(0);
|
expect(items[0].atencion).toBe(1);
|
||||||
expect(items[0].riesgoAlto).toBe(0);
|
expect(items[0].riesgoAlto).toBe(0);
|
||||||
expect(items[0].ok).toBe(1);
|
expect(items[0].absenceStreakCount).toBe(0);
|
||||||
expect(items[0].urgentes).toEqual([
|
expect(items[0].urgentes).toEqual([
|
||||||
{
|
{
|
||||||
attendeeId: 'a-1',
|
attendeeId: 'a-1',
|
||||||
fullName: 'Sofía Díaz',
|
fullName: 'Sofía Díaz',
|
||||||
level: 'ok',
|
level: 'atencion',
|
||||||
consecutiveAbsences: 0,
|
consecutiveAbsences: 0,
|
||||||
daysSinceLastAttendance: 1,
|
daysSinceLastAttendance: 1,
|
||||||
attendanceRate: 0,
|
attendanceRate: 0,
|
||||||
|
|||||||
@@ -14,9 +14,7 @@ import {
|
|||||||
|
|
||||||
Two test-scaffold helpers:
|
Two test-scaffold helpers:
|
||||||
|
|
||||||
- `dense` puts the classes on consecutive days, so that "how long since we
|
- `dense` puts the classes on consecutive days.
|
||||||
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).
|
|
||||||
- `series` honors the offsets it is given, for the cases that do need gaps.
|
- `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
|
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');
|
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', () => {
|
it('4 faltas en las últimas 6 clases dan riesgo alto aunque no haya racha', () => {
|
||||||
// A single absence, the most recent one: the streak doesn't reach. What drives
|
const { highWindowAbsences, highWindowSize } = ATTENDANCE_RISK_RULES;
|
||||||
// the level is the time since they last showed up.
|
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']));
|
||||||
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
|
|
||||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||||
expect(señales.consecutiveAbsences).toBe(1);
|
expect(señales.consecutiveAbsences).toBe(0);
|
||||||
expect(señales.daysSinceLastAttendance).toBe(30);
|
expect(señales.highWindow).toEqual({ absences: highWindowAbsences, classes: highWindowSize });
|
||||||
expect(señales.level).toBe('riesgo_alto');
|
expect(señales.level).toBe('riesgo_alto');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sin faltas después de la última presencia, la inactividad no cuenta', () => {
|
it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => {
|
||||||
// The group stopped recording classes (or didn't meet): 30 days since the
|
const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
|
||||||
// last presence, but the attendee missed nothing.
|
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 alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]]));
|
||||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||||
expect(señales.consecutiveAbsences).toBe(0);
|
|
||||||
expect(señales.daysSinceLastAttendance).toBe(30);
|
expect(señales.daysSinceLastAttendance).toBe(30);
|
||||||
expect(señales.level).toBe('ok');
|
expect(señales.level).toBe('ok');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
|
it('tres faltas seguidas son riesgo alto con buena historia detrás', () => {
|
||||||
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
|
// 16 classes at 81%: the 3 trailing absences are what decides the level.
|
||||||
// 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.
|
|
||||||
const alumno = member(dense([
|
const alumno = member(dense([
|
||||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
|
'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', () => {
|
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
|
// 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 conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
|
||||||
const señales = summarizeMemberAttendance(conHueco, NOW);
|
const señales = summarizeMemberAttendance(conHueco, NOW);
|
||||||
expect(señales.consecutiveAbsences).toBe(1);
|
expect(señales.consecutiveAbsences).toBe(1);
|
||||||
expect(señales.markedClasses).toBe(2);
|
expect(señales.markedClasses).toBe(2);
|
||||||
expect(señales.attendanceRate).toBe(0);
|
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', () => {
|
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.consecutiveAbsences).toBe(1);
|
||||||
expect(señales.markedClasses).toBe(2);
|
expect(señales.markedClasses).toBe(2);
|
||||||
expect(señales.attendanceRate).toBe(0);
|
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', () => {
|
it('avisar de la falta tampoco encadena las de alrededor', () => {
|
||||||
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
|
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
|
||||||
expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0);
|
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', () => {
|
it('no le importa el orden en que llegan las clases', () => {
|
||||||
|
|||||||
130
apps/backend/test/attention.test.ts
Normal file
130
apps/backend/test/attention.test.ts
Normal file
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
193
apps/backend/test/student-alerts.test.ts
Normal file
193
apps/backend/test/student-alerts.test.ts
Normal file
@@ -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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -88,7 +88,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
|||||||
{/* Toast Container */}
|
{/* Toast Container */}
|
||||||
<div
|
<div
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
className="fixed bottom-[calc(6rem+env(safe-area-inset-bottom))] right-4 z-50 lg:bottom-4 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
|
className="fixed bottom-[calc(9rem+env(safe-area-inset-bottom))] right-4 z-50 lg:bottom-4 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
|
||||||
>
|
>
|
||||||
{toasts.map((toast) => (
|
{toasts.map((toast) => (
|
||||||
<div
|
<div
|
||||||
|
|||||||
21
apps/web/src/features/attention/AlertTag.tsx
Normal file
21
apps/web/src/features/attention/AlertTag.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
80
apps/web/src/features/attention/AttentionCard.tsx
Normal file
80
apps/web/src/features/attention/AttentionCard.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
41
apps/web/src/features/attention/AttentionHeader.tsx
Normal file
41
apps/web/src/features/attention/AttentionHeader.tsx
Normal 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
|
||||||
|
}
|
||||||
82
apps/web/src/features/attention/AttentionProvider.tsx
Normal file
82
apps/web/src/features/attention/AttentionProvider.tsx
Normal 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
|
||||||
|
}
|
||||||
45
apps/web/src/features/attention/AttentionSection.tsx
Normal file
45
apps/web/src/features/attention/AttentionSection.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
48
apps/web/src/features/attention/AttentionView.tsx
Normal file
48
apps/web/src/features/attention/AttentionView.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
15
apps/web/src/features/attention/EmptyAttention.tsx
Normal file
15
apps/web/src/features/attention/EmptyAttention.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
37
apps/web/src/features/attention/FilterChips.tsx
Normal file
37
apps/web/src/features/attention/FilterChips.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
60
apps/web/src/features/attention/SeverityAvatar.tsx
Normal file
60
apps/web/src/features/attention/SeverityAvatar.tsx
Normal 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
|
||||||
|
}
|
||||||
135
apps/web/src/features/attention/attention.ts
Normal file
135
apps/web/src/features/attention/attention.ts
Normal 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}`
|
||||||
|
}
|
||||||
8
apps/web/src/features/attention/queries.ts
Normal file
8
apps/web/src/features/attention/queries.ts
Normal 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,
|
||||||
|
})
|
||||||
@@ -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 { Link } from '@tanstack/react-router'
|
||||||
import { TriangleAlert } from 'lucide-react'
|
import { cn } from '../../lib/utils'
|
||||||
import { AttendanceCapacityIndicator } from './AttendanceCapacityIndicator'
|
import { AvatarRow } from './AvatarRow'
|
||||||
import {
|
import { groupStatus, type GroupStatus } from './card'
|
||||||
SEGMENTED_CAPACITY_MAX,
|
|
||||||
alertTextFromMembers,
|
|
||||||
capacityCountsFromMembers,
|
|
||||||
membersFromGroupAndRisk,
|
|
||||||
type GroupMember,
|
|
||||||
} from './card'
|
|
||||||
|
|
||||||
const CARD_CLASS_NAME =
|
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 = {
|
const STATUS_TONES: Record<NonNullable<GroupStatus>['tone'], string> = {
|
||||||
id?: string
|
urgente: 'text-alert-urgent-fg',
|
||||||
name?: string
|
vigilar: 'text-alert-watch-fg',
|
||||||
capacity?: number
|
free: 'text-free-fg',
|
||||||
members?: GroupMember[]
|
full: 'text-secondary',
|
||||||
group?: GroupListItem
|
|
||||||
risk?: GroupRiskSummary | undefined
|
|
||||||
link?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function GroupCard({ link = true, ...props }: GroupCardProps) {
|
type GroupCardProps = {
|
||||||
const linkId = props.id ?? props.group?.id
|
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 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`
|
||||||
|
|
||||||
if (link && linkId) {
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
to="/groups/$groupId"
|
to="/groups/$groupId"
|
||||||
params={{ groupId: linkId }}
|
params={{ groupId: group.id }}
|
||||||
|
aria-label={[group.name, occupancy, status?.text].filter(Boolean).join(', ')}
|
||||||
className={CARD_CLASS_NAME}
|
className={CARD_CLASS_NAME}
|
||||||
>
|
>
|
||||||
<GroupCardContent {...props} />
|
<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>
|
||||||
|
|
||||||
|
{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>
|
</Link>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={CARD_CLASS_NAME}>
|
|
||||||
<GroupCardContent {...props} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
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>
|
|
||||||
</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>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
||||||
import { useState } from 'react'
|
|
||||||
import { Button } from '../../components/ui'
|
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 { GroupCard } from './GroupCard'
|
||||||
import { MOCK_TEST_CASES } from './card'
|
import { groupsSummary, membersOf } from './card'
|
||||||
|
import { NewGroupFab } from './NewGroupFab'
|
||||||
|
|
||||||
export function GroupsView() {
|
export function GroupsView() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@@ -13,49 +16,16 @@ export function GroupsView() {
|
|||||||
queryKey: ['groups'],
|
queryKey: ['groups'],
|
||||||
queryFn: getGroups,
|
queryFn: getGroups,
|
||||||
})
|
})
|
||||||
const riskQuery = useQuery({
|
const attentionQuery = useQuery(attentionQueryOptions)
|
||||||
queryKey: ['groups-risk-overview'],
|
|
||||||
queryFn: getGroupsRiskOverview,
|
|
||||||
})
|
|
||||||
|
|
||||||
const [showExamples, setShowExamples] = useState(() => {
|
const groups = groupsQuery.data?.data ?? []
|
||||||
if (typeof window !== 'undefined') {
|
const hasGroups = groupsQuery.isSuccess && groups.length > 0
|
||||||
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
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
// The FAB floats over the last card: 88px of room so it can be read.
|
||||||
<div className="flex items-center justify-between gap-3">
|
<section className="pb-[88px]">
|
||||||
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
||||||
<div className="flex items-center gap-2">
|
{hasGroups ? <p className="mt-1 text-sm text-secondary">{groupsSummary(groups)}</p> : null}
|
||||||
{!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>
|
|
||||||
|
|
||||||
{groupsQuery.isPending ? (
|
{groupsQuery.isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
@@ -73,15 +43,7 @@ export function GroupsView() {
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{showExamples ? (
|
{groupsQuery.isSuccess && groups.length === 0 ? (
|
||||||
<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 ? (
|
|
||||||
/* A single icon, one focal point, and the text in secondary: the empty
|
/* A single icon, one focal point, and the text in secondary: the empty
|
||||||
state competes with the action and must not win. */
|
state competes with the action and must not win. */
|
||||||
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
|
<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">
|
<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.
|
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
|
||||||
</p>
|
</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
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
className="h-11"
|
className="mt-6 h-11"
|
||||||
onClick={() => void navigate({ to: '/groups/new' })}
|
onClick={() => void navigate({ to: '/groups/new' })}
|
||||||
>
|
>
|
||||||
<Plus className="size-4" />
|
<Plus className="size-4" />
|
||||||
Crear primer grupo
|
Crear primer grupo
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{hasGroups && !showExamples ? (
|
{hasGroups ? (
|
||||||
<div className="mt-6 grid gap-4">
|
<>
|
||||||
{groupsQuery.data.data.map((group) => (
|
<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
|
<GroupCard
|
||||||
key={group.id}
|
key={group.id}
|
||||||
group={group}
|
group={group}
|
||||||
risk={riskByGroup.get(group.id)}
|
members={
|
||||||
|
attentionQuery.isSuccess
|
||||||
|
? (membersOf(attentionQuery.data.groups, group.id) ?? [])
|
||||||
|
: attentionQuery.isError
|
||||||
|
? null
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
<NewGroupFab />
|
||||||
</section>
|
</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
|
/* 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
|
here what is shown and in what order, so the JSX only builds the layout and
|
||||||
builds the layout and the rules can be tested on their own.
|
the rules can be tested on their own.
|
||||||
|
|
||||||
The per-level counts and the urgent attendees are not computed on the client:
|
The faces come from `GET /attention` (ACTIVE members with their alerts, the
|
||||||
they come from `GET /groups-risk/overview`, which runs the same domain function
|
same data as the "Requiere atención" screen); the occupancy from the group
|
||||||
(`getGroupAttendanceSummary` in packages/shared) that the follow-up section on
|
listing (`attendeesCount`, which is what the capacity checks count). */
|
||||||
Home will use. Here we only adapt that response to what the card needs to paint,
|
|
||||||
and we decide how it reads. */
|
|
||||||
|
|
||||||
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
|
/** Faces drawn before the "+N" when the row overlaps. */
|
||||||
* switches to proportional blocks.
|
export const STACKED_FACES = 4
|
||||||
|
|
||||||
|
export type AvatarSlot =
|
||||||
|
| { kind: 'member'; member: AttentionMember; severity: StudentAlertSeverity | null }
|
||||||
|
| { kind: 'free'; key: string }
|
||||||
|
| { kind: 'more'; count: number }
|
||||||
|
|
||||||
|
export type AvatarRowModel = { stacked: boolean; slots: AvatarSlot[] }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
*
|
*
|
||||||
* The threshold is set by the width, not by a round number. The bar has to fit
|
* - Fits in a line and has free spots: every face plus a dashed circle per spot.
|
||||||
* in a phone's card: ~291px on a 402px viewport, after discounting `<main>`'s
|
* - Otherwise (big or full group): overlapped faces, the last circle is "+N".
|
||||||
* 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
|
|
||||||
|
|
||||||
export type MemberStatus = 'high_risk' | 'attention' | 'ok'
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Counts derived directly from a member list and the capacity.
|
|
||||||
*/
|
*/
|
||||||
export function capacityCountsFromMembers(
|
export function avatarRow(
|
||||||
members: GroupMember[],
|
members: AttentionMember[],
|
||||||
capacity: number,
|
capacity: number | null,
|
||||||
): CapacityCounts {
|
occupied: number = members.length,
|
||||||
let riesgoAlto = 0
|
): AvatarRowModel {
|
||||||
let atencion = 0
|
const ordered = [...members].sort((a, b) => {
|
||||||
let ok = 0
|
const flagged = Number(b.alerts.length > 0) - Number(a.alerts.length > 0)
|
||||||
|
return flagged !== 0 ? flagged : a.alerts.length > 0 ? compareByWorstAlert(a, b) : 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') {
|
const faces = ordered.map(
|
||||||
members.push({
|
(member): AvatarSlot => ({ kind: 'member', member, severity: worstAlert(member.alerts)?.gravedad ?? null }),
|
||||||
id: u.attendeeId,
|
)
|
||||||
name: u.fullName,
|
const free = freeSpots(capacity, occupied)
|
||||||
status: 'attention',
|
|
||||||
absences: u.consecutiveAbsences,
|
if (capacity !== null && capacity <= INLINE_SLOTS_MAX && free > 0) {
|
||||||
reason: absenceReason(u) ?? undefined,
|
const dashed = Array.from({ length: free }, (_, index): AvatarSlot => ({ kind: 'free', key: `free-${index}` }))
|
||||||
})
|
return { stacked: false, slots: [...faces, ...dashed] }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentHigh = members.filter((m) => m.status === 'high_risk').length
|
// "+N" only when it saves at least two faces: "+1" takes the same room as
|
||||||
const remainingHigh = Math.max((risk?.riesgoAlto ?? 0) - currentHigh, 0)
|
// the face it hides.
|
||||||
for (let i = 0; i < remainingHigh; i++) {
|
if (occupied <= STACKED_FACES + 1) {
|
||||||
members.push({
|
return { stacked: true, slots: faces }
|
||||||
id: `high-risk-extra-${i}`,
|
}
|
||||||
name: `Alumno ${members.length + 1}`,
|
const shown = faces.slice(0, STACKED_FACES)
|
||||||
status: 'high_risk',
|
return { stacked: true, slots: [...shown, { kind: 'more', count: occupied - shown.length }] }
|
||||||
absences: 1,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentAttention = members.filter((m) => m.status === 'attention').length
|
export type GroupStatus =
|
||||||
const remainingAttention = Math.max((risk?.atencion ?? 0) - currentAttention, 0)
|
| { tone: StudentAlertSeverity; text: string }
|
||||||
for (let i = 0; i < remainingAttention; i++) {
|
| { tone: 'free'; text: string }
|
||||||
members.push({
|
| { tone: 'full'; text: string }
|
||||||
id: `attention-extra-${i}`,
|
| null
|
||||||
name: `Alumno ${members.length + 1}`,
|
|
||||||
status: 'attention',
|
/** Text to the right of the avatars: risk first, then free spots, then full. */
|
||||||
absences: 0,
|
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' }
|
||||||
}
|
}
|
||||||
|
|
||||||
const remainingOk = Math.max(group.attendeesCount - members.length, 0)
|
/** "4 grupos · 37 alumnos · 7 lugares libres" under the page title. */
|
||||||
for (let i = 0; i < remainingOk; i++) {
|
export function groupsSummary(groups: Pick<GroupListItem, 'attendeesCount' | 'capacity'>[]): string {
|
||||||
members.push({
|
const students = groups.reduce((total, group) => total + group.attendeesCount, 0)
|
||||||
id: `ok-${i}`,
|
const free = groups.reduce((total, group) => total + freeSpots(group.capacity, group.attendeesCount), 0)
|
||||||
name: `Alumno ${members.length + 1}`,
|
return [
|
||||||
status: 'ok',
|
plural(groups.length, 'grupo', 'grupos'),
|
||||||
absences: 0,
|
plural(students, 'alumno', 'alumnos'),
|
||||||
})
|
plural(free, 'lugar libre', 'lugares libres'),
|
||||||
|
].join(' · ')
|
||||||
}
|
}
|
||||||
|
|
||||||
return members
|
/** 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
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function freeSpots(capacity: number | null, occupied: number): number {
|
||||||
* Counts consumed by the capacity and attendance indicator.
|
return capacity === null ? 0 : Math.max(capacity - occupied, 0)
|
||||||
*
|
|
||||||
* `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.
|
|
||||||
*/
|
|
||||||
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)
|
|
||||||
|
|
||||||
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. */
|
function plural(count: number, one: string, many: string): string {
|
||||||
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
|
return `${count} ${count === 1 ? one : many}`
|
||||||
|
|
||||||
export function riskTone(counts: CapacityCounts): RiskTone {
|
|
||||||
if (counts.riesgoAlto > 0) return 'riesgo_alto'
|
|
||||||
if (counts.atencion > 0) return 'atencion'
|
|
||||||
return 'ok'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type StatusLine = {
|
/* The reason Home shows next to an at-risk student: first a streak of absences
|
||||||
text: string
|
(something that is going away), then the time since last showing up, and
|
||||||
tone: RiskTone
|
last the attendance rate. A single absence only names them when nothing else
|
||||||
}
|
does. */
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 (risk?.asistencia != null) return { text: `Asistencia ${risk.asistencia}%`, tone: 'ok' }
|
|
||||||
return { text: 'Sin clases registradas', tone: 'ok' }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "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'}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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(' · ')
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 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". */
|
|
||||||
export function absenceReason(miembro: UrgentMemberSummary): string | null {
|
export function absenceReason(miembro: UrgentMemberSummary): string | null {
|
||||||
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
|
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}%`
|
if (asistencia != null && asistencia < 100) return `asistencia ${asistencia}%`
|
||||||
return null
|
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,
|
|
||||||
})),
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|||||||
41
apps/web/src/hooks/useCollapseOnScroll.ts
Normal file
41
apps/web/src/hooks/useCollapseOnScroll.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
type CollapseOptions = {
|
||||||
|
/** Scroll from the top before collapsing is allowed. */
|
||||||
|
threshold?: number
|
||||||
|
/** Time without scrolling after which it expands again. */
|
||||||
|
idleMs?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `true` while the user scrolls down past `threshold`; `false` when they scroll
|
||||||
|
* up, stop for `idleMs`, or are back at the top. For a FAB that shrinks to its
|
||||||
|
* icon so it doesn't cover the content being read.
|
||||||
|
*/
|
||||||
|
export function useCollapseOnScroll({ threshold = 24, idleMs = 700 }: CollapseOptions = {}) {
|
||||||
|
const [collapsed, setCollapsed] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let lastY = window.scrollY
|
||||||
|
let idleTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
const onScroll = () => {
|
||||||
|
const y = window.scrollY
|
||||||
|
if (y <= threshold) setCollapsed(false)
|
||||||
|
else if (y > lastY) setCollapsed(true)
|
||||||
|
else if (y < lastY) setCollapsed(false)
|
||||||
|
lastY = y
|
||||||
|
|
||||||
|
clearTimeout(idleTimer)
|
||||||
|
idleTimer = setTimeout(() => setCollapsed(false), idleMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('scroll', onScroll, { passive: true })
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('scroll', onScroll)
|
||||||
|
clearTimeout(idleTimer)
|
||||||
|
}
|
||||||
|
}, [threshold, idleMs])
|
||||||
|
|
||||||
|
return collapsed
|
||||||
|
}
|
||||||
@@ -70,6 +70,17 @@
|
|||||||
--color-attendance-high: var(--attendance-high);
|
--color-attendance-high: var(--attendance-high);
|
||||||
--color-attendance-attention: var(--attendance-attention);
|
--color-attendance-attention: var(--attendance-attention);
|
||||||
--color-attendance-ok: var(--attendance-ok);
|
--color-attendance-ok: var(--attendance-ok);
|
||||||
|
/* "Requiere atención": severity of a student alert (ring, text, pill and the
|
||||||
|
container of the Grupos preview) and the "N libres" green. */
|
||||||
|
--color-alert-urgent-ring: var(--alert-urgent-ring);
|
||||||
|
--color-alert-urgent-fg: var(--alert-urgent-fg);
|
||||||
|
--color-alert-urgent-soft: var(--alert-urgent-soft);
|
||||||
|
--color-alert-urgent-surface: var(--alert-urgent-surface);
|
||||||
|
--color-alert-urgent-edge: var(--alert-urgent-edge);
|
||||||
|
--color-alert-watch-ring: var(--alert-watch-ring);
|
||||||
|
--color-alert-watch-fg: var(--alert-watch-fg);
|
||||||
|
--color-alert-watch-soft: var(--alert-watch-soft);
|
||||||
|
--color-free-fg: var(--free-fg);
|
||||||
|
|
||||||
/* Default border radius */
|
/* Default border radius */
|
||||||
--radius-xl: 0.75rem;
|
--radius-xl: 0.75rem;
|
||||||
@@ -157,6 +168,18 @@
|
|||||||
--attendance-high: #d63b3b;
|
--attendance-high: #d63b3b;
|
||||||
--attendance-attention: #f5a623;
|
--attendance-attention: #f5a623;
|
||||||
--attendance-ok: #2b7bd6;
|
--attendance-ok: #2b7bd6;
|
||||||
|
/* Alert severities. Text on its pill: urgent #b91c1c on #fee2e2 is 5.4:1,
|
||||||
|
watch #92400e on #fef3c7 is 6.4:1; the free green #15803d is 5.0:1 on the
|
||||||
|
card. The rings are fills (3:1 is enough), always next to a text label. */
|
||||||
|
--alert-urgent-ring: #dc2626;
|
||||||
|
--alert-urgent-fg: #b91c1c;
|
||||||
|
--alert-urgent-soft: #fee2e2;
|
||||||
|
--alert-urgent-surface: #fef2f2;
|
||||||
|
--alert-urgent-edge: #fecaca;
|
||||||
|
--alert-watch-ring: #d97706;
|
||||||
|
--alert-watch-fg: #92400e;
|
||||||
|
--alert-watch-soft: #fef3c7;
|
||||||
|
--free-fg: #15803d;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark {
|
.dark {
|
||||||
@@ -194,6 +217,15 @@
|
|||||||
/* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
|
/* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
|
||||||
more than enough as a fill, so there's nothing to move here. */
|
more than enough as a fill, so there's nothing to move here. */
|
||||||
--danger-fg: var(--danger);
|
--danger-fg: var(--danger);
|
||||||
|
--alert-urgent-ring: #f87171;
|
||||||
|
--alert-urgent-fg: #fca5a5;
|
||||||
|
--alert-urgent-soft: #2e1419;
|
||||||
|
--alert-urgent-surface: #15111a;
|
||||||
|
--alert-urgent-edge: #3a2028;
|
||||||
|
--alert-watch-ring: #fbbf24;
|
||||||
|
--alert-watch-fg: #fde68a;
|
||||||
|
--alert-watch-soft: #2b220f;
|
||||||
|
--free-fg: #86efac;
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ import type {
|
|||||||
GroupPreRegistrationList,
|
GroupPreRegistrationList,
|
||||||
GroupRiskSummary,
|
GroupRiskSummary,
|
||||||
GroupsRiskOverview,
|
GroupsRiskOverview,
|
||||||
|
AttentionOverview,
|
||||||
|
ResolveAlert,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
GroupWaitlistList,
|
GroupWaitlistList,
|
||||||
HomeSummaryDto,
|
HomeSummaryDto,
|
||||||
@@ -376,6 +378,14 @@ export const getStudentsAtRisk = (groupId: string) =>
|
|||||||
|
|
||||||
export const getGroupsRiskOverview = () => apiFetch<GroupsRiskOverview>('/api/v1/groups-risk/overview')
|
export const getGroupsRiskOverview = () => apiFetch<GroupsRiskOverview>('/api/v1/groups-risk/overview')
|
||||||
|
|
||||||
|
export const getAttention = () => apiFetch<AttentionOverview>('/api/v1/attention')
|
||||||
|
|
||||||
|
export const resolveAlert = (attendeeId: string, body: ResolveAlert) =>
|
||||||
|
apiFetch<ResolveAlert & { attendeeId: string }>(`/api/v1/attention/${attendeeId}/resolve`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})
|
||||||
|
|
||||||
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
|
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
|
||||||
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)
|
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
still uses the global header. */
|
still uses the global header. */
|
||||||
|
|
||||||
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||||
|
['groups', 'attention'],
|
||||||
['groups', ':id'],
|
['groups', ':id'],
|
||||||
['groups', ':id', 'analytics'],
|
['groups', ':id', 'analytics'],
|
||||||
['groups', ':id', 'attendees', ':attendeeId'],
|
['groups', ':id', 'attendees', ':attendeeId'],
|
||||||
@@ -16,8 +17,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
|||||||
|
|
||||||
/* Static routes that sit where a param would go. Without this list
|
/* Static routes that sit where a param would go. Without this list
|
||||||
`/groups/new` (create group) would be taken for a group detail page and would
|
`/groups/new` (create group) would be taken for a group detail page and would
|
||||||
lose the global header. */
|
lose the global header, and `/groups/attention/...` for a group's children.
|
||||||
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
|
(`/groups/attention` itself is immersive through its own pattern.) */
|
||||||
|
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new', 'attention'])
|
||||||
|
|
||||||
export function isImmersiveRoute(pathname: string) {
|
export function isImmersiveRoute(pathname: string) {
|
||||||
const segments = pathname.split('/').filter(Boolean)
|
const segments = pathname.split('/').filter(Boolean)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { Route as AdminIndexRouteImport } from './routes/admin/index'
|
|||||||
import { Route as JoinTokenRouteImport } from './routes/join.$token'
|
import { Route as JoinTokenRouteImport } from './routes/join.$token'
|
||||||
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
|
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
|
||||||
import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index'
|
import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index'
|
||||||
|
import { Route as AuthenticatedGroupsAttentionRouteImport } from './routes/_authenticated/groups/attention'
|
||||||
import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new'
|
import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new'
|
||||||
import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accounts.$accountId'
|
import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accounts.$accountId'
|
||||||
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
||||||
@@ -125,6 +126,12 @@ const AuthenticatedGroupsIndexRoute =
|
|||||||
path: '/groups/',
|
path: '/groups/',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AuthenticatedGroupsAttentionRoute =
|
||||||
|
AuthenticatedGroupsAttentionRouteImport.update({
|
||||||
|
id: '/groups/attention',
|
||||||
|
path: '/groups/attention',
|
||||||
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
|
} as any)
|
||||||
const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({
|
const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({
|
||||||
id: '/groups/new',
|
id: '/groups/new',
|
||||||
path: '/groups/new',
|
path: '/groups/new',
|
||||||
@@ -183,6 +190,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/join/$token': typeof JoinTokenRoute
|
'/join/$token': typeof JoinTokenRoute
|
||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
'/admin/': typeof AdminIndexRoute
|
'/admin/': typeof AdminIndexRoute
|
||||||
|
'/groups/attention': typeof AuthenticatedGroupsAttentionRoute
|
||||||
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/groups/': typeof AuthenticatedGroupsIndexRoute
|
'/groups/': typeof AuthenticatedGroupsIndexRoute
|
||||||
@@ -208,6 +216,7 @@ export interface FileRoutesByTo {
|
|||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
'/admin': typeof AdminIndexRoute
|
'/admin': typeof AdminIndexRoute
|
||||||
|
'/groups/attention': typeof AuthenticatedGroupsAttentionRoute
|
||||||
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/groups': typeof AuthenticatedGroupsIndexRoute
|
'/groups': typeof AuthenticatedGroupsIndexRoute
|
||||||
@@ -236,6 +245,7 @@ export interface FileRoutesById {
|
|||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||||
'/admin/': typeof AdminIndexRoute
|
'/admin/': typeof AdminIndexRoute
|
||||||
|
'/_authenticated/groups/attention': typeof AuthenticatedGroupsAttentionRoute
|
||||||
'/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute
|
'/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute
|
||||||
@@ -264,6 +274,7 @@ export interface FileRouteTypes {
|
|||||||
| '/join/$token'
|
| '/join/$token'
|
||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
| '/admin/'
|
| '/admin/'
|
||||||
|
| '/groups/attention'
|
||||||
| '/groups/new'
|
| '/groups/new'
|
||||||
| '/admin/accounts/$accountId'
|
| '/admin/accounts/$accountId'
|
||||||
| '/groups/'
|
| '/groups/'
|
||||||
@@ -289,6 +300,7 @@ export interface FileRouteTypes {
|
|||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
| '/'
|
| '/'
|
||||||
| '/admin'
|
| '/admin'
|
||||||
|
| '/groups/attention'
|
||||||
| '/groups/new'
|
| '/groups/new'
|
||||||
| '/admin/accounts/$accountId'
|
| '/admin/accounts/$accountId'
|
||||||
| '/groups'
|
| '/groups'
|
||||||
@@ -316,6 +328,7 @@ export interface FileRouteTypes {
|
|||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
| '/_authenticated/'
|
| '/_authenticated/'
|
||||||
| '/admin/'
|
| '/admin/'
|
||||||
|
| '/_authenticated/groups/attention'
|
||||||
| '/_authenticated/groups/new'
|
| '/_authenticated/groups/new'
|
||||||
| '/admin/accounts/$accountId'
|
| '/admin/accounts/$accountId'
|
||||||
| '/_authenticated/groups/'
|
| '/_authenticated/groups/'
|
||||||
@@ -467,6 +480,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedGroupsIndexRouteImport
|
preLoaderRoute: typeof AuthenticatedGroupsIndexRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
parentRoute: typeof AuthenticatedRoute
|
||||||
}
|
}
|
||||||
|
'/_authenticated/groups/attention': {
|
||||||
|
id: '/_authenticated/groups/attention'
|
||||||
|
path: '/groups/attention'
|
||||||
|
fullPath: '/groups/attention'
|
||||||
|
preLoaderRoute: typeof AuthenticatedGroupsAttentionRouteImport
|
||||||
|
parentRoute: typeof AuthenticatedRoute
|
||||||
|
}
|
||||||
'/_authenticated/groups/new': {
|
'/_authenticated/groups/new': {
|
||||||
id: '/_authenticated/groups/new'
|
id: '/_authenticated/groups/new'
|
||||||
path: '/groups/new'
|
path: '/groups/new'
|
||||||
@@ -526,6 +546,7 @@ interface AuthenticatedRouteChildren {
|
|||||||
AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute
|
AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute
|
||||||
AuthenticatedSettingsRoute: typeof AuthenticatedSettingsRoute
|
AuthenticatedSettingsRoute: typeof AuthenticatedSettingsRoute
|
||||||
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
|
AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute
|
||||||
|
AuthenticatedGroupsAttentionRoute: typeof AuthenticatedGroupsAttentionRoute
|
||||||
AuthenticatedGroupsNewRoute: typeof AuthenticatedGroupsNewRoute
|
AuthenticatedGroupsNewRoute: typeof AuthenticatedGroupsNewRoute
|
||||||
AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute
|
AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute
|
||||||
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
@@ -542,6 +563,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
|||||||
AuthenticatedSecurityRoute: AuthenticatedSecurityRoute,
|
AuthenticatedSecurityRoute: AuthenticatedSecurityRoute,
|
||||||
AuthenticatedSettingsRoute: AuthenticatedSettingsRoute,
|
AuthenticatedSettingsRoute: AuthenticatedSettingsRoute,
|
||||||
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
|
AuthenticatedIndexRoute: AuthenticatedIndexRoute,
|
||||||
|
AuthenticatedGroupsAttentionRoute: AuthenticatedGroupsAttentionRoute,
|
||||||
AuthenticatedGroupsNewRoute: AuthenticatedGroupsNewRoute,
|
AuthenticatedGroupsNewRoute: AuthenticatedGroupsNewRoute,
|
||||||
AuthenticatedGroupsIndexRoute: AuthenticatedGroupsIndexRoute,
|
AuthenticatedGroupsIndexRoute: AuthenticatedGroupsIndexRoute,
|
||||||
AuthenticatedClassSessionIdAttendanceRoute:
|
AuthenticatedClassSessionIdAttendanceRoute:
|
||||||
|
|||||||
11
apps/web/src/routes/_authenticated/groups/attention.tsx
Normal file
11
apps/web/src/routes/_authenticated/groups/attention.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { AttentionProvider } from '../../../features/attention/AttentionProvider'
|
||||||
|
import { AttentionView } from '../../../features/attention/AttentionView'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/groups/attention')({
|
||||||
|
component: () => (
|
||||||
|
<AttentionProvider>
|
||||||
|
<AttentionView />
|
||||||
|
</AttentionProvider>
|
||||||
|
),
|
||||||
|
})
|
||||||
167
apps/web/test/attention.test.ts
Normal file
167
apps/web/test/attention.test.ts
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
import type { AttentionMember, AttentionOverview, StudentAlert } from '@gruperly/shared'
|
||||||
|
import { createElement } from 'react'
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server'
|
||||||
|
import {
|
||||||
|
attentionItems,
|
||||||
|
attentionSubtitle,
|
||||||
|
filterCounts,
|
||||||
|
filterItems,
|
||||||
|
flaggedStudents,
|
||||||
|
itemsBySeverity,
|
||||||
|
reminderMessage,
|
||||||
|
whatsappLink,
|
||||||
|
withoutAlert,
|
||||||
|
} from '../src/features/attention/attention'
|
||||||
|
import { FilterChips } from '../src/features/attention/FilterChips'
|
||||||
|
|
||||||
|
/* "Requiere atención" recibe las alertas calculadas: acá se prueba cómo se
|
||||||
|
aplanan en tarjetas, se cuentan por filtro y gravedad, y qué mensaje sale. */
|
||||||
|
|
||||||
|
const alerta = (tipo: StudentAlert['tipo'], gravedad: StudentAlert['gravedad'], peso = 2): StudentAlert => ({
|
||||||
|
tipo,
|
||||||
|
gravedad,
|
||||||
|
etiqueta: tipo === 'pago' ? 'Cuota vencida' : `${peso} faltas`,
|
||||||
|
detalle: '',
|
||||||
|
firma: `${tipo}-firma`,
|
||||||
|
peso,
|
||||||
|
})
|
||||||
|
|
||||||
|
const miembro = (id: string, fullName: string, alerts: StudentAlert[], extra: Partial<AttentionMember> = {}) => ({
|
||||||
|
attendeeId: id,
|
||||||
|
fullName,
|
||||||
|
phone: '11 5555-0000',
|
||||||
|
whatsappPhone: '+5491155550000',
|
||||||
|
alerts,
|
||||||
|
overduePayments: [],
|
||||||
|
...extra,
|
||||||
|
})
|
||||||
|
|
||||||
|
const overview: AttentionOverview = {
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
groupId: 'g1',
|
||||||
|
groupName: 'Natación',
|
||||||
|
capacity: 30,
|
||||||
|
members: [
|
||||||
|
miembro('a1', 'Agustina', [alerta('asistencia', 'urgente', 4)]),
|
||||||
|
miembro('a2', 'Bruno', [alerta('pago', 'vigilar', 1)]),
|
||||||
|
miembro('a3', 'Felipe', []),
|
||||||
|
// Dos alertas: aparece en dos tarjetas, pero cuenta como un alumno.
|
||||||
|
miembro('a4', 'Valentina', [alerta('pago', 'urgente', 2), alerta('asistencia', 'vigilar')]),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupId: 'g2',
|
||||||
|
groupName: 'Tai Chi Martes',
|
||||||
|
capacity: 4,
|
||||||
|
members: [miembro('b1', 'Martina', [alerta('asistencia', 'vigilar')])],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('flaggedStudents', () => {
|
||||||
|
test('solo los alumnos con alerta, el más urgente primero, con su peor alerta', () => {
|
||||||
|
const students = flaggedStudents(overview)
|
||||||
|
expect(students.map((student) => [student.fullName, student.worst.gravedad])).toEqual([
|
||||||
|
['Agustina', 'urgente'],
|
||||||
|
['Valentina', 'urgente'],
|
||||||
|
['Martina', 'vigilar'],
|
||||||
|
['Bruno', 'vigilar'],
|
||||||
|
])
|
||||||
|
expect(students[2].groupName).toBe('Tai Chi Martes')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sin datos no hay alumnos', () => {
|
||||||
|
expect(flaggedStudents(undefined)).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('tarjetas, filtros y contadores', () => {
|
||||||
|
const items = attentionItems(flaggedStudents(overview))
|
||||||
|
|
||||||
|
test('una tarjeta por alerta, urgentes primero', () => {
|
||||||
|
expect(items.map((item) => `${item.student.fullName}:${item.alert.tipo}`)).toEqual([
|
||||||
|
'Agustina:asistencia',
|
||||||
|
'Valentina:pago',
|
||||||
|
'Martina:asistencia',
|
||||||
|
'Valentina:asistencia',
|
||||||
|
'Bruno:pago',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cuenta por filtro', () => {
|
||||||
|
expect(filterCounts(items)).toEqual({ todos: 5, asistencia: 3, pago: 2 })
|
||||||
|
expect(filterItems(items, 'pago').map((item) => item.student.fullName)).toEqual(['Valentina', 'Bruno'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('separa por gravedad', () => {
|
||||||
|
const { urgente, vigilar } = itemsBySeverity(items)
|
||||||
|
expect(urgente).toHaveLength(2)
|
||||||
|
expect(vigilar).toHaveLength(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el subtítulo cuenta alumnos, no tarjetas', () => {
|
||||||
|
expect(attentionSubtitle(items)).toBe('4 alumnos · 2 urgentes')
|
||||||
|
expect(attentionSubtitle(filterItems(items, 'asistencia').slice(2))).toBe('1 alumno')
|
||||||
|
expect(attentionSubtitle([])).toBe('Nada pendiente')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('"Resuelto" saca solo esa alerta del caché', () => {
|
||||||
|
const next = withoutAlert(overview, 'a4', 'pago')
|
||||||
|
const valentina = next.groups[0].members.find((member) => member.attendeeId === 'a4')
|
||||||
|
expect(valentina?.alerts.map((alert) => alert.tipo)).toEqual(['asistencia'])
|
||||||
|
expect(filterCounts(attentionItems(flaggedStudents(next)))).toEqual({ todos: 4, asistencia: 3, pago: 1 })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('WhatsApp', () => {
|
||||||
|
test('arma el link con el E.164 y el texto', () => {
|
||||||
|
expect(whatsappLink({ whatsappPhone: '+5491155550000' })).toBe('https://wa.me/5491155550000')
|
||||||
|
expect(whatsappLink({ whatsappPhone: '+5491155550000' }, 'Hola')).toBe('https://wa.me/5491155550000?text=Hola')
|
||||||
|
expect(whatsappLink({ whatsappPhone: null })).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el recordatorio nombra la cuota, la fecha y el link de pago', () => {
|
||||||
|
const [student] = flaggedStudents({
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
groupId: 'g1',
|
||||||
|
groupName: 'Natación',
|
||||||
|
capacity: 30,
|
||||||
|
members: [
|
||||||
|
miembro('a1', 'Nicolás Gómez', [alerta('pago', 'vigilar', 1)], {
|
||||||
|
overduePayments: [
|
||||||
|
{
|
||||||
|
id: 'p1',
|
||||||
|
amount: 15000,
|
||||||
|
currency: 'ARS',
|
||||||
|
dueDate: '2026-10-10T12:00:00.000Z',
|
||||||
|
checkoutUrl: 'https://mpago.la/abc',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
const message = reminderMessage(student)
|
||||||
|
expect(message).toStartWith('¡Hola Nicolás!')
|
||||||
|
expect(message).toContain('la cuota de Natación')
|
||||||
|
expect(message).toContain('venció el 10/10')
|
||||||
|
expect(message).toContain('https://mpago.la/abc')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('los chips marcan el activo con aria-pressed y muestran su contador', () => {
|
||||||
|
const markup = renderToStaticMarkup(
|
||||||
|
createElement(FilterChips, {
|
||||||
|
value: 'asistencia',
|
||||||
|
counts: { todos: 7, asistencia: 4, pago: 3 },
|
||||||
|
onChange: () => undefined,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(markup.match(/aria-pressed="true"/g)).toHaveLength(1)
|
||||||
|
expect(markup).toMatch(/aria-pressed="true"[^>]*>Asistencia/)
|
||||||
|
expect(markup).toContain('>7<')
|
||||||
|
})
|
||||||
@@ -1,544 +1,145 @@
|
|||||||
import { describe, expect, test } from 'bun:test'
|
import { describe, expect, test } from 'bun:test'
|
||||||
import type { GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
|
import type { AttentionMember, StudentAlert } from '@gruperly/shared'
|
||||||
import { createElement } from 'react'
|
import { createElement } from 'react'
|
||||||
import { renderToStaticMarkup } from 'react-dom/server'
|
import { renderToStaticMarkup } from 'react-dom/server'
|
||||||
|
import { AvatarRow } from '../src/features/groups/AvatarRow'
|
||||||
import {
|
import {
|
||||||
alertTextFromMembers,
|
avatarRow,
|
||||||
barCapacity,
|
groupStatus,
|
||||||
capacityCounts,
|
groupsSummary,
|
||||||
capacityCountsFromMembers,
|
INLINE_SLOTS_MAX,
|
||||||
isSegmentedCapacity,
|
membersOf,
|
||||||
MOCK_TEST_CASES,
|
STACKED_FACES,
|
||||||
occupancyLabel,
|
|
||||||
riskTone,
|
|
||||||
SEGMENTED_CAPACITY_MAX,
|
|
||||||
statusLine,
|
|
||||||
type GroupMember,
|
|
||||||
} from '../src/features/groups/card'
|
} from '../src/features/groups/card'
|
||||||
import {
|
|
||||||
capacityIndicatorLabel,
|
|
||||||
capacitySegmentWidth,
|
|
||||||
} from '../src/features/groups/AttendanceCapacityIndicator'
|
|
||||||
import { GroupCard, GroupCardContent } from '../src/features/groups/GroupCard'
|
|
||||||
|
|
||||||
/* La tarjeta del listado no calcula el riesgo: lo recibe de
|
/* La tarjeta del listado no calcula alertas: las recibe de `GET /attention`,
|
||||||
`GET /groups-risk/overview`, que corre la función de dominio del backend. Lo
|
que corre `computeStudentAlerts` (shared). Acá se prueba cómo se dibujan:
|
||||||
que se prueba acá es la traducción de esa respuesta a la tarjeta: qué se
|
qué caras van, en qué orden, cuándo se superponen y qué estado se nombra. */
|
||||||
cuenta, qué se nombra y cuándo la card se tiñe. Todo sin montar React. */
|
|
||||||
|
|
||||||
const risk = (
|
const alerta = (gravedad: StudentAlert['gravedad'], peso = 2): StudentAlert => ({
|
||||||
riesgoAlto: number,
|
tipo: 'asistencia',
|
||||||
atencion: number,
|
gravedad,
|
||||||
extra: Partial<GroupRiskSummary> = {},
|
etiqueta: `${peso} faltas`,
|
||||||
): GroupRiskSummary => ({
|
detalle: '',
|
||||||
groupId: 'grp_1',
|
firma: 'ses_1',
|
||||||
groupName: 'Pilates',
|
peso,
|
||||||
riskLevel: riesgoAlto > 0 ? 'HIGH' : atencion > 0 ? 'MEDIUM' : 'NONE',
|
|
||||||
absenceStreakCount: riesgoAlto,
|
|
||||||
lowAttendanceCount: atencion,
|
|
||||||
riesgoAlto,
|
|
||||||
atencion,
|
|
||||||
ok: 0,
|
|
||||||
libres: 0,
|
|
||||||
enEspera: 0,
|
|
||||||
asistencia: 100,
|
|
||||||
urgentes: [],
|
|
||||||
...extra,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const urgente = (extra: Partial<UrgentMemberSummary> = {}): UrgentMemberSummary => ({
|
const miembro = (id: string, alerts: StudentAlert[] = []): AttentionMember => ({
|
||||||
attendeeId: 'at_1',
|
attendeeId: id,
|
||||||
fullName: 'Sofía Ramírez',
|
fullName: `Alumno ${id}`,
|
||||||
level: 'riesgo_alto',
|
phone: null,
|
||||||
consecutiveAbsences: 0,
|
whatsappPhone: null,
|
||||||
daysSinceLastAttendance: null,
|
alerts,
|
||||||
attendanceRate: null,
|
overduePayments: [],
|
||||||
...extra,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const grupo = (attendeesCount: number, capacity: number | null) => ({ attendeesCount, capacity })
|
const miembros = (count: number) => Array.from({ length: count }, (_, index) => miembro(`m${index + 1}`))
|
||||||
|
|
||||||
describe('GroupCard - Casos de prueba de referencia', () => {
|
describe('avatarRow', () => {
|
||||||
test('Caso 1: Tai Chi Martes (cupo 5, 4/5 miembros, 5 píldoras, alerta Sofía)', () => {
|
test('grupo chico: una cara por alumno y un círculo punteado por lugar libre', () => {
|
||||||
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[0], link: false }))
|
const row = avatarRow(miembros(1), 4)
|
||||||
|
expect(row.stacked).toBe(false)
|
||||||
// Fila 1: el nombre solo. El cupo no se repite: ya está en el "4/5"
|
expect(row.slots.map((slot) => slot.kind)).toEqual(['member', 'free', 'free', 'free'])
|
||||||
expect(markup).toContain('Tai Chi Martes')
|
|
||||||
|
|
||||||
// Fila 2: 4/5 en una sola línea y 5 píldoras individuales. La palabra
|
|
||||||
// "miembros" va en un span oculto en móvil: se lleva ~60px que la barra
|
|
||||||
// necesita para que las píldoras sigan siendo píldoras.
|
|
||||||
expect(markup).toContain('4/5')
|
|
||||||
expect(markup).toContain('shrink-0 whitespace-nowrap text-base tabular-nums text-secondary">4/5<span')
|
|
||||||
expect(markup).toContain('hidden sm:inline">')
|
|
||||||
|
|
||||||
// Píldoras individuales (Modo A: cupo <= 10)
|
|
||||||
// 1 rojo (high), 1 ámbar (attention), 2 azul (ok), 1 vacía (libres)
|
|
||||||
expect(markup).toContain('min-w-0 flex-1 max-w-[50px]')
|
|
||||||
expect(markup).toContain('bg-attendance-high')
|
|
||||||
expect(markup).toContain('bg-attendance-attention')
|
|
||||||
expect(markup).toContain('bg-attendance-ok')
|
|
||||||
|
|
||||||
// Fila 3: alerta roja con ícono de cuadrado
|
|
||||||
expect(markup).toContain('Sofía: 4 faltas · 1 en atención')
|
|
||||||
expect(markup).toContain('text-[#8B1A1A]')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('Caso 2: Pilates Sábado (cupo 15, 12/15 miembros, barra continua, alerta Sofía)', () => {
|
test(`hasta ${INLINE_SLOTS_MAX} lugares entra en una línea`, () => {
|
||||||
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[1], link: false }))
|
expect(avatarRow(miembros(2), INLINE_SLOTS_MAX).stacked).toBe(false)
|
||||||
|
expect(avatarRow(miembros(2), INLINE_SLOTS_MAX + 1).stacked).toBe(true)
|
||||||
// Fila 1: el nombre solo
|
|
||||||
expect(markup).toContain('Pilates Sábado')
|
|
||||||
|
|
||||||
// Fila 2
|
|
||||||
expect(markup).toContain('12/15<span')
|
|
||||||
|
|
||||||
// Modo B: barra continua (overflow-hidden rounded-full)
|
|
||||||
expect(markup).toContain('overflow-hidden rounded-full')
|
|
||||||
|
|
||||||
// Fila 3: alerta
|
|
||||||
expect(markup).toContain('Sofía: 4 faltas · 2 en atención')
|
|
||||||
expect(markup).toContain('text-[#8B1A1A]')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('Caso 3: Natación Adultos (cupo 30, 22/30 miembros, barra continua, alerta múltiple)', () => {
|
test('grupo grande: caras superpuestas y un "+N" con el resto', () => {
|
||||||
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[2], link: false }))
|
const row = avatarRow(miembros(30), 30)
|
||||||
|
expect(row.stacked).toBe(true)
|
||||||
// Fila 1: el nombre solo
|
expect(row.slots).toHaveLength(STACKED_FACES + 1)
|
||||||
expect(markup).toContain('Natación Adultos')
|
expect(row.slots.at(-1)).toEqual({ kind: 'more', count: 30 - STACKED_FACES })
|
||||||
|
|
||||||
// Fila 2
|
|
||||||
expect(markup).toContain('22/30<span')
|
|
||||||
|
|
||||||
// Modo B: barra continua
|
|
||||||
expect(markup).toContain('overflow-hidden rounded-full')
|
|
||||||
|
|
||||||
// Fila 3: alerta con 3 en riesgo alto y 4 en atención
|
|
||||||
expect(markup).toContain('3 en riesgo alto · 4 en atención')
|
|
||||||
expect(markup).toContain('text-[#8B1A1A]')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
/* La barra segmentada se llevaba el ancho con un `w-[50px] shrink-0` por
|
test('el "+N" cuenta la ocupación del grupo, no solo los activos', () => {
|
||||||
segmento. Con 10 segmentos eso son 554px (más los gaps) contra los ~197px que
|
// 28 activos con cara, pero 30 lugares ocupados (2 en pausa).
|
||||||
deja la tarjeta en un viewport de 402px: los hijos `shrink-0` se salían de la
|
const row = avatarRow(miembros(28), 30, 30)
|
||||||
caja y arrastraban al documento a un scroll horizontal en el iPhone. Estos
|
expect(row.slots.at(-1)).toEqual({ kind: 'more', count: 26 })
|
||||||
tests fijan la forma del arreglo — la barra reparte el ancho disponible y lo
|
})
|
||||||
recorta — para que nadie vuelva a poner un ancho fijo acá. */
|
|
||||||
describe('GroupCard - la barra nunca desborda la tarjeta', () => {
|
test('un grupo chico completo se superpone sin "+N"', () => {
|
||||||
const markupDeCupo = (capacity: number) =>
|
const row = avatarRow(miembros(5), 5)
|
||||||
renderToStaticMarkup(
|
expect(row.stacked).toBe(true)
|
||||||
createElement(GroupCardContent, {
|
expect(row.slots.map((slot) => slot.kind)).toEqual(['member', 'member', 'member', 'member', 'member'])
|
||||||
name: 'Tai Chi Martes',
|
})
|
||||||
capacity,
|
|
||||||
members: [{ id: 'a1', name: 'Sofía', status: 'ok', absences: 0 }],
|
test('los alumnos con alerta van primero, el más grave adelante, con su gravedad', () => {
|
||||||
}),
|
const row = avatarRow(
|
||||||
|
[miembro('ok-1'), miembro('vig', [alerta('vigilar')]), miembro('ok-2'), miembro('urg', [alerta('urgente', 3)])],
|
||||||
|
30,
|
||||||
)
|
)
|
||||||
|
const caras = row.slots.flatMap((slot) => (slot.kind === 'member' ? [[slot.member.attendeeId, slot.severity]] : []))
|
||||||
/* Las clases llegan sueltas en el markup, así que se tokenizan: un `w-[50px]`
|
expect(caras).toEqual([
|
||||||
suelto es el bug y un `max-w-[50px]` es el arreglo, y un regex que busque
|
['urg', 'urgente'],
|
||||||
"w-[50px]" no distingue uno del otro. */
|
['vig', 'vigilar'],
|
||||||
const clasesDe = (markup: string): string[] =>
|
['ok-1', null],
|
||||||
[...markup.matchAll(/class="([^"]*)"/g)].flatMap(([, clases]) => clases.split(/\s+/))
|
['ok-2', null],
|
||||||
|
])
|
||||||
test('el segmento no tiene ancho fijo: se reparte con flex y solo se topa', () => {
|
|
||||||
const clases = clasesDe(markupDeCupo(SEGMENTED_CAPACITY_MAX))
|
|
||||||
|
|
||||||
// `max-w` sí: un tope no desborda, el ancho disponible sigue mandando.
|
|
||||||
expect(clases).toContain('max-w-[50px]')
|
|
||||||
// `w-[...]` no: es lo que empujaba la pantalla. Cubre todo ancho fijo, no
|
|
||||||
// solo el de 50px que tenía antes. Ojo que `shrink-0` sí sigue en el
|
|
||||||
// markup, pero solo en el label ("N/M miembros" no puede partirse en dos
|
|
||||||
// líneas); lo que no puede volver es un ancho fijo en el segmento.
|
|
||||||
expect(clases.filter((clase) => /^w-\[/.test(clase))).toEqual([])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('el contenedor de la barra segmentada recorta en vez de desbordar', () => {
|
test('el render marca los lugares libres y el resto', () => {
|
||||||
expect(markupDeCupo(SEGMENTED_CAPACITY_MAX)).toContain('gap-1.5 overflow-hidden')
|
const chico = renderToStaticMarkup(createElement(AvatarRow, { members: miembros(1), capacity: 3, occupied: 1 }))
|
||||||
})
|
expect(chico.match(/border-dashed/g)).toHaveLength(2)
|
||||||
|
|
||||||
test('un grupo completo conserva ancho para mostrar todos sus segmentos', () => {
|
const grande = renderToStaticMarkup(createElement(AvatarRow, { members: miembros(30), capacity: 30, occupied: 30 }))
|
||||||
const members = Array.from({ length: 5 }, (_, index) => ({
|
expect(grande).toContain('+26')
|
||||||
id: `a${index}`,
|
expect(grande).toContain('-ml-1.5')
|
||||||
name: `Miembro ${index + 1}`,
|
|
||||||
status: 'ok' as const,
|
|
||||||
absences: 0,
|
|
||||||
}))
|
|
||||||
const markup = renderToStaticMarkup(
|
|
||||||
createElement(GroupCardContent, {
|
|
||||||
name: 'Grupo de Prueba',
|
|
||||||
capacity: 5,
|
|
||||||
members,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(markup).toContain(
|
|
||||||
'flex h-3.5 min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('el peor caso (cupo 10) no introduce ancho fijo ni scroll propio', () => {
|
|
||||||
const markup = markupDeCupo(SEGMENTED_CAPACITY_MAX)
|
|
||||||
const clases = clasesDe(markup)
|
|
||||||
|
|
||||||
expect(clases.filter((clase) => /^w-\[/.test(clase))).toEqual([])
|
|
||||||
// Un contenedor con overflow horizontal propio scrollea; la tarjeta no
|
|
||||||
// debe tener ninguno: el desborde tiene que resolverse repartiendo el ancho.
|
|
||||||
expect(markup).not.toContain('overflow-x-auto')
|
|
||||||
expect(markup).not.toContain('overflow-scroll')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('la barra continua (cupo > 10) también se queda dentro de la tarjeta', () => {
|
|
||||||
const markup = markupDeCupo(SEGMENTED_CAPACITY_MAX + 1)
|
|
||||||
|
|
||||||
expect(markup).toContain('flex-1 items-stretch overflow-hidden rounded-full')
|
|
||||||
expect(clasesDe(markup).filter((clase) => /^w-\[/.test(clase))).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
/* Todo el rango segmentado (hasta 10) se dibuja con una píldora por lugar,
|
|
||||||
aunque en el tope la píldora quede angosta. Ver cuál está libre y de qué
|
|
||||||
nivel es cada uno informa más que una barra proporcional, así que el
|
|
||||||
umbral baja a 7-10 no es una opción: lo que tiene que garantizarse es que
|
|
||||||
la píldora angosta entre igual, sin ancho fijo y sin desbordar. */
|
|
||||||
test('los cupos 7-10 conservan la píldora por lugar', () => {
|
|
||||||
for (const capacity of [7, 8, 9, 10]) {
|
|
||||||
const markup = markupDeCupo(capacity)
|
|
||||||
|
|
||||||
expect(markup).toContain('max-w-[50px]')
|
|
||||||
expect(markup).not.toContain('flex-1 items-stretch overflow-hidden rounded-full')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un cupo bajo conserva la píldora por lugar', () => {
|
|
||||||
for (const capacity of [3, 4, 5, 6]) {
|
|
||||||
const markup = markupDeCupo(capacity)
|
|
||||||
|
|
||||||
expect(markup).toContain('max-w-[50px]')
|
|
||||||
expect(markup).not.toContain('flex-1 items-stretch overflow-hidden rounded-full')
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('alertTextFromMembers', () => {
|
describe('groupStatus', () => {
|
||||||
test('con exactamente 1 miembro en riesgo alto muestra su nombre y faltas', () => {
|
test('con alertas dice cuántos están en riesgo, con el tono de la peor', () => {
|
||||||
const members: GroupMember[] = [
|
expect(groupStatus([miembro('a', [alerta('vigilar')]), miembro('b')], 4)).toEqual({
|
||||||
{ id: '1', name: 'Sofía Ramírez', status: 'high_risk', absences: 4 },
|
tone: 'vigilar',
|
||||||
{ id: '2', name: 'Lucas', status: 'attention', absences: 1 },
|
text: '1 en riesgo',
|
||||||
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
|
|
||||||
]
|
|
||||||
expect(alertTextFromMembers(members)).toBe('Sofía: 4 faltas · 1 en atención')
|
|
||||||
})
|
})
|
||||||
|
expect(groupStatus([miembro('a', [alerta('vigilar')]), miembro('b', [alerta('urgente')])], 2)).toEqual({
|
||||||
test('con exactamente 1 miembro en riesgo alto y sin atención', () => {
|
tone: 'urgente',
|
||||||
const members: GroupMember[] = [
|
text: '2 en riesgo',
|
||||||
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 1 },
|
|
||||||
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
|
|
||||||
]
|
|
||||||
expect(alertTextFromMembers(members)).toBe('Sofía: 1 falta')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('con 2 o más en riesgo alto resume por cantidad', () => {
|
|
||||||
const members: GroupMember[] = [
|
|
||||||
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 4 },
|
|
||||||
{ id: '2', name: 'Mateo', status: 'high_risk', absences: 2 },
|
|
||||||
{ id: '3', name: 'Lucas', status: 'attention', absences: 1 },
|
|
||||||
]
|
|
||||||
expect(alertTextFromMembers(members)).toBe('2 en riesgo alto · 1 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin riesgo alto pero con atención muestra solo atención', () => {
|
|
||||||
const members: GroupMember[] = [
|
|
||||||
{ id: '1', name: 'Lucas', status: 'attention', absences: 1 },
|
|
||||||
{ id: '2', name: 'Elena', status: 'attention', absences: 1 },
|
|
||||||
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
|
|
||||||
]
|
|
||||||
expect(alertTextFromMembers(members)).toBe('2 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin riesgo alto ni atención devuelve null y no renderiza fila de alerta', () => {
|
|
||||||
const members: GroupMember[] = [
|
|
||||||
{ id: '1', name: 'Lucas', status: 'ok', absences: 0 },
|
|
||||||
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
|
|
||||||
]
|
|
||||||
expect(alertTextFromMembers(members)).toBeNull()
|
|
||||||
|
|
||||||
const markup = renderToStaticMarkup(
|
|
||||||
createElement(GroupCard, {
|
|
||||||
name: 'Yoga Tranquilo',
|
|
||||||
capacity: 10,
|
|
||||||
members,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
expect(markup).not.toContain('text-[#8B1A1A]')
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('capacityCounts', () => {
|
test('sin alertas muestra los lugares libres, y si no hay, "Completo"', () => {
|
||||||
test('los lugares libres son los que faltan del cupo', () => {
|
expect(groupStatus(miembros(1), 4)).toEqual({ tone: 'free', text: '3 libres' })
|
||||||
expect(capacityCounts(grupo(4, 5), undefined).libres).toBe(1)
|
expect(groupStatus(miembros(3), 4)).toEqual({ tone: 'free', text: '1 libre' })
|
||||||
expect(capacityCounts(grupo(12, 20), undefined).libres).toBe(8)
|
expect(groupStatus(miembros(4), 4)).toEqual({ tone: 'full', text: 'Completo' })
|
||||||
})
|
})
|
||||||
|
|
||||||
test('lleno o de más da 0 libres, nunca negativos', () => {
|
test('sin cupo definido y sin alertas no hay estado', () => {
|
||||||
expect(capacityCounts(grupo(5, 5), undefined).libres).toBe(0)
|
expect(groupStatus(miembros(3), null)).toBeNull()
|
||||||
expect(capacityCounts(grupo(7, 5), undefined).libres).toBe(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin cupo definido no hay lugares que repartir', () => {
|
|
||||||
expect(capacityCounts(grupo(3, null), undefined).libres).toBe(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('ok es la diferencia: el resumen solo nombra a los que hay que mirar', () => {
|
|
||||||
const counts = capacityCounts(grupo(10, 20), risk(2, 3))
|
|
||||||
|
|
||||||
expect(counts).toEqual({ riesgoAlto: 2, atencion: 3, ok: 5, libres: 10 })
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin resumen, todo el grupo queda en calma y la barra se puede pintar', () => {
|
|
||||||
expect(capacityCounts(grupo(4, 5), undefined)).toEqual({
|
|
||||||
riesgoAlto: 0,
|
|
||||||
atencion: 0,
|
|
||||||
ok: 4,
|
|
||||||
libres: 1,
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('ok no se vuelve negativo si el resumen contara más gente que la matrícula', () => {
|
describe('groupsSummary', () => {
|
||||||
expect(capacityCounts(grupo(2, 5), risk(3, 1)).ok).toBe(0)
|
test('suma grupos, alumnos y lugares libres', () => {
|
||||||
|
expect(
|
||||||
|
groupsSummary([
|
||||||
|
{ attendeesCount: 1, capacity: 4 },
|
||||||
|
{ attendeesCount: 1, capacity: 5 },
|
||||||
|
{ attendeesCount: 30, capacity: 30 },
|
||||||
|
{ attendeesCount: 5, capacity: 5 },
|
||||||
|
]),
|
||||||
|
).toBe('4 grupos · 37 alumnos · 7 lugares libres')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('singular y grupos sin cupo o sobrecargados', () => {
|
||||||
|
expect(groupsSummary([{ attendeesCount: 1, capacity: 2 }])).toBe('1 grupo · 1 alumno · 1 lugar libre')
|
||||||
|
expect(
|
||||||
|
groupsSummary([
|
||||||
|
{ attendeesCount: 3, capacity: null },
|
||||||
|
{ attendeesCount: 6, capacity: 5 },
|
||||||
|
]),
|
||||||
|
).toBe('2 grupos · 9 alumnos · 0 lugares libres')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('isSegmentedCapacity', () => {
|
test('membersOf busca el grupo en el resumen de atención', () => {
|
||||||
test('hasta 10 lugares va un segmento por lugar', () => {
|
const groups = [{ groupId: 'g1', groupName: 'Yoga', capacity: 4, members: miembros(2) }]
|
||||||
expect(isSegmentedCapacity(4)).toBe(true)
|
expect(membersOf(groups, 'g1')).toHaveLength(2)
|
||||||
expect(isSegmentedCapacity(5)).toBe(true)
|
expect(membersOf(groups, 'g2')).toBeUndefined()
|
||||||
expect(isSegmentedCapacity(6)).toBe(true)
|
expect(membersOf(undefined, 'g1')).toBeUndefined()
|
||||||
// 7-10 también: aunque la píldora queda angosta, ver qué lugar está libre
|
|
||||||
// informa más que una barra proporcional.
|
|
||||||
expect(isSegmentedCapacity(7)).toBe(true)
|
|
||||||
expect(isSegmentedCapacity(10)).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('de 11 para arriba pasa a bloques proporcionales', () => {
|
|
||||||
expect(isSegmentedCapacity(11)).toBe(false)
|
|
||||||
expect(isSegmentedCapacity(30)).toBe(false)
|
|
||||||
expect(isSegmentedCapacity(100)).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin matrícula ni cupo no hay nada que repartir', () => {
|
|
||||||
expect(isSegmentedCapacity(0)).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('barCapacity', () => {
|
|
||||||
test('con cupo declarado, el indicador mide los lugares del cupo', () => {
|
|
||||||
expect(barCapacity(grupo(4, 5))).toBe(5)
|
|
||||||
expect(barCapacity(grupo(0, 30))).toBe(30)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin cupo, el indicador mide a la matrícula en vez de desaparecer', () => {
|
|
||||||
expect(barCapacity(grupo(4, null))).toBe(4)
|
|
||||||
expect(barCapacity(grupo(30, null))).toBe(30)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo sin cupo y sin gente no inventa un total', () => {
|
|
||||||
expect(barCapacity(grupo(0, null))).toBe(0)
|
|
||||||
expect(isSegmentedCapacity(barCapacity(grupo(0, null)))).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('riskTone', () => {
|
|
||||||
test('manda el peor nivel presente', () => {
|
|
||||||
expect(riskTone({ riesgoAlto: 1, atencion: 4, ok: 0, libres: 0 })).toBe('riesgo_alto')
|
|
||||||
expect(riskTone({ riesgoAlto: 0, atencion: 1, ok: 0, libres: 0 })).toBe('atencion')
|
|
||||||
expect(riskTone({ riesgoAlto: 0, atencion: 0, ok: 9, libres: 0 })).toBe('ok')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('statusLine', () => {
|
|
||||||
test('grupo chico: nombra al caso más urgente y resume los demás', () => {
|
|
||||||
const resumen = risk(1, 1, {
|
|
||||||
urgentes: [
|
|
||||||
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
|
|
||||||
urgente({
|
|
||||||
attendeeId: 'at_2',
|
|
||||||
fullName: 'Diego Soto',
|
|
||||||
level: 'atencion',
|
|
||||||
consecutiveAbsences: 2,
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(4, 5), resumen)).toEqual({
|
|
||||||
text: 'Sofía: 4 faltas · 1 en atención',
|
|
||||||
tone: 'riesgo_alto',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test('con tres personas en riesgo alto resume el total aunque el grupo sea chico', () => {
|
|
||||||
const resumen = risk(3, 0, {
|
|
||||||
urgentes: [
|
|
||||||
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
|
|
||||||
urgente({ attendeeId: 'at_2', fullName: 'Diego Soto', consecutiveAbsences: 3 }),
|
|
||||||
urgente({ attendeeId: 'at_3', fullName: 'Ana Ruiz', consecutiveAbsences: 3 }),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(4, 5), resumen).text).toBe('3 en riesgo alto')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('grupo grande: el conteo por nivel en vez de nombres', () => {
|
|
||||||
const resumen = risk(3, 4, { urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })] })
|
|
||||||
|
|
||||||
expect(statusLine(grupo(18, 20), resumen)).toEqual({
|
|
||||||
text: '3 en riesgo alto · 4 en atención',
|
|
||||||
tone: 'riesgo_alto',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test('con exactamente una persona en riesgo alto la nombra, sin importar el cupo', () => {
|
|
||||||
const resumen = risk(1, 2, {
|
|
||||||
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(12, 15), resumen).text).toBe('Sofía: 4 faltas · 2 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('con dos personas en riesgo alto resume por cantidad', () => {
|
|
||||||
const resumen = risk(2, 3, {
|
|
||||||
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(12, 15), resumen).text).toBe('2 en riesgo alto · 3 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('el singular se corrige solo', () => {
|
|
||||||
expect(statusLine(grupo(18, 20), risk(1, 0)).text).toBe('1 en riesgo alto')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo chico sin cupo también nombra a la gente', () => {
|
|
||||||
// Sin cupo la barra mide a la matrícula, así que 4 miembros dan 4 segmentos
|
|
||||||
// y la línea puede usar nombres igual que un grupo con cupo chico.
|
|
||||||
const resumen = risk(1, 0, {
|
|
||||||
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(4, null), resumen)).toEqual({
|
|
||||||
text: 'Sofía: 4 faltas',
|
|
||||||
tone: 'riesgo_alto',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo grande sin cupo cae al conteo', () => {
|
|
||||||
const resumen = risk(3, 4, {
|
|
||||||
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(18, null), resumen).text).toBe('3 en riesgo alto · 4 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('el motivo más útil va primero: las faltas, después el tiempo, después la asistencia', () => {
|
|
||||||
const resumen = risk(2, 1, {
|
|
||||||
urgentes: [
|
|
||||||
urgente({ consecutiveAbsences: 2, daysSinceLastAttendance: 30, attendanceRate: 40 }),
|
|
||||||
urgente({
|
|
||||||
attendeeId: 'at_2',
|
|
||||||
fullName: 'Diego Soto',
|
|
||||||
level: 'atencion',
|
|
||||||
consecutiveAbsences: 0,
|
|
||||||
daysSinceLastAttendance: 14,
|
|
||||||
attendanceRate: 60,
|
|
||||||
}),
|
|
||||||
urgente({
|
|
||||||
attendeeId: 'at_3',
|
|
||||||
fullName: 'Ana Ruiz',
|
|
||||||
level: 'atencion',
|
|
||||||
consecutiveAbsences: 0,
|
|
||||||
daysSinceLastAttendance: 0,
|
|
||||||
attendanceRate: 55,
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(statusLine(grupo(4, 5), resumen).text).toBe('2 en riesgo alto · 1 en atención')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin riesgo la línea se apaga con la asistencia', () => {
|
|
||||||
const resumen = risk(0, 0, { asistencia: 94 })
|
|
||||||
|
|
||||||
expect(statusLine(grupo(18, 20), resumen)).toEqual({ text: 'Asistencia 94%', tone: 'ok' })
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo sin clases registradas no muestra un 100% inventado', () => {
|
|
||||||
expect(statusLine(grupo(4, 5), risk(0, 0, { asistencia: null })).text).toBe('Sin clases registradas')
|
|
||||||
// Todavía sin resumen: la tarjeta tiene que poder pintar igual.
|
|
||||||
expect(statusLine(grupo(4, 5), undefined).text).toBe('Sin clases registradas')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('si el resumen no trajo a quién nombrar, el grupo chico cae al conteo', () => {
|
|
||||||
// Los urgentes vienen truncados a 5: si hay más gente en riesgo que eso,
|
|
||||||
// la línea no puede quedarse en blanco.
|
|
||||||
expect(statusLine(grupo(4, 5), risk(2, 0, { urgentes: [] })).text).toBe('2 en riesgo alto')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('occupancyLabel', () => {
|
|
||||||
test('con cupo muestra el uso sobre el total', () => {
|
|
||||||
expect(occupancyLabel(grupo(4, 5))).toBe('4/5 miembros')
|
|
||||||
expect(occupancyLabel(grupo(12, 20))).toBe('12/20 miembros')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('1/5 se lee en plural: la unidad es el lugar, no la persona', () => {
|
|
||||||
expect(occupancyLabel(grupo(1, 5))).toBe('1/5 miembros')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin cupo el texto es el conteo, y el singular se corrige', () => {
|
|
||||||
expect(occupancyLabel(grupo(3, null))).toBe('3 miembros')
|
|
||||||
expect(occupancyLabel(grupo(1, null))).toBe('1 miembro')
|
|
||||||
expect(occupancyLabel(grupo(0, null))).toBe('0 miembros')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo vacío con cupo se lee como cualquier otro', () => {
|
|
||||||
expect(occupancyLabel(grupo(0, 5))).toBe('0/5 miembros')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('capacitySegmentWidth', () => {
|
|
||||||
test('calcula cada segmento sobre el cupo y conserva el espacio libre', () => {
|
|
||||||
expect(capacitySegmentWidth(2, 15)).toBe('13.3333%')
|
|
||||||
expect(capacitySegmentWidth(3, 15)).toBe('20.0000%')
|
|
||||||
expect(capacitySegmentWidth(7, 15)).toBe('46.6667%')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('capacityIndicatorLabel', () => {
|
|
||||||
test('el aria-label repite toda la información de la barra', () => {
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 2, atencion: 2, ok: 0, libres: 1 }, 5)).toBe(
|
|
||||||
'4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención, 1 libre',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('omite los niveles que están en cero y el plural de libre', () => {
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 0, ok: 3, libres: 1 }, 5)).toBe(
|
|
||||||
'4 de 5 lugares ocupados: 1 en riesgo alto, 3 en ok, 1 libre',
|
|
||||||
)
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 5, libres: 0 }, 5)).toBe(
|
|
||||||
'5 de 5 lugares ocupados: 5 en ok',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('un grupo vacío se anuncia sin niveles, no como un error', () => {
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 10 }, 10)).toBe(
|
|
||||||
'0 de 10 lugares ocupados, 10 libres',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('sin cupo declarado se anuncia por miembros, no por lugares inventados', () => {
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 2, ok: 1, libres: 0 }, 4, false)).toBe(
|
|
||||||
'4 miembros: 1 en riesgo alto, 2 en atención, 1 en ok',
|
|
||||||
)
|
|
||||||
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 1, libres: 0 }, 1, false)).toBe(
|
|
||||||
'1 miembro: 1 en ok',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ describe('isImmersiveRoute', () => {
|
|||||||
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
|
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('"Requiere atención" arma su propia barra', () => {
|
||||||
|
expect(isImmersiveRoute('/groups/attention')).toBe(true)
|
||||||
|
expect(isImmersiveRoute('/groups/attention/analytics')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
test('el detalle de miembro también es immersive', () => {
|
test('el detalle de miembro también es immersive', () => {
|
||||||
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(true)
|
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(true)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ export * from './lib/attendance-risk.js';
|
|||||||
export * from './lib/phone.js';
|
export * from './lib/phone.js';
|
||||||
export * from './lib/problem-details.js';
|
export * from './lib/problem-details.js';
|
||||||
export * from './lib/result.js';
|
export * from './lib/result.js';
|
||||||
|
export * from './lib/student-alerts.js';
|
||||||
export * from './schemas/admin.js';
|
export * from './schemas/admin.js';
|
||||||
export * from './schemas/analytics.js';
|
export * from './schemas/analytics.js';
|
||||||
export * from './schemas/attendance.js';
|
export * from './schemas/attendance.js';
|
||||||
export * from './schemas/attendees.js';
|
export * from './schemas/attendees.js';
|
||||||
|
export * from './schemas/attention.js';
|
||||||
export * from './schemas/billing.js';
|
export * from './schemas/billing.js';
|
||||||
export * from './schemas/country.js';
|
export * from './schemas/country.js';
|
||||||
export * from './schemas/enums.js';
|
export * from './schemas/enums.js';
|
||||||
|
|||||||
@@ -36,26 +36,23 @@ export type AttendanceRiskLevel = AttendanceRiskLevelDto;
|
|||||||
/**
|
/**
|
||||||
* Thresholds of the risk rule. Moving these numbers changes the status light
|
* Thresholds of the risk rule. Moving these numbers changes the status light
|
||||||
* across the whole app, so this is the only source: nothing else hardcodes
|
* across the whole app, so this is the only source: nothing else hardcodes
|
||||||
* them.
|
* them. The windows count *marked* classes (PRESENT / ABSENT): an excused class
|
||||||
|
* or one with no record neither fills nor empties a window.
|
||||||
*/
|
*/
|
||||||
export const ATTENDANCE_RISK_RULES = {
|
export const ATTENDANCE_RISK_RULES = {
|
||||||
/** Unexcused absences in a streak from which the risk is high. */
|
/** Unexcused absences in a streak from which the risk is high. */
|
||||||
highAbsenceStreak: 3,
|
highAbsenceStreak: 3,
|
||||||
/** Unexcused absences in a streak from which attention is needed. */
|
/** Size of the long window: "4 of the last 6 classes". */
|
||||||
|
highWindowSize: 6,
|
||||||
|
/** Absences inside the long window from which the risk is high. */
|
||||||
|
highWindowAbsences: 4,
|
||||||
|
/** Size of the short window: "2 recent absences" = 2 of the last 4. */
|
||||||
|
attentionWindowSize: 4,
|
||||||
|
/** Absences inside the short window from which attention is needed. */
|
||||||
|
attentionWindowAbsences: 2,
|
||||||
|
/** Unexcused absences in a streak that read as "they stopped coming" rather
|
||||||
|
* than as scattered absences. Only splits the reason, not the level. */
|
||||||
attentionAbsenceStreak: 2,
|
attentionAbsenceStreak: 2,
|
||||||
/** Days since last showing up to a class from which the risk is high. */
|
|
||||||
highInactivityDays: 10,
|
|
||||||
/** Size of each trend window: 4 recent classes vs the 4 before them. */
|
|
||||||
trendWindowSize: 4,
|
|
||||||
/** Marked classes needed to evaluate the trend. With fewer than this
|
|
||||||
* (6 = 4 + 2) any movement is noise, not a trend. */
|
|
||||||
trendMinClasses: 6,
|
|
||||||
/** How many classes have to be lost between one window and the other for
|
|
||||||
* the trend to count as "clearly" dropping. Counted in classes and not in
|
|
||||||
* percentage points on purpose: with a window of 4 the smallest possible
|
|
||||||
* jump is already 25 points, so a threshold in points would not tell
|
|
||||||
* "they missed a class" apart from "they are leaving". Two classes do. */
|
|
||||||
trendDropClasses: 2,
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** A class of the group, seen from one attendee. */
|
/** A class of the group, seen from one attendee. */
|
||||||
@@ -98,8 +95,16 @@ export type MemberRiskSignals = {
|
|||||||
attendanceRate: number | null;
|
attendanceRate: number | null;
|
||||||
/** Marked classes a verdict can be based on. */
|
/** Marked classes a verdict can be based on. */
|
||||||
markedClasses: number;
|
markedClasses: number;
|
||||||
|
/** Absences over the last `highWindowSize` marked classes. */
|
||||||
|
highWindow: AbsenceWindow;
|
||||||
|
/** Absences over the last `attentionWindowSize` marked classes. */
|
||||||
|
attentionWindow: AbsenceWindow;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Absences inside the most recent marked classes. `classes` can be smaller
|
||||||
|
* than the window size when the attendee has less history. */
|
||||||
|
export type AbsenceWindow = { absences: number; classes: number };
|
||||||
|
|
||||||
export type UrgentMember = MemberRiskSignals & {
|
export type UrgentMember = MemberRiskSignals & {
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
fullName: string;
|
fullName: string;
|
||||||
@@ -168,33 +173,43 @@ export function summarizeMemberAttendance(
|
|||||||
const present = marked.filter((session) => session.status === 'PRESENT').length;
|
const present = marked.filter((session) => session.status === 'PRESENT').length;
|
||||||
const attendanceRate = marked.length ? Math.round((present / marked.length) * 100) : null;
|
const attendanceRate = marked.length ? Math.round((present / marked.length) * 100) : null;
|
||||||
|
|
||||||
const level = classify(consecutiveAbsences, missedSpanDays(sessions, lastAttendedAt), marked);
|
const highWindow = absenceWindow(marked, ATTENDANCE_RISK_RULES.highWindowSize);
|
||||||
|
const attentionWindow = absenceWindow(marked, ATTENDANCE_RISK_RULES.attentionWindowSize);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
level,
|
level: classify(consecutiveAbsences, highWindow, attentionWindow),
|
||||||
consecutiveAbsences,
|
consecutiveAbsences,
|
||||||
daysSinceLastAttendance,
|
daysSinceLastAttendance,
|
||||||
attendanceRate,
|
attendanceRate,
|
||||||
markedClasses: marked.length,
|
markedClasses: marked.length,
|
||||||
|
highWindow,
|
||||||
|
attentionWindow,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Verdict: first the streak and the inactivity, then the trend. */
|
/** Verdict: the streak and the long window decide "high", the short one "attention". */
|
||||||
function classify(
|
function classify(
|
||||||
consecutiveAbsences: number,
|
consecutiveAbsences: number,
|
||||||
missedDays: number | null,
|
highWindow: AbsenceWindow,
|
||||||
markedSessions: MemberClassSession[],
|
attentionWindow: AbsenceWindow,
|
||||||
): AttendanceRiskLevel {
|
): AttendanceRiskLevel {
|
||||||
const rules = ATTENDANCE_RISK_RULES;
|
const rules = ATTENDANCE_RISK_RULES;
|
||||||
const inactive = missedDays !== null && missedDays > rules.highInactivityDays;
|
if (consecutiveAbsences >= rules.highAbsenceStreak || highWindow.absences >= rules.highWindowAbsences) {
|
||||||
|
|
||||||
if (consecutiveAbsences >= rules.highAbsenceStreak || inactive) {
|
|
||||||
return 'riesgo_alto';
|
return 'riesgo_alto';
|
||||||
}
|
}
|
||||||
if (consecutiveAbsences >= rules.attentionAbsenceStreak) {
|
if (attentionWindow.absences >= rules.attentionWindowAbsences) {
|
||||||
return 'atencion';
|
return 'atencion';
|
||||||
}
|
}
|
||||||
return isDeclining(markedSessions) ? 'atencion' : 'ok';
|
return 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Absences over the last `size` marked classes (`marked` comes oldest to newest). */
|
||||||
|
function absenceWindow(marked: MemberClassSession[], size: number): AbsenceWindow {
|
||||||
|
const window = marked.slice(-size);
|
||||||
|
return {
|
||||||
|
absences: window.filter((session) => session.status === 'ABSENT').length,
|
||||||
|
classes: window.length,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -239,8 +254,8 @@ export function getGroupAttendanceSummary(
|
|||||||
};
|
};
|
||||||
|
|
||||||
/* Urgency order: worst level first; within the same level, whoever has more
|
/* Urgency order: worst level first; within the same level, whoever has more
|
||||||
consecutive absences, then whoever has gone the longest without showing
|
consecutive absences, then more absences in the long window, then whoever
|
||||||
up, then whoever has the lower attendance. The name never breaks the tie:
|
has gone the longest without showing up, then the lower attendance. The name never breaks the tie:
|
||||||
two people with the same signal keep the order they arrived in. */
|
two people with the same signal keep the order they arrived in. */
|
||||||
function byUrgency(a: UrgentMember, b: UrgentMember): number {
|
function byUrgency(a: UrgentMember, b: UrgentMember): number {
|
||||||
const level = levelWeight(b.level) - levelWeight(a.level);
|
const level = levelWeight(b.level) - levelWeight(a.level);
|
||||||
@@ -248,65 +263,15 @@ export function getGroupAttendanceSummary(
|
|||||||
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
|
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
|
||||||
return b.consecutiveAbsences - a.consecutiveAbsences;
|
return b.consecutiveAbsences - a.consecutiveAbsences;
|
||||||
}
|
}
|
||||||
|
if (a.highWindow.absences !== b.highWindow.absences) {
|
||||||
|
return b.highWindow.absences - a.highWindow.absences;
|
||||||
|
}
|
||||||
const inactivity = (b.daysSinceLastAttendance ?? 0) - (a.daysSinceLastAttendance ?? 0);
|
const inactivity = (b.daysSinceLastAttendance ?? 0) - (a.daysSinceLastAttendance ?? 0);
|
||||||
if (inactivity !== 0) return inactivity;
|
if (inactivity !== 0) return inactivity;
|
||||||
return (a.attendanceRate ?? 101) - (b.attendanceRate ?? 101);
|
return (a.attendanceRate ?? 101) - (b.attendanceRate ?? 101);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Attendance over the last 4 marked classes against the 4 before them. The
|
|
||||||
* drop-off is only declared when there is history for both windows: with one
|
|
||||||
* alone there is nothing to compare against, and guessing would flag attendees
|
|
||||||
* who are just starting out.
|
|
||||||
*
|
|
||||||
* With a window of 4, the smallest non-zero difference is one class, which is
|
|
||||||
* noise: that is why the threshold is `trendDropClasses` lost classes and not
|
|
||||||
* "any decrease".
|
|
||||||
*/
|
|
||||||
function isDeclining(sessions: MemberClassSession[]): boolean {
|
|
||||||
const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } =
|
|
||||||
ATTENDANCE_RISK_RULES;
|
|
||||||
if (sessions.length < minClasses) return false;
|
|
||||||
|
|
||||||
// `sessions` comes oldest to newest, so the recent window is the tail.
|
|
||||||
const recent = sessions.slice(-size);
|
|
||||||
const previous = sessions.slice(-size * 2, -size);
|
|
||||||
if (previous.length === 0 || recent.length === 0) return false;
|
|
||||||
|
|
||||||
return present(previous) - present(recent) >= dropClasses;
|
|
||||||
|
|
||||||
function present(window: MemberClassSession[]): number {
|
|
||||||
return window.filter((session) => session.status === 'PRESENT').length;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inactivity as the group lived it: days from the last presence (or, if they
|
|
||||||
* never came, from their first class) to the most recent class they missed.
|
|
||||||
* It is measured against the classes and not against today on purpose: if the
|
|
||||||
* group stopped meeting, or nobody recorded attendance, those days are the
|
|
||||||
* group's, not the attendee's. Without this, a group that went 10 days without
|
|
||||||
* recording a class turned all its members red at once. `null` when they have
|
|
||||||
* not missed any class since their last presence.
|
|
||||||
*/
|
|
||||||
function missedSpanDays(
|
|
||||||
sessions: MemberClassSession[],
|
|
||||||
lastAttendedAt: string | undefined,
|
|
||||||
): number | null {
|
|
||||||
let lastMissedAt: string | undefined;
|
|
||||||
for (let index = sessions.length - 1; index >= 0; index -= 1) {
|
|
||||||
if (sessions[index].status === 'ABSENT') {
|
|
||||||
lastMissedAt = sessions[index].startsAt;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const from = lastAttendedAt ?? sessions[0]?.startsAt;
|
|
||||||
if (!lastMissedAt || !from) return null;
|
|
||||||
const span = new Date(lastMissedAt).getTime() - new Date(from).getTime();
|
|
||||||
return span > 0 ? Math.floor(span / DAY_MS) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Start of the most recent class with presence, or `undefined` if they have none. */
|
/** Start of the most recent class with presence, or `undefined` if they have none. */
|
||||||
function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
|
function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
|
||||||
for (let index = sessions.length - 1; index >= 0; index -= 1) {
|
for (let index = sessions.length - 1; index >= 0; index -= 1) {
|
||||||
|
|||||||
194
packages/shared/src/lib/student-alerts.ts
Normal file
194
packages/shared/src/lib/student-alerts.ts
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
import type {
|
||||||
|
OverduePayment,
|
||||||
|
StudentAlert,
|
||||||
|
StudentAlertSeverity,
|
||||||
|
StudentAlertType,
|
||||||
|
} from '../schemas/attention.js';
|
||||||
|
import {
|
||||||
|
ATTENDANCE_RISK_RULES,
|
||||||
|
type MemberAttendance,
|
||||||
|
summarizeMemberAttendance,
|
||||||
|
} from './attendance-risk.js';
|
||||||
|
|
||||||
|
/* The alerts of one attendee, for the Grupos list and the "Requiere atención"
|
||||||
|
screen. Attendance reuses the single risk rule (`attendance-risk.ts`):
|
||||||
|
`riesgo_alto` is "urgente" and `atencion` is "vigilar", so a student can't be
|
||||||
|
urgent here and fine on Home. Payments only add their own threshold. */
|
||||||
|
|
||||||
|
/** Overdue-fee thresholds. The attendance ones live in `ATTENDANCE_RISK_RULES`. */
|
||||||
|
export const STUDENT_ALERT_RULES = {
|
||||||
|
/** Overdue fees from which the alert is urgent. */
|
||||||
|
urgentOverdue: 2,
|
||||||
|
/** Overdue fees from which the alert asks to keep an eye on it. */
|
||||||
|
watchOverdue: 1,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type StudentAlertInput = {
|
||||||
|
attendance: MemberAttendance;
|
||||||
|
overduePayments: Pick<OverduePayment, 'id' | 'dueDate'>[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AlertResolution = { tipo: StudentAlertType; firma: string };
|
||||||
|
|
||||||
|
const MONTHS = [
|
||||||
|
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio',
|
||||||
|
'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Every alert of the attendee, worst first. Empty when everything is fine. */
|
||||||
|
export function computeStudentAlerts(input: StudentAlertInput, now: Date = new Date()): StudentAlert[] {
|
||||||
|
const alerts: StudentAlert[] = [];
|
||||||
|
const attendance = attendanceAlert(input.attendance, now);
|
||||||
|
if (attendance) alerts.push(attendance);
|
||||||
|
const payment = paymentAlert(input.overduePayments);
|
||||||
|
if (payment) alerts.push(payment);
|
||||||
|
return alerts.sort(compareAlerts);
|
||||||
|
}
|
||||||
|
|
||||||
|
function attendanceAlert(member: MemberAttendance, now: Date): StudentAlert | null {
|
||||||
|
const signals = summarizeMemberAttendance(member, now);
|
||||||
|
if (signals.level === 'ok') return null;
|
||||||
|
|
||||||
|
const firma = lastAbsenceId(member, now);
|
||||||
|
if (!firma) return null;
|
||||||
|
|
||||||
|
const { consecutiveAbsences: streak, highWindow, attentionWindow } = signals;
|
||||||
|
|
||||||
|
if (signals.level === 'riesgo_alto') {
|
||||||
|
// The streak is the clearer story ("hace 3 clases que no viene"), so it
|
||||||
|
// wins over the window when both fire.
|
||||||
|
if (streak >= ATTENDANCE_RISK_RULES.highAbsenceStreak) {
|
||||||
|
return {
|
||||||
|
tipo: 'asistencia',
|
||||||
|
gravedad: 'urgente',
|
||||||
|
etiqueta: `${streak} seguidas`,
|
||||||
|
detalle: `No viene hace ${streak} clases seguidas.`,
|
||||||
|
firma,
|
||||||
|
peso: streak,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
tipo: 'asistencia',
|
||||||
|
gravedad: 'urgente',
|
||||||
|
etiqueta: `${highWindow.absences} faltas`,
|
||||||
|
detalle: `Faltó a ${highWindow.absences} de las últimas ${highWindow.classes} clases.`,
|
||||||
|
firma,
|
||||||
|
peso: highWindow.absences,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const { absences, classes } = attentionWindow;
|
||||||
|
return {
|
||||||
|
tipo: 'asistencia',
|
||||||
|
gravedad: 'vigilar',
|
||||||
|
etiqueta: `${absences} faltas`,
|
||||||
|
// When the absences are exactly the trailing streak, say so plainly.
|
||||||
|
detalle:
|
||||||
|
absences === streak
|
||||||
|
? `Faltó a las últimas ${absences} clases.`
|
||||||
|
: `Faltó a ${absences} de las últimas ${classes} clases.`,
|
||||||
|
firma,
|
||||||
|
peso: absences,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function paymentAlert(payments: StudentAlertInput['overduePayments']): StudentAlert | null {
|
||||||
|
const count = payments.length;
|
||||||
|
if (count < STUDENT_ALERT_RULES.watchOverdue) return null;
|
||||||
|
|
||||||
|
const sorted = [...payments].sort((a, b) => a.dueDate.localeCompare(b.dueDate));
|
||||||
|
const firma = sorted.map((payment) => payment.id).sort().join(',');
|
||||||
|
|
||||||
|
if (count >= STUDENT_ALERT_RULES.urgentOverdue) {
|
||||||
|
const months = [...new Set(sorted.map((payment) => monthName(payment.dueDate)))];
|
||||||
|
return {
|
||||||
|
tipo: 'pago',
|
||||||
|
gravedad: 'urgente',
|
||||||
|
etiqueta: `${count} cuotas`,
|
||||||
|
// Two fees in the same month (a re-created link) would read "las cuotas
|
||||||
|
// de octubre": fall back to the count.
|
||||||
|
detalle:
|
||||||
|
months.length === count
|
||||||
|
? `Debe las cuotas de ${joinList(months)}.`
|
||||||
|
: `Debe ${count} cuotas vencidas.`,
|
||||||
|
firma,
|
||||||
|
peso: count,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const [payment] = sorted;
|
||||||
|
return {
|
||||||
|
tipo: 'pago',
|
||||||
|
gravedad: 'vigilar',
|
||||||
|
etiqueta: 'Cuota vencida',
|
||||||
|
detalle: `La cuota de ${monthName(payment.dueDate)} venció el ${dayMonth(payment.dueDate)}.`,
|
||||||
|
firma,
|
||||||
|
peso: count,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drops the alerts the professor already marked as resolved, as long as
|
||||||
|
* nothing changed since (same type and same signature). */
|
||||||
|
export function applyResolutions(alerts: StudentAlert[], resolutions: AlertResolution[]): StudentAlert[] {
|
||||||
|
return alerts.filter(
|
||||||
|
(alert) => !resolutions.some((resolved) => resolved.tipo === alert.tipo && resolved.firma === alert.firma),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Worst first: severity, then strength of the signal. Ties keep their order. */
|
||||||
|
export function compareAlerts(a: StudentAlert, b: StudentAlert): number {
|
||||||
|
const severity = severityWeight(b.gravedad) - severityWeight(a.gravedad);
|
||||||
|
if (severity !== 0) return severity;
|
||||||
|
return b.peso - a.peso;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The alert that represents the attendee where only one fits, or `null`. */
|
||||||
|
export function worstAlert(alerts: StudentAlert[]): StudentAlert | null {
|
||||||
|
return [...alerts].sort(compareAlerts)[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Orders attendees by their worst alert, then by name. */
|
||||||
|
export function compareByWorstAlert<T extends { fullName: string; alerts: StudentAlert[] }>(a: T, b: T): number {
|
||||||
|
const worstA = worstAlert(a.alerts);
|
||||||
|
const worstB = worstAlert(b.alerts);
|
||||||
|
if (worstA && worstB) {
|
||||||
|
const byAlert = compareAlerts(worstA, worstB);
|
||||||
|
if (byAlert !== 0) return byAlert;
|
||||||
|
} else if (worstA || worstB) {
|
||||||
|
return worstA ? -1 : 1;
|
||||||
|
}
|
||||||
|
return a.fullName.localeCompare(b.fullName, 'es');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function severityWeight(severity: StudentAlertSeverity): number {
|
||||||
|
return severity === 'urgente' ? 2 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Most recent past ABSENT class after enrollment: the attendance signature. */
|
||||||
|
function lastAbsenceId(member: MemberAttendance, now: Date): string | null {
|
||||||
|
const enrolledAt = new Date(member.enrolledAt).getTime();
|
||||||
|
let latest: { id: string; at: number } | null = null;
|
||||||
|
for (const session of member.sessions) {
|
||||||
|
if (session.status !== 'ABSENT') continue;
|
||||||
|
const at = new Date(session.startsAt).getTime();
|
||||||
|
if (at > now.getTime() || at < enrolledAt) continue;
|
||||||
|
if (!latest || at > latest.at) latest = { id: session.sessionId, at };
|
||||||
|
}
|
||||||
|
return latest?.id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// `dueDate` is a calendar date the web sends at 12:00 UTC: reading it in UTC
|
||||||
|
// keeps the day the professor picked, whatever the server's time zone.
|
||||||
|
function monthName(iso: string): string {
|
||||||
|
return MONTHS[new Date(iso).getUTCMonth()];
|
||||||
|
}
|
||||||
|
|
||||||
|
function dayMonth(iso: string): string {
|
||||||
|
const date = new Date(iso);
|
||||||
|
return `${date.getUTCDate()}/${date.getUTCMonth() + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function joinList(items: string[]): string {
|
||||||
|
if (items.length <= 1) return items.join('');
|
||||||
|
return `${items.slice(0, -1).join(', ')} y ${items.at(-1)}`;
|
||||||
|
}
|
||||||
72
packages/shared/src/schemas/attention.ts
Normal file
72
packages/shared/src/schemas/attention.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const isoDateTimeSchema = z.string().datetime();
|
||||||
|
|
||||||
|
/* "Requiere atención": per-attendee alerts that the Grupos list and the
|
||||||
|
"Ver todos" screen read from the same endpoint. The rule that produces them
|
||||||
|
lives in `lib/student-alerts.ts`; this file only describes the transport. */
|
||||||
|
|
||||||
|
export const studentAlertTypeSchema = z.enum(['asistencia', 'pago']);
|
||||||
|
export type StudentAlertType = z.output<typeof studentAlertTypeSchema>;
|
||||||
|
|
||||||
|
export const studentAlertSeveritySchema = z.enum(['urgente', 'vigilar']);
|
||||||
|
export type StudentAlertSeverity = z.output<typeof studentAlertSeveritySchema>;
|
||||||
|
|
||||||
|
export const StudentAlertSchema = z.object({
|
||||||
|
tipo: studentAlertTypeSchema,
|
||||||
|
gravedad: studentAlertSeveritySchema,
|
||||||
|
/** Short reason for the pill: "4 faltas", "Cuota vencida". */
|
||||||
|
etiqueta: z.string(),
|
||||||
|
/** Natural-language line: "Faltó a 4 de las últimas 6 clases." */
|
||||||
|
detalle: z.string(),
|
||||||
|
/** What the alert is about (last absence / overdue payments). "Resuelto"
|
||||||
|
* stores it, so a new absence or a new overdue fee brings the alert back. */
|
||||||
|
firma: z.string(),
|
||||||
|
/** How strong the signal is inside its severity (absences, overdue fees);
|
||||||
|
* only used to order. */
|
||||||
|
peso: z.number().int().min(0),
|
||||||
|
});
|
||||||
|
export type StudentAlert = z.output<typeof StudentAlertSchema>;
|
||||||
|
|
||||||
|
export const OverduePaymentSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
amount: z.number(),
|
||||||
|
currency: z.string(),
|
||||||
|
dueDate: isoDateTimeSchema,
|
||||||
|
checkoutUrl: z.string().nullable(),
|
||||||
|
});
|
||||||
|
export type OverduePayment = z.output<typeof OverduePaymentSchema>;
|
||||||
|
|
||||||
|
export const AttentionMemberSchema = z.object({
|
||||||
|
attendeeId: z.string(),
|
||||||
|
fullName: z.string(),
|
||||||
|
/** `phone ?? guardianPhone`, as stored (national format). */
|
||||||
|
phone: z.string().nullable(),
|
||||||
|
/** The same phone in E.164 with the professor's country, ready for `wa.me`;
|
||||||
|
* `null` when it can't be normalized. */
|
||||||
|
whatsappPhone: z.string().nullable(),
|
||||||
|
/** Already filtered by "Resuelto" and ordered worst first. */
|
||||||
|
alerts: z.array(StudentAlertSchema),
|
||||||
|
overduePayments: z.array(OverduePaymentSchema),
|
||||||
|
});
|
||||||
|
export type AttentionMember = z.output<typeof AttentionMemberSchema>;
|
||||||
|
|
||||||
|
export const AttentionGroupSchema = z.object({
|
||||||
|
groupId: z.string(),
|
||||||
|
groupName: z.string(),
|
||||||
|
capacity: z.number().int().nullable(),
|
||||||
|
/** Every ACTIVE member, with or without alerts (the card draws them all). */
|
||||||
|
members: z.array(AttentionMemberSchema),
|
||||||
|
});
|
||||||
|
export type AttentionGroup = z.output<typeof AttentionGroupSchema>;
|
||||||
|
|
||||||
|
export const AttentionOverviewSchema = z.object({
|
||||||
|
groups: z.array(AttentionGroupSchema),
|
||||||
|
});
|
||||||
|
export type AttentionOverview = z.output<typeof AttentionOverviewSchema>;
|
||||||
|
|
||||||
|
export const ResolveAlertSchema = z.strictObject({
|
||||||
|
tipo: studentAlertTypeSchema,
|
||||||
|
firma: z.string().min(1),
|
||||||
|
});
|
||||||
|
export type ResolveAlert = z.output<typeof ResolveAlertSchema>;
|
||||||
Reference in New Issue
Block a user