Merge pull request 'feat/improve-ui' (#11) from feat/improve-ui into development
Reviewed-on: #11
This commit is contained in:
17
AGENTS.md
17
AGENTS.md
@@ -31,7 +31,8 @@ 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.
|
||||||
|
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
||||||
- `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).
|
||||||
@@ -64,6 +65,17 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||||
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||||
|
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/acceso`, `/alumno/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
|
||||||
|
1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`.
|
||||||
|
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
||||||
|
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
||||||
|
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
||||||
|
5. Autorización: todo pasa por `findLinkedAttendee` (attendee vinculado a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. Vincular tutores a varios hijos (N:N en `student_account_attendees`) es solo del lado profe y **todavía no tiene UI**.
|
||||||
|
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
||||||
|
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
||||||
|
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
||||||
|
9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`).
|
||||||
|
10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`.
|
||||||
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||||
|
|
||||||
## Convenciones repo-específicas
|
## Convenciones repo-específicas
|
||||||
@@ -74,13 +86,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
|
||||||
|
|
||||||
|
|||||||
@@ -74,3 +74,23 @@ KAPSO_WEBHOOK_URL=""
|
|||||||
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
|
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
|
||||||
KAPSO_WEBHOOK_SECRET=""
|
KAPSO_WEBHOOK_SECRET=""
|
||||||
# KAPSO_API_URL="https://api.kapso.ai"
|
# KAPSO_API_URL="https://api.kapso.ai"
|
||||||
|
|
||||||
|
# App de alumnos (acceso sin contraseña por link de un solo uso; ver AGENTS.md).
|
||||||
|
# Comprobantes de pago: storage privado compatible con S3 (RustFS, MinIO, R2, AWS).
|
||||||
|
# Sin estas cuatro variables, "Informar pago" responde 503 storage_not_available.
|
||||||
|
S3_ENDPOINT="http://localhost:9000"
|
||||||
|
S3_BUCKET="gruperly-receipts"
|
||||||
|
S3_ACCESS_KEY_ID=""
|
||||||
|
S3_SECRET_ACCESS_KEY=""
|
||||||
|
S3_REGION="us-east-1"
|
||||||
|
# on = URLs estilo AWS (bucket.endpoint). RustFS/MinIO usan path-style: dejalo vacío.
|
||||||
|
S3_VIRTUAL_HOSTED=""
|
||||||
|
# Días que se guarda un comprobante después de que el profe lo revisó. 0 = para siempre.
|
||||||
|
RECEIPT_RETENTION_DAYS="0"
|
||||||
|
# WebAuthn (Face ID / huella del alumno). Por defecto salen de WEB_URL; cambialos
|
||||||
|
# solo si la web se sirve desde otro origen (p. ej. un túnel para probar en el teléfono).
|
||||||
|
# WEBAUTHN_RP_ID="localhost"
|
||||||
|
# WEBAUTHN_ORIGIN="http://localhost:6173"
|
||||||
|
# Proxies delante de la API que agregan X-Forwarded-For (1 = solo nginx; 2 = Traefik + nginx).
|
||||||
|
# Define qué IP cuenta para el rate limit de "Pedir un link a mi mail".
|
||||||
|
TRUSTED_PROXY_HOPS="1"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"build": "prisma generate && tsc",
|
"build": "prisma generate && tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "bun test",
|
"test": "bun test",
|
||||||
|
"test:db": "DB_TESTS=1 bun test test/db",
|
||||||
"test:watch": "bun test --watch",
|
"test:watch": "bun test --watch",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
"lint:fix": "biome check . --write",
|
"lint:fix": "biome check . --write",
|
||||||
@@ -23,6 +24,7 @@
|
|||||||
"@gruperly/shared": "workspace:*",
|
"@gruperly/shared": "workspace:*",
|
||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
|
"@simplewebauthn/server": "13.3.3",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
"dotenv": "^16.4.5",
|
"dotenv": "^16.4.5",
|
||||||
"hono": "^4.13.3",
|
"hono": "^4.13.3",
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "StudentTokenKind" AS ENUM ('INVITATION', 'RECOVERY', 'EMAIL_CONFIRMATION');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "WebauthnChallengePurpose" AS ENUM ('REGISTER', 'LOGIN');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "AbsenceReason" AS ENUM ('HEALTH', 'TRAVEL', 'WORK_STUDY', 'OTHER');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "ReportedPaymentStatus" AS ENUM ('REPORTED', 'CONFIRMED', 'REJECTED');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "users" ADD COLUMN "transfer_alias" TEXT,
|
||||||
|
ADD COLUMN "transfer_holder" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_accounts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"recovery_email" TEXT,
|
||||||
|
"recovery_email_verified_at" TIMESTAMP(3),
|
||||||
|
"pending_recovery_email" TEXT,
|
||||||
|
"welcomed_at" TIMESTAMP(3),
|
||||||
|
"created_by_id" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "student_accounts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_account_attendees" (
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"attendee_id" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "student_account_attendees_pkey" PRIMARY KEY ("account_id","attendee_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_access_tokens" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"token_hash" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"kind" "StudentTokenKind" NOT NULL,
|
||||||
|
"email" TEXT,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"used_at" TIMESTAMP(3),
|
||||||
|
"revoked_at" TIMESTAMP(3),
|
||||||
|
"created_by_id" TEXT,
|
||||||
|
"used_ip" TEXT,
|
||||||
|
"used_user_agent" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "student_access_tokens_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_sessions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"token_hash" TEXT NOT NULL,
|
||||||
|
"device" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"revoked_at" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "student_sessions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_passkeys" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"credential_id" TEXT NOT NULL,
|
||||||
|
"public_key" BYTEA NOT NULL,
|
||||||
|
"counter" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"transports" TEXT[],
|
||||||
|
"device" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"last_used_at" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "student_passkeys_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "student_webauthn_challenges" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"challenge" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT,
|
||||||
|
"purpose" "WebauthnChallengePurpose" NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "student_webauthn_challenges_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "rate_limit_events" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "rate_limit_events_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "absence_notices" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"attendee_id" TEXT NOT NULL,
|
||||||
|
"class_session_id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT,
|
||||||
|
"reason" "AbsenceReason",
|
||||||
|
"message" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"cancelled_at" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "absence_notices_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "reported_payments" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"attendee_id" TEXT NOT NULL,
|
||||||
|
"group_id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT,
|
||||||
|
"total_amount" DECIMAL(10,2) NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"receipt_key" TEXT,
|
||||||
|
"receipt_mime" TEXT NOT NULL,
|
||||||
|
"receipt_name" TEXT NOT NULL,
|
||||||
|
"receipt_size" INTEGER NOT NULL,
|
||||||
|
"status" "ReportedPaymentStatus" NOT NULL DEFAULT 'REPORTED',
|
||||||
|
"reviewed_by_id" TEXT,
|
||||||
|
"reviewed_at" TIMESTAMP(3),
|
||||||
|
"rejection_reason" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "reported_payments_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "reported_payment_items" (
|
||||||
|
"reported_payment_id" TEXT NOT NULL,
|
||||||
|
"payment_id" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "reported_payment_items_pkey" PRIMARY KEY ("reported_payment_id","payment_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_accounts_recovery_email_idx" ON "student_accounts"("recovery_email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_accounts_created_by_id_idx" ON "student_accounts"("created_by_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_account_attendees_attendee_id_idx" ON "student_account_attendees"("attendee_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "student_access_tokens_token_hash_key" ON "student_access_tokens"("token_hash");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_access_tokens_account_id_kind_idx" ON "student_access_tokens"("account_id", "kind");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "student_sessions_token_hash_key" ON "student_sessions"("token_hash");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_sessions_account_id_idx" ON "student_sessions"("account_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "student_passkeys_credential_id_key" ON "student_passkeys"("credential_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_passkeys_account_id_idx" ON "student_passkeys"("account_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "student_webauthn_challenges_expires_at_idx" ON "student_webauthn_challenges"("expires_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "rate_limit_events_key_created_at_idx" ON "rate_limit_events"("key", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "absence_notices_attendee_id_class_session_id_idx" ON "absence_notices"("attendee_id", "class_session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "absence_notices_class_session_id_idx" ON "absence_notices"("class_session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "reported_payments_group_id_status_idx" ON "reported_payments"("group_id", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "reported_payments_attendee_id_idx" ON "reported_payments"("attendee_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "reported_payment_items_payment_id_idx" ON "reported_payment_items"("payment_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_accounts" ADD CONSTRAINT "student_accounts_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_access_tokens" ADD CONSTRAINT "student_access_tokens_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_sessions" ADD CONSTRAINT "student_sessions_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_passkeys" ADD CONSTRAINT "student_passkeys_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "student_webauthn_challenges" ADD CONSTRAINT "student_webauthn_challenges_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_class_session_id_fkey" FOREIGN KEY ("class_session_id") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_reported_payment_id_fkey" FOREIGN KEY ("reported_payment_id") REFERENCES "reported_payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_payment_id_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- At most one active (not cancelled) absence notice per attendee and class.
|
||||||
|
-- Partial index: Prisma can't express it in the schema.
|
||||||
|
CREATE UNIQUE INDEX "absence_notices_active_attendee_class_key" ON "absence_notices"("attendee_id", "class_session_id") WHERE "cancelled_at" IS NULL;
|
||||||
@@ -13,9 +13,10 @@ model ClassSession {
|
|||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
|
||||||
attendances Attendance[]
|
attendances Attendance[]
|
||||||
slotReleases SlotRelease[]
|
slotReleases SlotRelease[]
|
||||||
|
absenceNotices AbsenceNotice[]
|
||||||
|
|
||||||
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
|
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
|
||||||
@@map("class_sessions")
|
@@map("class_sessions")
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ model User {
|
|||||||
country String? @map("country_code")
|
country String? @map("country_code")
|
||||||
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
||||||
planSelectedAt DateTime? @map("plan_selected_at")
|
planSelectedAt DateTime? @map("plan_selected_at")
|
||||||
|
// Bank transfer details shown to students when they report a payment.
|
||||||
|
transferAlias String? @map("transfer_alias")
|
||||||
|
transferHolder String? @map("transfer_holder")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@ -24,6 +27,7 @@ model User {
|
|||||||
mpAccount MpAccount?
|
mpAccount MpAccount?
|
||||||
whatsappAccount WhatsappAccount?
|
whatsappAccount WhatsappAccount?
|
||||||
subscription BillingSubscription?
|
subscription BillingSubscription?
|
||||||
|
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ model Group {
|
|||||||
preRegistrations GroupPreRegistration[]
|
preRegistrations GroupPreRegistration[]
|
||||||
classSessions ClassSession[]
|
classSessions ClassSession[]
|
||||||
outboundMessages OutboundMessage[]
|
outboundMessages OutboundMessage[]
|
||||||
|
reportedPayments ReportedPayment[]
|
||||||
|
|
||||||
@@map("groups")
|
@@map("groups")
|
||||||
}
|
}
|
||||||
@@ -85,16 +86,42 @@ model Attendee {
|
|||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
||||||
payments Payment[]
|
payments Payment[]
|
||||||
attendances Attendance[]
|
attendances Attendance[]
|
||||||
slotReleases SlotRelease[]
|
slotReleases SlotRelease[]
|
||||||
outboundMessages OutboundMessage[]
|
outboundMessages OutboundMessage[]
|
||||||
|
alertResolutions AttendeeAlertResolution[]
|
||||||
|
studentAccounts StudentAccountAttendee[]
|
||||||
|
absenceNotices AbsenceNotice[]
|
||||||
|
reportedPayments ReportedPayment[]
|
||||||
|
|
||||||
@@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")
|
||||||
@@ -111,9 +138,10 @@ model Payment {
|
|||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
|
||||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
|
||||||
outboundMessages OutboundMessage[]
|
outboundMessages OutboundMessage[]
|
||||||
|
reportedItems ReportedPaymentItem[]
|
||||||
|
|
||||||
@@index([groupId], map: "payments_groupId_idx")
|
@@index([groupId], map: "payments_groupId_idx")
|
||||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||||
|
|||||||
235
apps/backend/prisma/models/student-access.prisma
Normal file
235
apps/backend/prisma/models/student-access.prisma
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
// Student access (attendees or their guardians), without passwords.
|
||||||
|
//
|
||||||
|
// The teacher sends a single-use invitation link over WhatsApp; consuming it
|
||||||
|
// creates a long sliding session on that device. Passkeys and a recovery email
|
||||||
|
// are optional and let the student get back in without the teacher. None of
|
||||||
|
// this goes through Better Auth: students have no mandatory email and their
|
||||||
|
// session must never pass the teacher's endpoints (separate cookie and
|
||||||
|
// middleware under /api/v1/student).
|
||||||
|
|
||||||
|
// The person who signs in: the attendee or a guardian. Linked to one or more
|
||||||
|
// attendees (a guardian may have several children), always by the teacher.
|
||||||
|
model StudentAccount {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
name String
|
||||||
|
// Verified recovery email (the student loads it, optional).
|
||||||
|
recoveryEmail String? @map("recovery_email")
|
||||||
|
recoveryEmailVerifiedAt DateTime? @map("recovery_email_verified_at")
|
||||||
|
// Email waiting for its confirmation link; never used to recover.
|
||||||
|
pendingRecoveryEmail String? @map("pending_recovery_email")
|
||||||
|
// First sign-in done: the welcome screen is shown only once.
|
||||||
|
welcomedAt DateTime? @map("welcomed_at")
|
||||||
|
createdById String @map("created_by_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
|
||||||
|
attendees StudentAccountAttendee[]
|
||||||
|
tokens StudentAccessToken[]
|
||||||
|
sessions StudentSession[]
|
||||||
|
passkeys StudentPasskey[]
|
||||||
|
challenges StudentWebauthnChallenge[]
|
||||||
|
absenceNotices AbsenceNotice[]
|
||||||
|
reportedPayments ReportedPayment[]
|
||||||
|
|
||||||
|
@@index([recoveryEmail])
|
||||||
|
@@index([createdById])
|
||||||
|
@@map("student_accounts")
|
||||||
|
}
|
||||||
|
|
||||||
|
model StudentAccountAttendee {
|
||||||
|
accountId String @map("account_id")
|
||||||
|
attendeeId String @map("attendee_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([accountId, attendeeId])
|
||||||
|
@@index([attendeeId])
|
||||||
|
@@map("student_account_attendees")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StudentTokenKind {
|
||||||
|
INVITATION
|
||||||
|
RECOVERY
|
||||||
|
EMAIL_CONFIRMATION
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link token. Only its SHA-256 is stored. Consuming it is a conditional update
|
||||||
|
// (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now()`), so the
|
||||||
|
// first device wins and the link dies.
|
||||||
|
model StudentAccessToken {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
tokenHash String @unique @map("token_hash")
|
||||||
|
accountId String @map("account_id")
|
||||||
|
kind StudentTokenKind
|
||||||
|
// EMAIL_CONFIRMATION only: the address being confirmed.
|
||||||
|
email String?
|
||||||
|
expiresAt DateTime @map("expires_at")
|
||||||
|
usedAt DateTime? @map("used_at")
|
||||||
|
// A new invitation revokes the account's pending tokens.
|
||||||
|
revokedAt DateTime? @map("revoked_at")
|
||||||
|
// Teacher who generated the invitation (null for recovery/confirmation).
|
||||||
|
createdById String? @map("created_by_id")
|
||||||
|
usedIp String? @map("used_ip")
|
||||||
|
usedUserAgent String? @map("used_user_agent")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([accountId, kind])
|
||||||
|
@@map("student_access_tokens")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Long sliding session (90 days, renewed on use). The cookie carries the raw
|
||||||
|
// token; only its hash is stored.
|
||||||
|
model StudentSession {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String @map("account_id")
|
||||||
|
tokenHash String @unique @map("token_hash")
|
||||||
|
// Human readable, derived from the user agent ("iPhone · Safari").
|
||||||
|
device String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
lastUsedAt DateTime @default(now()) @map("last_used_at")
|
||||||
|
expiresAt DateTime @map("expires_at")
|
||||||
|
revokedAt DateTime? @map("revoked_at")
|
||||||
|
|
||||||
|
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
@@map("student_sessions")
|
||||||
|
}
|
||||||
|
|
||||||
|
model StudentPasskey {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String @map("account_id")
|
||||||
|
credentialId String @unique @map("credential_id")
|
||||||
|
publicKey Bytes @map("public_key")
|
||||||
|
counter Int @default(0)
|
||||||
|
transports String[]
|
||||||
|
device String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
lastUsedAt DateTime? @map("last_used_at")
|
||||||
|
|
||||||
|
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
@@map("student_passkeys")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum WebauthnChallengePurpose {
|
||||||
|
REGISTER
|
||||||
|
LOGIN
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pending WebAuthn challenge, single use (deleted when verified), 5 minutes.
|
||||||
|
model StudentWebauthnChallenge {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
challenge String
|
||||||
|
// Registration only: the signed-in account. Login is discoverable (no account).
|
||||||
|
accountId String? @map("account_id")
|
||||||
|
purpose WebauthnChallengePurpose
|
||||||
|
expiresAt DateTime @map("expires_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([expiresAt])
|
||||||
|
@@map("student_webauthn_challenges")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generic sliding-window rate limit: one row per hit, counted by key within
|
||||||
|
// the window (e.g. "recovery:email:<sha256>", "recovery:ip:<ip>").
|
||||||
|
model RateLimitEvent {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
key String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([key, createdAt])
|
||||||
|
@@map("rate_limit_events")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum AbsenceReason {
|
||||||
|
HEALTH
|
||||||
|
TRAVEL
|
||||||
|
WORK_STUDY
|
||||||
|
OTHER
|
||||||
|
}
|
||||||
|
|
||||||
|
// Absence notice from the student. It only marks the attendance as EXCUSED
|
||||||
|
// (which already doesn't count for the attendance risk rules); the teacher
|
||||||
|
// sees it. At most one active (not cancelled) notice per attendee and class:
|
||||||
|
// enforced by a partial unique index in the migration.
|
||||||
|
model AbsenceNotice {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
attendeeId String @map("attendee_id")
|
||||||
|
classSessionId String @map("class_session_id")
|
||||||
|
accountId String? @map("account_id")
|
||||||
|
reason AbsenceReason?
|
||||||
|
message String?
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
cancelledAt DateTime? @map("cancelled_at")
|
||||||
|
|
||||||
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||||
|
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||||
|
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([attendeeId, classSessionId])
|
||||||
|
@@index([classSessionId])
|
||||||
|
@@map("absence_notices")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ReportedPaymentStatus {
|
||||||
|
REPORTED
|
||||||
|
CONFIRMED
|
||||||
|
REJECTED
|
||||||
|
}
|
||||||
|
|
||||||
|
// Payment reported by the student with a receipt. It stays REPORTED until the
|
||||||
|
// teacher confirms it (the fees become PAID) or rejects it. `Payment.status` is
|
||||||
|
// not touched while REPORTED: the MP reconciliation and the overdue job keep
|
||||||
|
// working as before, and "Requiere atención" skips fees covered by a REPORTED
|
||||||
|
// report.
|
||||||
|
model ReportedPayment {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
attendeeId String @map("attendee_id")
|
||||||
|
groupId String @map("group_id")
|
||||||
|
accountId String? @map("account_id")
|
||||||
|
totalAmount Decimal @map("total_amount") @db.Decimal(10, 2)
|
||||||
|
currency String
|
||||||
|
// Private object key in the storage; null once the retention policy deletes it.
|
||||||
|
receiptKey String? @map("receipt_key")
|
||||||
|
receiptMime String @map("receipt_mime")
|
||||||
|
receiptName String @map("receipt_name")
|
||||||
|
receiptSize Int @map("receipt_size")
|
||||||
|
status ReportedPaymentStatus @default(REPORTED)
|
||||||
|
reviewedById String? @map("reviewed_by_id")
|
||||||
|
reviewedAt DateTime? @map("reviewed_at")
|
||||||
|
rejectionReason String? @map("rejection_reason")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||||
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||||
|
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
|
||||||
|
items ReportedPaymentItem[]
|
||||||
|
|
||||||
|
@@index([groupId, status])
|
||||||
|
@@index([attendeeId])
|
||||||
|
@@map("reported_payments")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fees a report covers. A fee can't be in two REPORTED reports at once
|
||||||
|
// (checked in the use-case, inside the transaction).
|
||||||
|
model ReportedPaymentItem {
|
||||||
|
reportedPaymentId String @map("reported_payment_id")
|
||||||
|
paymentId String @map("payment_id")
|
||||||
|
|
||||||
|
reportedPayment ReportedPayment @relation(fields: [reportedPaymentId], references: [id], onDelete: Cascade)
|
||||||
|
payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([reportedPaymentId, paymentId])
|
||||||
|
@@index([paymentId])
|
||||||
|
@@map("reported_payment_items")
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
@@ -26,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
|
|||||||
import { mpRoutes } from './modules/mp';
|
import { mpRoutes } from './modules/mp';
|
||||||
import { onboardingRoutes } from './modules/onboarding';
|
import { onboardingRoutes } from './modules/onboarding';
|
||||||
import { paymentsRoutes } from './modules/payments';
|
import { paymentsRoutes } from './modules/payments';
|
||||||
|
import { studentPortalRoutes } from './modules/student-portal';
|
||||||
import { waitlistRoutes } from './modules/waitlist';
|
import { waitlistRoutes } from './modules/waitlist';
|
||||||
import { whatsappRoutes } from './modules/whatsapp';
|
import { whatsappRoutes } from './modules/whatsapp';
|
||||||
|
|
||||||
@@ -65,6 +67,8 @@ 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);
|
||||||
|
api.route('/student-portal', studentPortalRoutes);
|
||||||
|
|
||||||
app.notFound((c) => {
|
app.notFound((c) => {
|
||||||
return problemJson(c, notFoundProblem(c.req.path));
|
return problemJson(c, notFoundProblem(c.req.path));
|
||||||
|
|||||||
@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
|
|||||||
|
|
||||||
type AuthSession = typeof auth.$Infer.Session;
|
type AuthSession = typeof auth.$Infer.Session;
|
||||||
|
|
||||||
|
/** Signed-in student (attendee or guardian): set only on /student-portal. */
|
||||||
|
export type StudentContext = { accountId: string; sessionId: string };
|
||||||
|
|
||||||
export type BackendEnv = {
|
export type BackendEnv = {
|
||||||
Variables: {
|
Variables: {
|
||||||
user: AuthSession['user'] | null;
|
user: AuthSession['user'] | null;
|
||||||
session: AuthSession['session'] | null;
|
session: AuthSession['session'] | null;
|
||||||
requestId: string;
|
requestId: string;
|
||||||
|
student: StudentContext | null;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -15,5 +19,6 @@ declare module 'hono' {
|
|||||||
user: AuthSession['user'] | null;
|
user: AuthSession['user'] | null;
|
||||||
session: AuthSession['session'] | null;
|
session: AuthSession['session'] | null;
|
||||||
requestId: string;
|
requestId: string;
|
||||||
|
student: StudentContext | null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,6 +57,9 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
|||||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|
||||||
|| matchesPublicPrefix(normalizedPath, '/api/auth')
|
|| matchesPublicPrefix(normalizedPath, '/api/auth')
|
||||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations')
|
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations')
|
||||||
|
// Student app: its own cookie and middleware (modules/student-portal), never
|
||||||
|
// the teacher's session.
|
||||||
|
|| matchesPublicPrefix(normalizedPath, '/api/v1/student-portal')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,15 @@ import nodemailer, { type Transporter } from 'nodemailer'
|
|||||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||||
|
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
||||||
|
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
||||||
|
type StudentPaymentReviewedData = {
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
confirmed: boolean
|
||||||
|
amount: string
|
||||||
|
reason?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
// Brand colors (same system as the web app: index.css in apps/web).
|
// Brand colors (same system as the web app: index.css in apps/web).
|
||||||
const BRAND_600 = '#2544ea'
|
const BRAND_600 = '#2544ea'
|
||||||
@@ -26,10 +35,27 @@ function loadLogoTypoDataUri(): string {
|
|||||||
|
|
||||||
const LOGO_DATA_URI = loadLogoTypoDataUri()
|
const LOGO_DATA_URI = loadLogoTypoDataUri()
|
||||||
|
|
||||||
interface EmailProvider {
|
export interface EmailProvider {
|
||||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||||
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
||||||
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
||||||
|
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
||||||
|
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
||||||
|
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Names come from what teachers and students type: never raw into the HTML.
|
||||||
|
function escapeHtml(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''')
|
||||||
|
}
|
||||||
|
|
||||||
|
function button(url: string, label: string): string {
|
||||||
|
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
|
||||||
}
|
}
|
||||||
|
|
||||||
class SMTPEmailProvider implements EmailProvider {
|
class SMTPEmailProvider implements EmailProvider {
|
||||||
@@ -109,6 +135,47 @@ class SMTPEmailProvider implements EmailProvider {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) {
|
||||||
|
await this.send(
|
||||||
|
email,
|
||||||
|
'Confirmá tu mail de recuperación en Gruperly',
|
||||||
|
this.layout(
|
||||||
|
'Confirmá tu mail',
|
||||||
|
`Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.<br/><br/>${button(url, 'Confirmar mail')}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) {
|
||||||
|
// A guardian may have one account per child with the same email: one button each.
|
||||||
|
const buttons = links
|
||||||
|
.map((link) =>
|
||||||
|
links.length > 1
|
||||||
|
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
|
||||||
|
: button(link.url, 'Ingresar'),
|
||||||
|
)
|
||||||
|
.join('<br/>')
|
||||||
|
await this.send(
|
||||||
|
email,
|
||||||
|
'Tu link para ingresar a Gruperly',
|
||||||
|
this.layout(
|
||||||
|
'Tu link de ingreso',
|
||||||
|
`Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.<br/><br/>${buttons}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) {
|
||||||
|
const body = confirmed
|
||||||
|
? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!`
|
||||||
|
: `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>Podés volver a informarlo desde la app.`
|
||||||
|
await this.send(
|
||||||
|
email,
|
||||||
|
confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado',
|
||||||
|
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||||
|
|||||||
36
apps/backend/src/lib/file-type.ts
Normal file
36
apps/backend/src/lib/file-type.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
/* Real type of an uploaded file from its first bytes (magic numbers), never
|
||||||
|
from the name or the Content-Type the browser claims. */
|
||||||
|
|
||||||
|
export type ReceiptMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/heic' | 'application/pdf';
|
||||||
|
|
||||||
|
export const RECEIPT_MAX_BYTES = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
export const RECEIPT_EXTENSIONS: Record<ReceiptMime, string> = {
|
||||||
|
'image/jpeg': 'jpg',
|
||||||
|
'image/png': 'png',
|
||||||
|
'image/webp': 'webp',
|
||||||
|
'image/heic': 'heic',
|
||||||
|
'application/pdf': 'pdf',
|
||||||
|
};
|
||||||
|
|
||||||
|
// ISO-BMFF brands used by HEIC/HEIF photos (iPhone camera).
|
||||||
|
const HEIF_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1']);
|
||||||
|
|
||||||
|
function ascii(bytes: Uint8Array, start: number, length: number): string {
|
||||||
|
return String.fromCharCode(...bytes.subarray(start, start + length));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectReceiptType(bytes: Uint8Array): ReceiptMime | null {
|
||||||
|
if (bytes.length < 12) return null;
|
||||||
|
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
||||||
|
if (
|
||||||
|
bytes[0] === 0x89 && ascii(bytes, 1, 3) === 'PNG'
|
||||||
|
&& bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
|
||||||
|
) {
|
||||||
|
return 'image/png';
|
||||||
|
}
|
||||||
|
if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp';
|
||||||
|
if (ascii(bytes, 4, 4) === 'ftyp' && HEIF_BRANDS.has(ascii(bytes, 8, 4))) return 'image/heic';
|
||||||
|
if (ascii(bytes, 0, 5) === '%PDF-') return 'application/pdf';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
54
apps/backend/src/lib/storage.ts
Normal file
54
apps/backend/src/lib/storage.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { S3Client } from 'bun';
|
||||||
|
|
||||||
|
/* Private file storage (payment receipts). Behind a port, like the WhatsApp and
|
||||||
|
billing providers: the use-cases never talk to S3 directly, and the tests
|
||||||
|
inject an in-memory fake. Objects are never public; the teacher sees them
|
||||||
|
through short-lived signed URLs. */
|
||||||
|
export interface FileStorage {
|
||||||
|
put(key: string, body: Uint8Array, contentType: string): Promise<void>;
|
||||||
|
/** GET URL valid for `expiresInSeconds`. */
|
||||||
|
signedUrl(key: string, expiresInSeconds: number): string;
|
||||||
|
remove(key: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Any S3-compatible service (RustFS, MinIO, R2, AWS). Path-style addressing by
|
||||||
|
default, which is what self-hosted services expect; S3_VIRTUAL_HOSTED=on for
|
||||||
|
AWS-style bucket subdomains. */
|
||||||
|
class S3FileStorage implements FileStorage {
|
||||||
|
constructor(private readonly client: S3Client) {}
|
||||||
|
|
||||||
|
async put(key: string, body: Uint8Array, contentType: string): Promise<void> {
|
||||||
|
await this.client.write(key, body, { type: contentType });
|
||||||
|
}
|
||||||
|
|
||||||
|
signedUrl(key: string, expiresInSeconds: number): string {
|
||||||
|
return this.client.presign(key, { method: 'GET', expiresIn: expiresInSeconds });
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(key: string): Promise<void> {
|
||||||
|
await this.client.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let storage: FileStorage | null | undefined;
|
||||||
|
|
||||||
|
/** null when S3 isn't configured: the endpoints that need it answer 503. */
|
||||||
|
export function getFileStorage(): FileStorage | null {
|
||||||
|
if (storage !== undefined) return storage;
|
||||||
|
const { S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY } = process.env;
|
||||||
|
if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
|
||||||
|
storage = null;
|
||||||
|
return storage;
|
||||||
|
}
|
||||||
|
storage = new S3FileStorage(
|
||||||
|
new S3Client({
|
||||||
|
endpoint: S3_ENDPOINT,
|
||||||
|
bucket: S3_BUCKET,
|
||||||
|
region: process.env.S3_REGION || 'us-east-1',
|
||||||
|
accessKeyId: S3_ACCESS_KEY_ID,
|
||||||
|
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
||||||
|
virtualHostedStyle: process.env.S3_VIRTUAL_HOSTED === 'on',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return storage;
|
||||||
|
}
|
||||||
@@ -39,8 +39,21 @@ export class GetAttendeeHistory {
|
|||||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Same effective join date as the risk rule (`toMemberAttendance`): an
|
||||||
|
// attendee loaded after their first classes were already recorded starts
|
||||||
|
// at that first class, not at `createdAt`. Otherwise this screen said
|
||||||
|
// "1 de 3 clases" while the group list said "1 de 5" for the same person.
|
||||||
|
const firstAttendance = await db.attendance.findFirst({
|
||||||
|
where: { attendeeId },
|
||||||
|
orderBy: { classSession: { startsAt: 'asc' } },
|
||||||
|
select: { classSession: { select: { startsAt: true } } },
|
||||||
|
});
|
||||||
|
const firstClassAt = firstAttendance?.classSession.startsAt;
|
||||||
|
const since =
|
||||||
|
firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt;
|
||||||
|
|
||||||
const sessions = await db.classSession.findMany({
|
const sessions = await db.classSession.findMany({
|
||||||
where: { groupId, startsAt: { gte: attendee.createdAt } },
|
where: { groupId, startsAt: { gte: since } },
|
||||||
orderBy: { startsAt: 'desc' },
|
orderBy: { startsAt: 'desc' },
|
||||||
take: HISTORY_SESSIONS_LIMIT,
|
take: HISTORY_SESSIONS_LIMIT,
|
||||||
select: { id: true, startsAt: true },
|
select: { id: true, startsAt: true },
|
||||||
|
|||||||
@@ -4,30 +4,21 @@ import type {
|
|||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
GroupRiskSummary,
|
GroupRiskSummary,
|
||||||
GroupsRiskOverview,
|
GroupsRiskOverview,
|
||||||
MemberClassSession,
|
|
||||||
ProblemDetails,
|
ProblemDetails,
|
||||||
Result,
|
Result,
|
||||||
UrgentMemberSummary,
|
UrgentMemberSummary,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
|
import {
|
||||||
|
ATTENDANCE_RISK_RULES,
|
||||||
|
getGroupAttendanceSummary,
|
||||||
|
ok,
|
||||||
|
URGENT_MEMBERS_LIMIT,
|
||||||
|
} from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import {
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
classifyRisk,
|
|
||||||
MIN_RISK_ABSENCE_STREAK,
|
|
||||||
MIN_RISK_MONTHLY_RATE,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '../../lib/risk';
|
|
||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
/* How many classes we look back per attendee. That is the real ceiling of the
|
|
||||||
model: `class_sessions` are not created on their own, they get materialized
|
|
||||||
when someone opens "today's classes", so pulling years of rows makes no
|
|
||||||
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
|
|
||||||
the attendance rate the card shows. */
|
|
||||||
const MEMBER_HISTORY_LIMIT = 20;
|
|
||||||
|
|
||||||
type GetGroupsRiskOverviewDeps = {
|
type GetGroupsRiskOverviewDeps = {
|
||||||
db?: {
|
db?: {
|
||||||
group: Prisma.GroupDelegate;
|
group: Prisma.GroupDelegate;
|
||||||
@@ -54,10 +45,10 @@ type AttendanceRow = {
|
|||||||
classSession: { startsAt: Date };
|
classSession: { startsAt: Date };
|
||||||
};
|
};
|
||||||
|
|
||||||
// Risk status light summary per group for the group listing.
|
// Risk summary per group for the group listing and Home. Everything comes from
|
||||||
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
|
// the domain rule (`getGroupAttendanceSummary`): the status light is the worst
|
||||||
// any is at medium risk and NONE otherwise. The counters state the reason
|
// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
|
||||||
// (consecutive absences or low attendance) so the listing can name it.
|
// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
|
||||||
export class GetGroupsRiskOverview {
|
export class GetGroupsRiskOverview {
|
||||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||||
|
|
||||||
@@ -117,75 +108,31 @@ export class GetGroupsRiskOverview {
|
|||||||
|
|
||||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||||
|
|
||||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
const items: GroupRiskSummary[] = groups.map((group) =>
|
||||||
// Why there is risk, computed in the same pass: a member with an absence
|
buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
|
||||||
// streak counts in the first counter and only there; the second one
|
);
|
||||||
// groups the members that don't reach a streak and are still below the
|
|
||||||
// attendance minimum.
|
|
||||||
const absenceStreakCountByGroup = new Map<string, number>();
|
|
||||||
const lowAttendanceCountByGroup = new Map<string, number>();
|
|
||||||
|
|
||||||
for (const attendee of attendees) {
|
|
||||||
const groupId = attendee.groupId;
|
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
|
||||||
status: row.status,
|
|
||||||
occurredAt: row.classSession.startsAt,
|
|
||||||
}));
|
|
||||||
const streak = trailingAbsentStreak(stream);
|
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
|
||||||
sessionsByGroup.get(groupId)?.length ?? 0,
|
|
||||||
);
|
|
||||||
const riskLevel = classifyRisk(streak, monthlyRate);
|
|
||||||
if (!riskLevel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (streak >= MIN_RISK_ABSENCE_STREAK) {
|
|
||||||
bump(absenceStreakCountByGroup, groupId);
|
|
||||||
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
|
||||||
bump(lowAttendanceCountByGroup, groupId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
|
|
||||||
if (
|
|
||||||
riskLevel === 'HIGH' ||
|
|
||||||
(riskLevel === 'MEDIUM' && current === 'NONE')
|
|
||||||
) {
|
|
||||||
worstRiskByGroup.set(groupId, riskLevel);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const items: GroupRiskSummary[] = groups.map((group) => ({
|
|
||||||
groupId: group.id,
|
|
||||||
groupName: group.name,
|
|
||||||
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
|
|
||||||
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
|
|
||||||
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
|
|
||||||
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
|
|
||||||
}));
|
|
||||||
|
|
||||||
return ok({ items });
|
return ok({ items });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The per-level summary consumed by the listing card and the Home follow-up
|
* The per-level summary consumed by the listing card and Home. It comes from
|
||||||
* section. It comes from `getGroupAttendanceSummary`, the same domain function
|
* `getGroupAttendanceSummary`, the same domain function that
|
||||||
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
* `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||||
* copies: one here and another in the client.
|
* copies: one here and another in the client.
|
||||||
*
|
*
|
||||||
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
||||||
* summary counts the group members and the card needs the capacity slots to
|
* summary counts the group members and the card needs the capacity slots to
|
||||||
* paint the indicator.
|
* paint the indicator.
|
||||||
*/
|
*/
|
||||||
function buildSummaryFields(
|
function buildSummary(
|
||||||
group: GroupRow,
|
group: GroupRow,
|
||||||
attendees: AttendeeRow[],
|
attendees: AttendeeRow[],
|
||||||
sessionsByGroup: Map<string, SessionRow[]>,
|
sessionsByGroup: Map<string, SessionRow[]>,
|
||||||
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
||||||
now: Date,
|
now: Date,
|
||||||
) {
|
): GroupRiskSummary {
|
||||||
const resumen = getGroupAttendanceSummary({
|
const resumen = getGroupAttendanceSummary({
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
capacity: group.capacity,
|
capacity: group.capacity,
|
||||||
@@ -193,35 +140,23 @@ function buildSummaryFields(
|
|||||||
now,
|
now,
|
||||||
members: attendees
|
members: attendees
|
||||||
.filter((attendee) => attendee.groupId === group.id)
|
.filter((attendee) => attendee.groupId === group.id)
|
||||||
.map((attendee) => {
|
.map((attendee) =>
|
||||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
toMemberAttendance(
|
||||||
// If the attendee has attendances before their enrollment date in the
|
attendee,
|
||||||
// DB (e.g. created today but with past classes already recorded), their
|
sessionsByGroup.get(group.id) ?? [],
|
||||||
// effective join date is the first class they were marked for.
|
attendanceByAttendee.get(attendee.id) ?? [],
|
||||||
const earliestAttendance = attendeeAttendances.reduce<Date | null>(
|
),
|
||||||
(earliest, att) =>
|
),
|
||||||
!earliest || att.classSession.startsAt < earliest
|
|
||||||
? att.classSession.startsAt
|
|
||||||
: earliest,
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const enrolledAt =
|
|
||||||
earliestAttendance && earliestAttendance < attendee.createdAt
|
|
||||||
? earliestAttendance
|
|
||||||
: attendee.createdAt;
|
|
||||||
|
|
||||||
return {
|
|
||||||
attendeeId: attendee.id,
|
|
||||||
fullName: attendee.fullName,
|
|
||||||
enrolledAt: enrolledAt.toISOString(),
|
|
||||||
sessions: memberSessions(
|
|
||||||
sessionsByGroup.get(group.id) ?? [],
|
|
||||||
attendeeAttendances,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Why there is risk, over every member and not only the urgent ones sent to
|
||||||
|
// the client. Disjoint: an absence streak counts in the first and only
|
||||||
|
// there; the second groups the rest (inactivity or a declining trend).
|
||||||
|
const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok');
|
||||||
|
const absenceStreakCount = atRisk.filter(
|
||||||
|
(member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak,
|
||||||
|
).length;
|
||||||
|
|
||||||
const urgentes: UrgentMemberSummary[] = resumen.urgentes
|
const urgentes: UrgentMemberSummary[] = resumen.urgentes
|
||||||
.slice(0, URGENT_MEMBERS_LIMIT)
|
.slice(0, URGENT_MEMBERS_LIMIT)
|
||||||
.map((urgente) => ({
|
.map((urgente) => ({
|
||||||
@@ -233,7 +168,14 @@ function buildSummaryFields(
|
|||||||
attendanceRate: urgente.attendanceRate,
|
attendanceRate: urgente.attendanceRate,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
groupId: group.id,
|
||||||
|
groupName: group.name,
|
||||||
|
riskLevel,
|
||||||
|
absenceStreakCount,
|
||||||
|
lowAttendanceCount: atRisk.length - absenceStreakCount,
|
||||||
riesgoAlto: resumen.riesgoAlto,
|
riesgoAlto: resumen.riesgoAlto,
|
||||||
atencion: resumen.atencion,
|
atencion: resumen.atencion,
|
||||||
ok: resumen.ok,
|
ok: resumen.ok,
|
||||||
@@ -244,10 +186,6 @@ function buildSummaryFields(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function bump(counter: Map<string, number>, key: string) {
|
|
||||||
counter.set(key, (counter.get(key) ?? 0) + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
||||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
@@ -257,25 +195,3 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
|||||||
}
|
}
|
||||||
return byAttendee;
|
return byAttendee;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The universe of classes is the group's, not the `Attendance` rows'.
|
|
||||||
Attendance is recorded attendee by attendee and only when someone marks a
|
|
||||||
class, so "this class happened and this attendee has no record" is a real
|
|
||||||
and frequent state, not an absence. If the list were built from the
|
|
||||||
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
|
||||||
two absences separated by an unmarked class would count as three in a row.
|
|
||||||
The domain already treats them as neutral (`status: null`), so all that is
|
|
||||||
left here is to pick the right universe and keep the criterion on one side.
|
|
||||||
`sessions` comes from most recent to oldest, so keeping the first
|
|
||||||
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
|
||||||
and not global, so a group with a long history doesn't steal window from
|
|
||||||
the groups listed after it. */
|
|
||||||
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
|
|
||||||
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
|
||||||
|
|
||||||
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
|
|
||||||
sessionId: session.id,
|
|
||||||
startsAt: session.startsAt.toISOString(),
|
|
||||||
status: statusBySession.get(session.id) ?? null,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
@@ -6,15 +6,11 @@ import type {
|
|||||||
StudentAtRisk,
|
StudentAtRisk,
|
||||||
StudentsAtRisk,
|
StudentsAtRisk,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||||
import {
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
classifyRisk,
|
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||||
lastAttendedAt,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '../../lib/risk';
|
|
||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
type GetStudentsAtRiskDeps = {
|
type GetStudentsAtRiskDeps = {
|
||||||
@@ -24,6 +20,7 @@ type GetStudentsAtRiskDeps = {
|
|||||||
|
|
||||||
type AttendanceStreamRow = {
|
type AttendanceStreamRow = {
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
|
classSessionId: string;
|
||||||
status: AttendanceStatus;
|
status: AttendanceStatus;
|
||||||
classSession: { startsAt: Date };
|
classSession: { startsAt: Date };
|
||||||
};
|
};
|
||||||
@@ -56,8 +53,10 @@ export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' |
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
||||||
* the "Alumnos en riesgo" screen and the weekly re-engagement job, so both
|
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
|
||||||
* agree on who is at risk. Does not check access: callers do.
|
* with the same domain rule as the group listing and Home
|
||||||
|
* (`summarizeMemberAttendance`), so every screen agrees on who is at risk.
|
||||||
|
* Does not check access: callers do.
|
||||||
*/
|
*/
|
||||||
export async function findStudentsAtRisk(
|
export async function findStudentsAtRisk(
|
||||||
db: StudentsAtRiskDb,
|
db: StudentsAtRiskDb,
|
||||||
@@ -69,16 +68,18 @@ export async function findStudentsAtRisk(
|
|||||||
const [windowSessions, attendees, attendances] = await Promise.all([
|
const [windowSessions, attendees, attendances] = await Promise.all([
|
||||||
db.classSession.findMany({
|
db.classSession.findMany({
|
||||||
where: { groupId, startsAt: { gte: since } },
|
where: { groupId, startsAt: { gte: since } },
|
||||||
select: { id: true },
|
select: { id: true, startsAt: true },
|
||||||
|
orderBy: { startsAt: 'desc' },
|
||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { groupId, status: 'ACTIVE' },
|
where: { groupId, status: 'ACTIVE' },
|
||||||
select: { id: true, fullName: true, phone: true },
|
select: { id: true, fullName: true, phone: true, createdAt: true },
|
||||||
}),
|
}),
|
||||||
db.attendance.findMany({
|
db.attendance.findMany({
|
||||||
where: { attendee: { groupId } },
|
where: { attendee: { groupId } },
|
||||||
select: {
|
select: {
|
||||||
attendeeId: true,
|
attendeeId: true,
|
||||||
|
classSessionId: true,
|
||||||
status: true,
|
status: true,
|
||||||
classSession: { select: { startsAt: true } },
|
classSession: { select: { startsAt: true } },
|
||||||
},
|
},
|
||||||
@@ -91,20 +92,21 @@ export async function findStudentsAtRisk(
|
|||||||
|
|
||||||
const atRisk: StudentAtRisk[] = [];
|
const atRisk: StudentAtRisk[] = [];
|
||||||
for (const attendee of attendees) {
|
for (const attendee of attendees) {
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
const rows = streamByAttendee.get(attendee.id) ?? [];
|
||||||
status: row.status,
|
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
|
||||||
occurredAt: row.classSession.startsAt,
|
const riskLevel = toRiskLevel(signals.level);
|
||||||
}));
|
if (!riskLevel) {
|
||||||
const consecutiveAbsences = trailingAbsentStreak(stream);
|
continue;
|
||||||
|
}
|
||||||
|
// Display only: the verdict is the domain's. The rate keeps counting
|
||||||
|
// unrecorded classes as missed, which is what "asistencia mensual" says.
|
||||||
|
const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
|
||||||
|
const consecutiveAbsences = signals.consecutiveAbsences;
|
||||||
const attendedAt = lastAttendedAt(stream);
|
const attendedAt = lastAttendedAt(stream);
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
const monthlyRate = monthlyAttendanceRate(
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||||
totalWindowSessions,
|
totalWindowSessions,
|
||||||
);
|
);
|
||||||
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
|
|
||||||
if (!riskLevel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
atRisk.push({
|
atRisk.push({
|
||||||
attendeeId: attendee.id,
|
attendeeId: attendee.id,
|
||||||
fullName: attendee.fullName,
|
fullName: attendee.fullName,
|
||||||
|
|||||||
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared';
|
||||||
|
|
||||||
|
/* How many classes we look back per attendee. That is the real ceiling of the
|
||||||
|
model: `class_sessions` are not created on their own, they get materialized
|
||||||
|
when someone opens "today's classes", so pulling years of rows makes no
|
||||||
|
sense. 20 classes is enough for the streak, for the 6-class window and for
|
||||||
|
the attendance rate the card shows. */
|
||||||
|
export const MEMBER_HISTORY_LIMIT = 20;
|
||||||
|
|
||||||
|
export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date };
|
||||||
|
export type MemberSessionRow = { id: string; startsAt: Date };
|
||||||
|
export type MemberAttendanceRow = {
|
||||||
|
classSessionId: string;
|
||||||
|
status: AttendanceStatus;
|
||||||
|
classSession: { startsAt: Date };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The input of the domain risk rule (`summarizeMemberAttendance` in shared) for
|
||||||
|
* one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the
|
||||||
|
* re-engagement job all build it here, so they can't disagree on who is at risk.
|
||||||
|
*
|
||||||
|
* `groupSessions` must come most recent first (as the queries order them).
|
||||||
|
*/
|
||||||
|
export function toMemberAttendance(
|
||||||
|
attendee: MemberAttendeeRow,
|
||||||
|
groupSessions: MemberSessionRow[],
|
||||||
|
attendances: MemberAttendanceRow[],
|
||||||
|
): MemberAttendance {
|
||||||
|
// If the attendee has attendances before their enrollment date in the DB
|
||||||
|
// (e.g. created today but with past classes already recorded), their
|
||||||
|
// effective join date is the first class they were marked for.
|
||||||
|
const earliestAttendance = attendances.reduce<Date | null>(
|
||||||
|
(earliest, att) =>
|
||||||
|
!earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const enrolledAt =
|
||||||
|
earliestAttendance && earliestAttendance < attendee.createdAt
|
||||||
|
? earliestAttendance
|
||||||
|
: attendee.createdAt;
|
||||||
|
|
||||||
|
return {
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
fullName: attendee.fullName,
|
||||||
|
enrolledAt: enrolledAt.toISOString(),
|
||||||
|
sessions: memberSessions(groupSessions, attendances),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */
|
||||||
|
export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null {
|
||||||
|
if (level === 'riesgo_alto') return 'HIGH';
|
||||||
|
if (level === 'atencion') return 'MEDIUM';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The universe of classes is the group's, not the `Attendance` rows'.
|
||||||
|
Attendance is recorded attendee by attendee and only when someone marks a
|
||||||
|
class, so "this class happened and this attendee has no record" is a real
|
||||||
|
and frequent state, not an absence. If the list were built from the
|
||||||
|
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
||||||
|
two absences separated by an unmarked class would count as three in a row.
|
||||||
|
The domain already treats them as neutral (`status: null`), so all that is
|
||||||
|
left here is to pick the right universe and keep the criterion on one side.
|
||||||
|
`sessions` comes from most recent to oldest, so keeping the first
|
||||||
|
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
||||||
|
and not global, so a group with a long history doesn't steal window from
|
||||||
|
the groups listed after it. */
|
||||||
|
function memberSessions(
|
||||||
|
sessions: MemberSessionRow[],
|
||||||
|
attendances: MemberAttendanceRow[],
|
||||||
|
): MemberClassSession[] {
|
||||||
|
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
||||||
|
|
||||||
|
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
|
||||||
|
sessionId: session.id,
|
||||||
|
startsAt: session.startsAt.toISOString(),
|
||||||
|
status: statusBySession.get(session.id) ?? null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -3,27 +3,6 @@ export type AttendanceStreamEntry = {
|
|||||||
occurredAt: Date;
|
occurredAt: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
|
||||||
|
|
||||||
/** Minimum streak of unexcused absences that already triggers risk. */
|
|
||||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
|
||||||
|
|
||||||
/** Monthly attendance (30-day window) below which there is risk. */
|
|
||||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
|
||||||
|
|
||||||
// Counts the consecutive unexcused absences from the most recent class.
|
|
||||||
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
|
|
||||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
|
||||||
let streak = 0;
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (entry.status !== 'ABSENT') {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
streak += 1;
|
|
||||||
}
|
|
||||||
return streak;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
@@ -46,17 +25,3 @@ export function monthlyAttendanceRate(
|
|||||||
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
||||||
return Math.round((present / totalSessions) * 100);
|
return Math.round((present / totalSessions) * 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
|
|
||||||
export function classifyRisk(
|
|
||||||
consecutiveAbsences: number,
|
|
||||||
monthlyRate: number,
|
|
||||||
): RiskLevel | null {
|
|
||||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
|
|
||||||
return 'HIGH';
|
|
||||||
}
|
|
||||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
|
||||||
return 'MEDIUM';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -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,181 @@
|
|||||||
|
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' },
|
||||||
|
// A fee the student reported (with a receipt) is out of the alert while
|
||||||
|
// the teacher reviews it; a rejection brings it back.
|
||||||
|
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
||||||
|
},
|
||||||
|
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;
|
||||||
@@ -10,6 +10,7 @@ import updateAttendeeRoute from '../attendees/features/update/route';
|
|||||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
||||||
|
import { studentAccessRoutes } from '../student-access';
|
||||||
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
|
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
|
||||||
import createGroupRoute from './features/create/route';
|
import createGroupRoute from './features/create/route';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
@@ -36,5 +37,6 @@ routes.route('/', getAttendeeRoute);
|
|||||||
routes.route('/', updateAttendeeRoute);
|
routes.route('/', updateAttendeeRoute);
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
routes.route('/', removeAttendeeRoute);
|
routes.route('/', removeAttendeeRoute);
|
||||||
|
routes.route('/', studentAccessRoutes);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ type GroupSummaryRecord = {
|
|||||||
name: string;
|
name: string;
|
||||||
days: NextClass['days'];
|
days: NextClass['days'];
|
||||||
time: string | null;
|
time: string | null;
|
||||||
_count: { attendees: number };
|
_count: { attendees: number; preRegistrations: number };
|
||||||
};
|
};
|
||||||
|
|
||||||
export class GetHomeSummary {
|
export class GetHomeSummary {
|
||||||
@@ -42,7 +42,11 @@ export class GetHomeSummary {
|
|||||||
name: true,
|
name: true,
|
||||||
days: true,
|
days: true,
|
||||||
time: true,
|
time: true,
|
||||||
_count: { select: { attendees: true } },
|
// The pending pre-registrations ride on the same query: Home lists
|
||||||
|
// them under "Para atender" without one request per group.
|
||||||
|
_count: {
|
||||||
|
select: { attendees: true, preRegistrations: { where: { status: 'PENDING' } } },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -51,6 +55,7 @@ export class GetHomeSummary {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +98,13 @@ export class GetHomeSummary {
|
|||||||
groupName: payment.group.name,
|
groupName: payment.group.name,
|
||||||
attendeeName: payment.attendee.fullName,
|
attendeeName: payment.attendee.fullName,
|
||||||
})),
|
})),
|
||||||
|
pendingPreRegistrations: groups
|
||||||
|
.filter((group) => group._count.preRegistrations > 0)
|
||||||
|
.map((group) => ({
|
||||||
|
groupId: group.id,
|
||||||
|
groupName: group.name,
|
||||||
|
count: group._count.preRegistrations,
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { WeekDay } from '@gruperly/shared';
|
import type { WeekDay } from '@gruperly/shared';
|
||||||
|
|
||||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City';
|
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Argentina/Buenos_Aires';
|
||||||
|
|
||||||
// Window (in hours) during which an already started class shows as "in progress".
|
// Window (in hours) during which an already started class shows as "in progress".
|
||||||
export const CLASS_WINDOW_HOURS = 2;
|
export const CLASS_WINDOW_HOURS = 2;
|
||||||
@@ -185,4 +185,50 @@ export function todayOccurrence(opt: {
|
|||||||
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
||||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||||
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
||||||
}
|
}
|
||||||
|
// Every class start of a group within [from, to), in `timeZone`. Empty when the
|
||||||
|
// group has no valid schedule.
|
||||||
|
export function occurrencesBetween(opt: {
|
||||||
|
days: WeekDay[];
|
||||||
|
time: string | null;
|
||||||
|
from: Date;
|
||||||
|
to: Date;
|
||||||
|
timeZone: string;
|
||||||
|
}): Date[] {
|
||||||
|
const { days, time, from, to, timeZone } = opt;
|
||||||
|
if (days.length === 0 || !time) return [];
|
||||||
|
const [hour, minute] = time.split(':').map(Number);
|
||||||
|
if (
|
||||||
|
Number.isNaN(hour) ||
|
||||||
|
Number.isNaN(minute) ||
|
||||||
|
hour < 0 ||
|
||||||
|
hour > 23 ||
|
||||||
|
minute < 0 ||
|
||||||
|
minute > 59
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const dowSet = new Set(days.map((day) => WEEKDAY_TO_DOW[day]));
|
||||||
|
const { year, month, day } = wallDateInTimeZone(from, timeZone);
|
||||||
|
const result: Date[] = [];
|
||||||
|
// One extra day on each side covers the time zone offset.
|
||||||
|
const spanDays = Math.ceil((to.getTime() - from.getTime()) / (24 * 60 * 60 * 1000)) + 1;
|
||||||
|
for (let offset = -1; offset <= spanDays; offset++) {
|
||||||
|
const candidateDay = new Date(Date.UTC(year, month - 1, day + offset));
|
||||||
|
if (!dowSet.has(candidateDay.getUTCDay())) continue;
|
||||||
|
const wall = `${candidateDay.toISOString().slice(0, 10)}T${pad(hour)}:${pad(minute)}`;
|
||||||
|
const startsAt = zonedWallClockToUtc(wall, timeZone);
|
||||||
|
if (startsAt >= from && startsAt < to) result.push(startsAt);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monday 00:00 of `now`'s week in `timeZone`.
|
||||||
|
export function startOfWeekInTimeZone(now: Date, timeZone: string): Date {
|
||||||
|
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||||
|
const date = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
const sinceMonday = (date.getUTCDay() + 6) % 7;
|
||||||
|
const monday = new Date(Date.UTC(year, month - 1, day - sinceMonday));
|
||||||
|
return zonedWallClockToUtc(`${monday.toISOString().slice(0, 10)}T00:00`, timeZone);
|
||||||
|
}
|
||||||
|
|||||||
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
40
apps/backend/src/modules/payments/features/reported/route.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { type RejectReportedPayment, RejectReportedPaymentSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { ReportedPayments } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/reported', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
return resultJson(c, await new ReportedPayments().list(user.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.get('/reported/:reportId/receipt', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
return resultJson(c, await new ReportedPayments().receiptUrl(user.id, c.req.param('reportId')));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/reported/:reportId/confirm', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
return resultJson(c, await new ReportedPayments().confirm(user.id, c.req.param('reportId')));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/reported/:reportId/reject', validate.json(RejectReportedPaymentSchema), async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { reason } = c.req.valid('json') as RejectReportedPayment;
|
||||||
|
return resultJson(c, await new ReportedPayments().reject(user.id, c.req.param('reportId'), reason ?? null));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/reported/:reportId/undo', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
return resultJson(c, await new ReportedPayments().undo(user.id, c.req.param('reportId')));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
226
apps/backend/src/modules/payments/features/reported/use-case.ts
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, ReceiptUrlDto, ReportedPaymentDto, ReportedPaymentList, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok, REVIEW_UNDO_MINUTES } from '@gruperly/shared';
|
||||||
|
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||||
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
|
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
|
||||||
|
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
|
||||||
|
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
|
||||||
|
|
||||||
|
export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
|
||||||
|
const PREVIEWABLE = new Set(['image/jpeg', 'image/png', 'image/webp']);
|
||||||
|
|
||||||
|
type ReportedDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'reportedPayment'>;
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
storage?: FileStorage | null;
|
||||||
|
notify?: ReviewNotifier;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const reportSelect = {
|
||||||
|
id: true,
|
||||||
|
status: true,
|
||||||
|
createdAt: true,
|
||||||
|
totalAmount: true,
|
||||||
|
currency: true,
|
||||||
|
receiptKey: true,
|
||||||
|
receiptMime: true,
|
||||||
|
receiptName: true,
|
||||||
|
receiptSize: true,
|
||||||
|
attendee: { select: { id: true, fullName: true } },
|
||||||
|
group: { select: { id: true, name: true } },
|
||||||
|
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
|
||||||
|
} satisfies Prisma.ReportedPaymentSelect;
|
||||||
|
|
||||||
|
type ReportRow = Prisma.ReportedPaymentGetPayload<{ select: typeof reportSelect }>;
|
||||||
|
|
||||||
|
const STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
|
||||||
|
|
||||||
|
function accessible(userId: string): Prisma.ReportedPaymentWhereInput {
|
||||||
|
return { group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cobros → "Pagos para verificar": reports waiting for the teacher, across
|
||||||
|
their groups, oldest first. */
|
||||||
|
export class ReportedPayments {
|
||||||
|
constructor(private readonly deps: ReportedDeps = {}) {}
|
||||||
|
|
||||||
|
private get db() {
|
||||||
|
return this.deps.db ?? prisma;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get storage(): FileStorage | null {
|
||||||
|
return this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get now(): Date {
|
||||||
|
return this.deps.now ?? new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(userId: string): Promise<Result<ReportedPaymentList, ProblemDetails>> {
|
||||||
|
const rows = await this.db.reportedPayment.findMany({
|
||||||
|
where: { ...accessible(userId), status: 'REPORTED' },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: reportSelect,
|
||||||
|
});
|
||||||
|
return ok({ data: rows.map((row) => this.toDto(row)) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async receiptUrl(userId: string, reportId: string): Promise<Result<ReceiptUrlDto, ProblemDetails>> {
|
||||||
|
const row = await this.db.reportedPayment.findFirst({
|
||||||
|
where: { id: reportId, ...accessible(userId) },
|
||||||
|
select: { receiptKey: true, receiptMime: true, receiptName: true },
|
||||||
|
});
|
||||||
|
if (!row?.receiptKey) return err(notFoundResourceProblem('Receipt', reportId));
|
||||||
|
const storage = this.storage;
|
||||||
|
if (!storage) return err(storageNotAvailableProblem());
|
||||||
|
return ok({
|
||||||
|
url: storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS),
|
||||||
|
mime: row.receiptMime,
|
||||||
|
name: row.receiptName,
|
||||||
|
expiresAt: new Date(this.now.getTime() + RECEIPT_URL_TTL_SECONDS * 1000).toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Confirm: the report and its fees become paid, in one transaction. A fee
|
||||||
|
already PAID (e.g. through Mercado Pago meanwhile) is left as it is. */
|
||||||
|
async confirm(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||||
|
return this.review(userId, reportId, 'CONFIRMED', null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Reject: the fees stay as they were, and they come back to the overdue alert. */
|
||||||
|
async reject(userId: string, reportId: string, reason: string | null): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||||
|
return this.review(userId, reportId, 'REJECTED', reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "Deshacer", for a few minutes after the review: back to REPORTED. A confirm
|
||||||
|
is reverted only on the fees it paid (paid_at equal to the review and no MP
|
||||||
|
payment), which go back to PENDING or OVERDUE by the overdue job's rule. */
|
||||||
|
async undo(userId: string, reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||||
|
const now = this.now;
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const undone = await unitOfWork.executeResult(async (tx) => {
|
||||||
|
const report = await tx.reportedPayment.findFirst({
|
||||||
|
where: {
|
||||||
|
id: reportId,
|
||||||
|
...accessible(userId),
|
||||||
|
status: { in: ['CONFIRMED', 'REJECTED'] },
|
||||||
|
reviewedAt: { gt: new Date(now.getTime() - REVIEW_UNDO_MINUTES * 60 * 1000) },
|
||||||
|
},
|
||||||
|
select: { status: true, reviewedAt: true, items: { select: { paymentId: true } } },
|
||||||
|
});
|
||||||
|
if (!report?.reviewedAt) {
|
||||||
|
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||||
|
}
|
||||||
|
const claimed = await tx.reportedPayment.updateMany({
|
||||||
|
where: { id: reportId, status: report.status, reviewedAt: report.reviewedAt },
|
||||||
|
data: { status: 'REPORTED', reviewedAt: null, reviewedById: null, rejectionReason: null },
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) {
|
||||||
|
return err(conflictProblem({ detail: 'Ya no se puede deshacer.', code: 'review_undo_expired' }));
|
||||||
|
}
|
||||||
|
if (report.status === 'CONFIRMED') {
|
||||||
|
const paidByReview = {
|
||||||
|
id: { in: report.items.map((item) => item.paymentId) },
|
||||||
|
status: 'PAID' as const,
|
||||||
|
paidAt: report.reviewedAt,
|
||||||
|
mpPaymentId: null,
|
||||||
|
};
|
||||||
|
const overdueBefore = new Date(now.getTime() - OVERDUE_GRACE_MS);
|
||||||
|
await tx.payment.updateMany({
|
||||||
|
where: { ...paidByReview, dueDate: { lt: overdueBefore } },
|
||||||
|
data: { status: 'OVERDUE', paidAt: null },
|
||||||
|
});
|
||||||
|
await tx.payment.updateMany({
|
||||||
|
where: { ...paidByReview, dueDate: { gte: overdueBefore } },
|
||||||
|
data: { status: 'PENDING', paidAt: null },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return ok(null);
|
||||||
|
});
|
||||||
|
if (!undone.ok) return undone;
|
||||||
|
return this.load(reportId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async review(
|
||||||
|
userId: string,
|
||||||
|
reportId: string,
|
||||||
|
status: 'CONFIRMED' | 'REJECTED',
|
||||||
|
reason: string | null,
|
||||||
|
): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||||
|
const now = this.now;
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
|
||||||
|
const reviewed = await unitOfWork.executeResult(async (tx) => {
|
||||||
|
const claimed = await tx.reportedPayment.updateMany({
|
||||||
|
where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
|
||||||
|
data: {
|
||||||
|
status,
|
||||||
|
reviewedById: userId,
|
||||||
|
reviewedAt: now,
|
||||||
|
rejectionReason: status === 'REJECTED' ? reason || null : null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) {
|
||||||
|
const exists = await tx.reportedPayment.findFirst({ where: { id: reportId, ...accessible(userId) }, select: { id: true } });
|
||||||
|
return err(
|
||||||
|
exists
|
||||||
|
? conflictProblem({ detail: 'Este pago ya fue revisado.', code: 'payment_report_already_reviewed' })
|
||||||
|
: notFoundResourceProblem('ReportedPayment', reportId),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status === 'CONFIRMED') {
|
||||||
|
const items = await tx.reportedPaymentItem.findMany({ where: { reportedPaymentId: reportId }, select: { paymentId: true } });
|
||||||
|
await tx.payment.updateMany({
|
||||||
|
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
data: { status: 'PAID', paidAt: now },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return ok(null);
|
||||||
|
});
|
||||||
|
if (!reviewed.ok) return reviewed;
|
||||||
|
|
||||||
|
(this.deps.notify ?? scheduleReviewNotification)(reportId, now);
|
||||||
|
return this.load(reportId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async load(reportId: string): Promise<Result<ReportedPaymentDto, ProblemDetails>> {
|
||||||
|
const row = await this.db.reportedPayment.findUniqueOrThrow({ where: { id: reportId }, select: reportSelect });
|
||||||
|
return ok(this.toDto(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: ReportRow): ReportedPaymentDto {
|
||||||
|
const storage = this.storage;
|
||||||
|
const thumbnailUrl =
|
||||||
|
row.receiptKey && storage && PREVIEWABLE.has(row.receiptMime)
|
||||||
|
? storage.signedUrl(row.receiptKey, RECEIPT_URL_TTL_SECONDS)
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
status: STATUS[row.status],
|
||||||
|
attendee: row.attendee,
|
||||||
|
group: row.group,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
totalAmount: row.totalAmount.toNumber(),
|
||||||
|
currency: row.currency,
|
||||||
|
fees: row.items
|
||||||
|
.map(({ payment }) => ({
|
||||||
|
id: payment.id,
|
||||||
|
description: payment.description,
|
||||||
|
dueDate: payment.dueDate.toISOString(),
|
||||||
|
amount: payment.amount.toNumber(),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.dueDate.localeCompare(b.dueDate)),
|
||||||
|
receipt: {
|
||||||
|
mime: row.receiptMime,
|
||||||
|
name: row.receiptName,
|
||||||
|
size: row.receiptSize,
|
||||||
|
thumbnailUrl,
|
||||||
|
available: row.receiptKey !== null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { type UpdateTransferDetails, UpdateTransferDetailsSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
|
/* Bank transfer details (Ajustes) that students see when reporting a payment. */
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/transfer-details', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const row = await prisma.user.findUniqueOrThrow({
|
||||||
|
where: { id: user.id },
|
||||||
|
select: { transferAlias: true, transferHolder: true },
|
||||||
|
});
|
||||||
|
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
|
||||||
|
});
|
||||||
|
|
||||||
|
route.put('/transfer-details', validate.json(UpdateTransferDetailsSchema), async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { alias, holder } = c.req.valid('json') as UpdateTransferDetails;
|
||||||
|
const row = await prisma.user.update({
|
||||||
|
where: { id: user.id },
|
||||||
|
data: { transferAlias: alias || null, transferHolder: holder || null },
|
||||||
|
select: { transferAlias: true, transferHolder: true },
|
||||||
|
});
|
||||||
|
return c.json({ alias: row.transferAlias, holder: row.transferHolder });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -6,7 +6,7 @@ import prisma from '@/lib/prisma';
|
|||||||
* is still PENDING becomes OVERDUE; it stays billable, so the professor can
|
* is still PENDING becomes OVERDUE; it stays billable, so the professor can
|
||||||
* renew its link from Cobros.
|
* renew its link from Cobros.
|
||||||
*/
|
*/
|
||||||
const GRACE_MS = 24 * 60 * 60 * 1000;
|
export const OVERDUE_GRACE_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
export type MarkOverduePaymentsResult = {
|
export type MarkOverduePaymentsResult = {
|
||||||
marked: number;
|
marked: number;
|
||||||
@@ -23,7 +23,7 @@ export class MarkOverduePayments {
|
|||||||
async execute(): Promise<MarkOverduePaymentsResult> {
|
async execute(): Promise<MarkOverduePaymentsResult> {
|
||||||
const db = this.deps.db ?? prisma;
|
const db = this.deps.db ?? prisma;
|
||||||
const now = this.deps.now ?? new Date();
|
const now = this.deps.now ?? new Date();
|
||||||
const horizon = new Date(now.getTime() - GRACE_MS);
|
const horizon = new Date(now.getTime() - OVERDUE_GRACE_MS);
|
||||||
|
|
||||||
const updated = await db.payment.updateMany({
|
const updated = await db.payment.updateMany({
|
||||||
where: { status: 'PENDING', dueDate: { lt: horizon } },
|
where: { status: 'PENDING', dueDate: { lt: horizon } },
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { CountryCode } from '@gruperly/shared';
|
||||||
|
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { formatAmount } from '@/modules/whatsapp/lib/format';
|
||||||
|
|
||||||
|
// Long enough to cover the "Deshacer" on the card: an undone review emails nothing.
|
||||||
|
const NOTIFY_DELAY_MS = 60 * 1000;
|
||||||
|
|
||||||
|
export type ReviewNotifier = (reportId: string, reviewedAt: Date) => void;
|
||||||
|
|
||||||
|
/* Tells the student by email (only if they confirmed a recovery email) once
|
||||||
|
the review settles. The in-app banner is the main channel; this is a
|
||||||
|
courtesy, so an in-process timer lost on a restart is acceptable. */
|
||||||
|
export const scheduleReviewNotification: ReviewNotifier = (reportId, reviewedAt) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
void sendReviewNotification(reportId, reviewedAt).catch((error) =>
|
||||||
|
logger.error({ error, reportId }, 'Payment review notification failed'),
|
||||||
|
);
|
||||||
|
}, NOTIFY_DELAY_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function sendReviewNotification(
|
||||||
|
reportId: string,
|
||||||
|
reviewedAt: Date,
|
||||||
|
deps: { db?: Pick<PrismaClient, 'reportedPayment'>; email?: Pick<EmailProvider, 'sendStudentPaymentReviewed'> } = {},
|
||||||
|
): Promise<boolean> {
|
||||||
|
const db = deps.db ?? prisma;
|
||||||
|
const report = await db.reportedPayment.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
select: {
|
||||||
|
status: true,
|
||||||
|
reviewedAt: true,
|
||||||
|
rejectionReason: true,
|
||||||
|
totalAmount: true,
|
||||||
|
currency: true,
|
||||||
|
group: { select: { owner: { select: { country: true } } } },
|
||||||
|
account: { select: { name: true, recoveryEmail: true, recoveryEmailVerifiedAt: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Undone or reviewed again since: this notification is stale.
|
||||||
|
if (!report || report.status === 'REPORTED' || report.reviewedAt?.getTime() !== reviewedAt.getTime()) return false;
|
||||||
|
const account = report.account;
|
||||||
|
if (!account?.recoveryEmail || !account.recoveryEmailVerifiedAt) return false;
|
||||||
|
|
||||||
|
await (deps.email ?? emailProvider).sendStudentPaymentReviewed({
|
||||||
|
email: account.recoveryEmail,
|
||||||
|
name: account.name,
|
||||||
|
confirmed: report.status === 'CONFIRMED',
|
||||||
|
amount: formatAmount(report.totalAmount.toNumber(), report.currency, report.group.owner.country as CountryCode | null),
|
||||||
|
reason: report.rejectionReason,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
import renewRoute from './features/renew/route';
|
import renewRoute from './features/renew/route';
|
||||||
|
import reportedRoute from './features/reported/route';
|
||||||
|
import transferDetailsRoute from './features/transfer-details/route';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
routes.route('/', getAllRoute);
|
routes.route('/', getAllRoute);
|
||||||
|
routes.route('/', reportedRoute);
|
||||||
|
routes.route('/', transferDetailsRoute);
|
||||||
routes.route('/', renewRoute);
|
routes.route('/', renewRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { GetStudentAccess } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/:groupId/attendees/:attendeeId/student-access', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
const result = await new GetStudentAccess().execute(
|
||||||
|
c.req.param('groupId'),
|
||||||
|
c.req.param('attendeeId'),
|
||||||
|
user.id,
|
||||||
|
);
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, StudentAccessDto } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
|
type GetStudentAccessDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class GetStudentAccess {
|
||||||
|
constructor(private readonly deps: GetStudentAccessDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
groupId: string,
|
||||||
|
attendeeId: string,
|
||||||
|
userId: string,
|
||||||
|
): Promise<Result<StudentAccessDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) return access;
|
||||||
|
|
||||||
|
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true } });
|
||||||
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
|
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { InviteStudent } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.post('/:groupId/attendees/:attendeeId/student-access/invite', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
const result = await new InviteStudent().execute(
|
||||||
|
c.req.param('groupId'),
|
||||||
|
c.req.param('attendeeId'),
|
||||||
|
user.id,
|
||||||
|
);
|
||||||
|
return resultJson(c, result, { status: 201 });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
||||||
|
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||||
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||||
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
|
type InviteStudentDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* "Invitar" / "Reinvitar": reinviting restarts the access. It revokes every
|
||||||
|
pending link and every session and removes the passkeys (a lost phone must not
|
||||||
|
keep a way in), then issues a fresh 72 h single-use link. The welcome screen
|
||||||
|
shows again on the next sign-in so the student can add a passkey back. The
|
||||||
|
raw token only leaves here, inside the URL: the database keeps its hash. */
|
||||||
|
export class InviteStudent {
|
||||||
|
constructor(private readonly deps: InviteStudentDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
groupId: string,
|
||||||
|
attendeeId: string,
|
||||||
|
userId: string,
|
||||||
|
): Promise<Result<StudentInvitationDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) return access;
|
||||||
|
|
||||||
|
const attendee = await db.attendee.findFirst({
|
||||||
|
where: { id: attendeeId, groupId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
fullName: true,
|
||||||
|
phone: true,
|
||||||
|
guardianPhone: true,
|
||||||
|
group: { select: { owner: { select: { country: true } } } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
|
const token = generateAccessToken();
|
||||||
|
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
|
||||||
|
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||||
|
const link = await tx.studentAccountAttendee.findFirst({
|
||||||
|
where: { attendeeId },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { accountId: true },
|
||||||
|
});
|
||||||
|
const accountId =
|
||||||
|
link?.accountId
|
||||||
|
?? (
|
||||||
|
await tx.studentAccount.create({
|
||||||
|
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
).id;
|
||||||
|
|
||||||
|
await tx.studentAccessToken.updateMany({
|
||||||
|
where: { accountId, usedAt: null, revokedAt: null },
|
||||||
|
data: { revokedAt: now },
|
||||||
|
});
|
||||||
|
await tx.studentSession.updateMany({
|
||||||
|
where: { accountId, revokedAt: null },
|
||||||
|
data: { revokedAt: now },
|
||||||
|
});
|
||||||
|
await tx.studentPasskey.deleteMany({ where: { accountId } });
|
||||||
|
await tx.studentAccount.update({ where: { id: accountId }, data: { welcomedAt: null } });
|
||||||
|
await tx.studentAccessToken.create({
|
||||||
|
data: {
|
||||||
|
accountId,
|
||||||
|
kind: 'INVITATION',
|
||||||
|
tokenHash: hashToken(token),
|
||||||
|
expiresAt,
|
||||||
|
createdById: userId,
|
||||||
|
createdAt: now,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return ok(accountId);
|
||||||
|
});
|
||||||
|
if (!issued.ok) return issued;
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
url: studentLinkUrl(token),
|
||||||
|
expiresAt: expiresAt.toISOString(),
|
||||||
|
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
|
||||||
|
access: await computeStudentAccess(db, attendeeId, now),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
||||||
|
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { ListGroupAbsenceNotices } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/:groupId/absence-notices', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
return resultJson(c, await new ListGroupAbsenceNotices().execute(c.req.param('groupId'), user.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, TeacherAbsenceNoticeList } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
import { startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||||
|
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
|
||||||
|
|
||||||
|
const REASON = { HEALTH: 'health', TRAVEL: 'travel', WORK_STUDY: 'work_study', OTHER: 'other' } as const;
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
type ListAbsenceNoticesDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'user' | 'absenceNotice'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* "Faltas avisadas · esta semana" on the group card: active notices for this
|
||||||
|
week's classes (Monday to Sunday on the teacher's clock). */
|
||||||
|
export class ListGroupAbsenceNotices {
|
||||||
|
constructor(private readonly deps: ListAbsenceNoticesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(groupId: string, userId: string): Promise<Result<TeacherAbsenceNoticeList, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) return access;
|
||||||
|
|
||||||
|
const owner = await db.user.findUnique({ where: { id: access.value.createdById }, select: { country: true } });
|
||||||
|
const timeZone = teacherTimeZone(owner?.country);
|
||||||
|
const from = startOfWeekInTimeZone(now, timeZone);
|
||||||
|
const to = startOfWeekInTimeZone(new Date(from.getTime() + 8 * DAY_MS), timeZone);
|
||||||
|
|
||||||
|
const notices = await db.absenceNotice.findMany({
|
||||||
|
where: { cancelledAt: null, classSession: { groupId, startsAt: { gte: from, lt: to } } },
|
||||||
|
orderBy: [{ classSession: { startsAt: 'asc' } }, { createdAt: 'asc' }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
reason: true,
|
||||||
|
message: true,
|
||||||
|
createdAt: true,
|
||||||
|
attendee: { select: { id: true, fullName: true } },
|
||||||
|
classSession: { select: { startsAt: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
data: notices.map((notice) => ({
|
||||||
|
id: notice.id,
|
||||||
|
attendee: notice.attendee,
|
||||||
|
startsAt: notice.classSession.startsAt.toISOString(),
|
||||||
|
reason: notice.reason ? REASON[notice.reason] : null,
|
||||||
|
message: notice.message,
|
||||||
|
createdAt: notice.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
2
apps/backend/src/modules/student-access/index.ts
Normal file
2
apps/backend/src/modules/student-access/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { startStudentAccessJobs } from './jobs/cleanup';
|
||||||
|
export { default as studentAccessRoutes } from './routes';
|
||||||
95
apps/backend/src/modules/student-access/jobs/cleanup.ts
Normal file
95
apps/backend/src/modules/student-access/jobs/cleanup.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const BATCH = 100;
|
||||||
|
|
||||||
|
type CleanupDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'reportedPayment' | 'studentAccessToken' | 'studentWebauthnChallenge' | 'rateLimitEvent' | 'studentSession'>;
|
||||||
|
storage?: FileStorage | null;
|
||||||
|
now?: Date;
|
||||||
|
/** Days a receipt is kept after the teacher reviewed it; 0 keeps it forever. */
|
||||||
|
retentionDays?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function receiptRetentionDays(): number {
|
||||||
|
const parsed = Number(process.env.RECEIPT_RETENTION_DAYS ?? 0);
|
||||||
|
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Daily housekeeping of the student access:
|
||||||
|
- Receipt retention: deletes the files of reports reviewed more than
|
||||||
|
RECEIPT_RETENTION_DAYS ago (the row stays, without `receipt_key`). Reports
|
||||||
|
still waiting for the teacher are never touched.
|
||||||
|
- Drops dead tokens, challenges, rate limit hits and sessions after a grace
|
||||||
|
period (they only matter for the audit while they are recent). */
|
||||||
|
export class StudentAccessCleanup {
|
||||||
|
constructor(private readonly deps: CleanupDeps = {}) {}
|
||||||
|
|
||||||
|
async execute() {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||||
|
const retentionDays = this.deps.retentionDays ?? receiptRetentionDays();
|
||||||
|
|
||||||
|
let receiptsDeleted = 0;
|
||||||
|
if (retentionDays > 0 && storage) {
|
||||||
|
const before = new Date(now.getTime() - retentionDays * DAY_MS);
|
||||||
|
for (;;) {
|
||||||
|
const rows = await db.reportedPayment.findMany({
|
||||||
|
where: { status: { in: ['CONFIRMED', 'REJECTED'] }, reviewedAt: { lt: before }, receiptKey: { not: null } },
|
||||||
|
select: { id: true, receiptKey: true },
|
||||||
|
take: BATCH,
|
||||||
|
});
|
||||||
|
if (rows.length === 0) break;
|
||||||
|
for (const row of rows) {
|
||||||
|
try {
|
||||||
|
await storage.remove(row.receiptKey as string);
|
||||||
|
await db.reportedPayment.update({ where: { id: row.id }, data: { receiptKey: null } });
|
||||||
|
receiptsDeleted++;
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn({ error, reportId: row.id }, 'Receipt retention: file could not be removed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.length < BATCH) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const monthAgo = new Date(now.getTime() - 30 * DAY_MS);
|
||||||
|
const [tokens, challenges, hits, sessions] = await Promise.all([
|
||||||
|
db.studentAccessToken.deleteMany({ where: { expiresAt: { lt: monthAgo } } }),
|
||||||
|
db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: now } } }),
|
||||||
|
db.rateLimitEvent.deleteMany({ where: { createdAt: { lt: new Date(now.getTime() - DAY_MS) } } }),
|
||||||
|
db.studentSession.deleteMany({
|
||||||
|
where: { OR: [{ expiresAt: { lt: monthAgo } }, { revokedAt: { lt: monthAgo } }] },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
receiptsDeleted,
|
||||||
|
tokensDeleted: tokens.count,
|
||||||
|
challengesDeleted: challenges.count,
|
||||||
|
rateLimitHitsDeleted: hits.count,
|
||||||
|
sessionsDeleted: sessions.count,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const CLEANUP_CRON = '23 5 * * *';
|
||||||
|
|
||||||
|
/** Registered from server.ts, with the same guards as the other jobs. */
|
||||||
|
export function startStudentAccessJobs(): void {
|
||||||
|
Bun.cron(
|
||||||
|
CLEANUP_CRON,
|
||||||
|
async () => {
|
||||||
|
try {
|
||||||
|
logger.info(await new StudentAccessCleanup().execute(), 'Student access cleanup finished');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, 'Student access cleanup failed');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ tz: 'UTC' },
|
||||||
|
).unref();
|
||||||
|
}
|
||||||
70
apps/backend/src/modules/student-access/lib/status.ts
Normal file
70
apps/backend/src/modules/student-access/lib/status.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { StudentAccessDto } from '@gruperly/shared';
|
||||||
|
|
||||||
|
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>;
|
||||||
|
|
||||||
|
/* Passive state for the attendee's card: active (a live session) > invited
|
||||||
|
(a pending invitation) > expired (invited before, nothing alive) > not invited. */
|
||||||
|
export async function computeStudentAccess(
|
||||||
|
db: StudentAccessStatusDb,
|
||||||
|
attendeeId: string,
|
||||||
|
now: Date,
|
||||||
|
): Promise<StudentAccessDto> {
|
||||||
|
const link = await db.studentAccountAttendee.findFirst({
|
||||||
|
where: { attendeeId },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
account: {
|
||||||
|
select: {
|
||||||
|
_count: { select: { passkeys: true } },
|
||||||
|
sessions: {
|
||||||
|
where: { revokedAt: null, expiresAt: { gt: now } },
|
||||||
|
orderBy: { lastUsedAt: 'desc' },
|
||||||
|
select: { device: true, createdAt: true, lastUsedAt: true },
|
||||||
|
},
|
||||||
|
tokens: {
|
||||||
|
where: { kind: 'INVITATION' },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
select: { usedAt: true, revokedAt: true, expiresAt: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!link) {
|
||||||
|
return { status: 'not_invited', invitationExpiresAt: null, devices: [], hasPasskey: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { account } = link;
|
||||||
|
const devices = account.sessions.map((session) => ({
|
||||||
|
device: session.device,
|
||||||
|
createdAt: session.createdAt.toISOString(),
|
||||||
|
lastUsedAt: session.lastUsedAt.toISOString(),
|
||||||
|
}));
|
||||||
|
const hasPasskey = account._count.passkeys > 0;
|
||||||
|
const lastInvitation = account.tokens[0] ?? null;
|
||||||
|
const pending =
|
||||||
|
lastInvitation && !lastInvitation.usedAt && !lastInvitation.revokedAt && lastInvitation.expiresAt > now
|
||||||
|
? lastInvitation
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (devices.length > 0) {
|
||||||
|
return { status: 'active', invitationExpiresAt: null, devices, hasPasskey };
|
||||||
|
}
|
||||||
|
if (pending) {
|
||||||
|
return {
|
||||||
|
status: 'invited',
|
||||||
|
invitationExpiresAt: pending.expiresAt.toISOString(),
|
||||||
|
devices,
|
||||||
|
hasPasskey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: lastInvitation ? 'expired' : 'not_invited',
|
||||||
|
invitationExpiresAt: null,
|
||||||
|
devices,
|
||||||
|
hasPasskey,
|
||||||
|
};
|
||||||
|
}
|
||||||
15
apps/backend/src/modules/student-access/routes.ts
Normal file
15
apps/backend/src/modules/student-access/routes.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import getStatusRoute from './features/get-status/route';
|
||||||
|
import inviteRoute from './features/invite/route';
|
||||||
|
import listAbsenceNoticesRoute from './features/list-absence-notices/route';
|
||||||
|
|
||||||
|
// Teacher side of the student access. Hooked into modules/groups/routes.ts:
|
||||||
|
// it hangs from /groups/:groupId (absence notices) and
|
||||||
|
// /groups/:groupId/attendees/:attendeeId (access).
|
||||||
|
const routes = new Hono();
|
||||||
|
|
||||||
|
routes.route('/', getStatusRoute);
|
||||||
|
routes.route('/', inviteRoute);
|
||||||
|
routes.route('/', listAbsenceNoticesRoute);
|
||||||
|
|
||||||
|
export default routes;
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type {
|
||||||
|
CreateAbsenceNotices,
|
||||||
|
CreateAbsenceNoticesResult,
|
||||||
|
ProblemDetails,
|
||||||
|
Result,
|
||||||
|
} from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { validationProblem } from '@/http/problem-builders';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { absenceReleaseHours, registerAbsence } from '@/modules/classes/lib';
|
||||||
|
import { occurrencesBetween } from '@/modules/home/lib/scheduler';
|
||||||
|
import {
|
||||||
|
classAlreadyStartedProblem,
|
||||||
|
findLinkedAttendee,
|
||||||
|
studentAttendeeNotFoundProblem,
|
||||||
|
teacherTimeZone,
|
||||||
|
} from '../../lib';
|
||||||
|
import { ABSENCE_REASON_TO_DB, horizonEnd } from '../classes/use-case';
|
||||||
|
|
||||||
|
type AbsenceDb = Pick<
|
||||||
|
PrismaClient,
|
||||||
|
'attendee' | 'classSession' | 'absenceNotice' | 'attendance' | 'slotRelease'
|
||||||
|
>;
|
||||||
|
|
||||||
|
type AbsenceDeps = {
|
||||||
|
db?: AbsenceDb;
|
||||||
|
unitOfWork?: UnitOfWork;
|
||||||
|
now?: Date;
|
||||||
|
releaseHours?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* "No voy a ir": only before the class starts, only for real classes of the
|
||||||
|
attendee's group. Each class goes through the same `registerAbsence` the
|
||||||
|
teacher and the old absence link use (EXCUSED + spot release), so an excused
|
||||||
|
absence doesn't count for the attendance risk rules. Classes already
|
||||||
|
notified are skipped (idempotent). */
|
||||||
|
export class NotifyStudentAbsences {
|
||||||
|
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
accountId: string,
|
||||||
|
input: CreateAbsenceNotices,
|
||||||
|
): Promise<Result<CreateAbsenceNoticesResult, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||||
|
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||||
|
|
||||||
|
const timeZone = teacherTimeZone(attendee.group.owner.country);
|
||||||
|
const valid = new Set(
|
||||||
|
occurrencesBetween({
|
||||||
|
days: attendee.group.days,
|
||||||
|
time: attendee.group.time,
|
||||||
|
from: now,
|
||||||
|
to: horizonEnd(now),
|
||||||
|
timeZone,
|
||||||
|
}).map((date) => date.getTime()),
|
||||||
|
);
|
||||||
|
|
||||||
|
const requested = [...new Set(input.startsAt.map((value) => new Date(value).getTime()))];
|
||||||
|
for (const time of requested) {
|
||||||
|
if (time <= now.getTime()) return err(classAlreadyStartedProblem());
|
||||||
|
if (!valid.has(time)) {
|
||||||
|
return err(validationProblem({ detail: 'Una de las clases elegidas no es del grupo.' }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const notified: CreateAbsenceNoticesResult['notified'] = [];
|
||||||
|
for (const time of requested.sort((a, b) => a - b)) {
|
||||||
|
const startsAt = new Date(time);
|
||||||
|
const session = await db.classSession.upsert({
|
||||||
|
where: { groupId_startsAt: { groupId: attendee.groupId, startsAt } },
|
||||||
|
create: { groupId: attendee.groupId, startsAt },
|
||||||
|
update: {},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const existing = await db.absenceNotice.findFirst({
|
||||||
|
where: { attendeeId: attendee.id, classSessionId: session.id, cancelledAt: null },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (existing) continue;
|
||||||
|
|
||||||
|
const registered = await registerAbsence(
|
||||||
|
{ db, unitOfWork },
|
||||||
|
{
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
classSessionId: session.id,
|
||||||
|
now,
|
||||||
|
releaseHours: this.deps.releaseHours ?? absenceReleaseHours(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!registered.ok) return registered;
|
||||||
|
|
||||||
|
const notice = await db.absenceNotice.create({
|
||||||
|
data: {
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
classSessionId: session.id,
|
||||||
|
accountId,
|
||||||
|
reason: input.reason ? ABSENCE_REASON_TO_DB[input.reason] : null,
|
||||||
|
message: input.message || null,
|
||||||
|
createdAt: now,
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
notified.push({ id: notice.id, startsAt: startsAt.toISOString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({ notified });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "Deshacer": while the class hasn't started. Undoes what the notice did: the
|
||||||
|
EXCUSED mark and the released spot, if nobody claimed it. */
|
||||||
|
export class CancelStudentAbsence {
|
||||||
|
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string, noticeId: string): Promise<Result<{ id: string }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const notice = await db.absenceNotice.findFirst({
|
||||||
|
where: {
|
||||||
|
id: noticeId,
|
||||||
|
cancelledAt: null,
|
||||||
|
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
|
||||||
|
},
|
||||||
|
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||||
|
});
|
||||||
|
if (!notice) return err(studentAttendeeNotFoundProblem());
|
||||||
|
if (notice.classSession.startsAt <= now) return err(classAlreadyStartedProblem());
|
||||||
|
|
||||||
|
return unitOfWork.executeResult(async (tx) => {
|
||||||
|
await tx.absenceNotice.update({ where: { id: notice.id }, data: { cancelledAt: now } });
|
||||||
|
await tx.attendance.deleteMany({
|
||||||
|
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, status: 'EXCUSED' },
|
||||||
|
});
|
||||||
|
await tx.slotRelease.deleteMany({
|
||||||
|
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, isClaimed: false },
|
||||||
|
});
|
||||||
|
return ok({ id: notice.id });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
type CreateAbsenceNotices,
|
||||||
|
CreateAbsenceNoticesSchema,
|
||||||
|
type StudentAttendeeQuery,
|
||||||
|
StudentAttendeeQuerySchema,
|
||||||
|
} from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
import { CancelStudentAbsence, NotifyStudentAbsences } from '../absences/use-case';
|
||||||
|
import { GetStudentClasses } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.get('/classes', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
|
||||||
|
return resultJson(c, await new GetStudentClasses().execute(accountId, attendeeId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/absences', studentSession, validate.json(CreateAbsenceNoticesSchema), async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
const input = c.req.valid('json') as CreateAbsenceNotices;
|
||||||
|
return resultJson(c, await new NotifyStudentAbsences().execute(accountId, input), { status: 201 });
|
||||||
|
});
|
||||||
|
|
||||||
|
route.delete('/absences/:noticeId', studentSession, async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
return resultJson(c, await new CancelStudentAbsence().execute(accountId, c.req.param('noticeId')));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AbsenceReasonValue, ProblemDetails, Result, StudentClassesDto } from '@gruperly/shared';
|
||||||
|
import { ABSENCE_NOTICE_HORIZON_DAYS, err, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||||
|
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
|
||||||
|
|
||||||
|
type GetStudentClassesDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'attendee' | 'absenceNotice'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ABSENCE_REASON_TO_DB = {
|
||||||
|
health: 'HEALTH',
|
||||||
|
travel: 'TRAVEL',
|
||||||
|
work_study: 'WORK_STUDY',
|
||||||
|
other: 'OTHER',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const ABSENCE_REASON_FROM_DB: Record<string, AbsenceReasonValue> = {
|
||||||
|
HEALTH: 'health',
|
||||||
|
TRAVEL: 'travel',
|
||||||
|
WORK_STUDY: 'work_study',
|
||||||
|
OTHER: 'other',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function horizonEnd(now: Date): Date {
|
||||||
|
return new Date(now.getTime() + ABSENCE_NOTICE_HORIZON_DAYS * 24 * 60 * 60 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Classes of this week (already started ones included, for "Esta semana") up
|
||||||
|
to the notice horizon, with the student's active notice on each. Only the
|
||||||
|
attendee's own data: never other members of the group. */
|
||||||
|
export class GetStudentClasses {
|
||||||
|
constructor(private readonly deps: GetStudentClassesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string, attendeeId: string): Promise<Result<StudentClassesDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
|
||||||
|
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||||
|
|
||||||
|
const timeZone = teacherTimeZone(attendee.group.owner.country);
|
||||||
|
const from = startOfWeekInTimeZone(now, timeZone);
|
||||||
|
const to = horizonEnd(now);
|
||||||
|
const weekEndsAt = startOfWeekInTimeZone(new Date(from.getTime() + 8 * 24 * 60 * 60 * 1000), timeZone);
|
||||||
|
const starts = occurrencesBetween({ days: attendee.group.days, time: attendee.group.time, from, to, timeZone });
|
||||||
|
|
||||||
|
const notices = await db.absenceNotice.findMany({
|
||||||
|
where: {
|
||||||
|
attendeeId,
|
||||||
|
cancelledAt: null,
|
||||||
|
classSession: { groupId: attendee.groupId, startsAt: { gte: from, lt: to } },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
reason: true,
|
||||||
|
message: true,
|
||||||
|
createdAt: true,
|
||||||
|
classSession: { select: { startsAt: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const noticeByStart = new Map(notices.map((notice) => [notice.classSession.startsAt.getTime(), notice]));
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
attendeeId,
|
||||||
|
timeZone,
|
||||||
|
weekEndsAt: weekEndsAt.toISOString(),
|
||||||
|
classes: starts.map((startsAt) => {
|
||||||
|
const notice = noticeByStart.get(startsAt.getTime());
|
||||||
|
return {
|
||||||
|
startsAt: startsAt.toISOString(),
|
||||||
|
groupName: attendee.group.name,
|
||||||
|
started: startsAt <= now,
|
||||||
|
notice: notice
|
||||||
|
? {
|
||||||
|
id: notice.id,
|
||||||
|
reason: notice.reason ? ABSENCE_REASON_FROM_DB[notice.reason] ?? null : null,
|
||||||
|
message: notice.message,
|
||||||
|
createdAt: notice.createdAt.toISOString(),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson } from '@/http/problem-details';
|
||||||
|
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
|
||||||
|
import { ConsumeStudentLink } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.post('/links/:token/consume', async (c) => {
|
||||||
|
const result = await new ConsumeStudentLink().execute({
|
||||||
|
token: c.req.param('token'),
|
||||||
|
ip: clientIp(c),
|
||||||
|
userAgent: userAgent(c),
|
||||||
|
currentSessionToken: readStudentSessionCookie(c),
|
||||||
|
});
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
|
||||||
|
writeStudentSessionCookie(c, result.value.sessionToken);
|
||||||
|
return c.json({ firstLogin: result.value.firstLogin });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import {
|
||||||
|
createStudentSession,
|
||||||
|
hashToken,
|
||||||
|
revokeStudentSessionByToken,
|
||||||
|
studentLinkInvalidProblem,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
|
type ConsumeStudentLinkDeps = {
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConsumeStudentLinkInput = {
|
||||||
|
token: string;
|
||||||
|
ip: string | null;
|
||||||
|
userAgent: string | null;
|
||||||
|
/** Session cookie already on this device, if any: it is replaced. */
|
||||||
|
currentSessionToken?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConsumeStudentLinkOutput = { sessionToken: string; firstLogin: boolean };
|
||||||
|
|
||||||
|
/* POST of the link. The conditional update is what makes it single use: under
|
||||||
|
concurrency Postgres re-checks `used_at IS NULL` after the first commit, so
|
||||||
|
exactly one request gets count === 1 and the rest see a dead link. */
|
||||||
|
export class ConsumeStudentLink {
|
||||||
|
constructor(private readonly deps: ConsumeStudentLinkDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
input: ConsumeStudentLinkInput,
|
||||||
|
): Promise<Result<ConsumeStudentLinkOutput, ProblemDetails>> {
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
const tokenHash = hashToken(input.token);
|
||||||
|
|
||||||
|
return unitOfWork.executeResult(async (tx) => {
|
||||||
|
const claimed = await tx.studentAccessToken.updateMany({
|
||||||
|
where: {
|
||||||
|
tokenHash,
|
||||||
|
kind: { in: ['INVITATION', 'RECOVERY'] },
|
||||||
|
usedAt: null,
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: { gt: now },
|
||||||
|
},
|
||||||
|
data: { usedAt: now, usedIp: input.ip, usedUserAgent: input.userAgent },
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) {
|
||||||
|
return err(studentLinkInvalidProblem());
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await tx.studentAccessToken.findUniqueOrThrow({
|
||||||
|
where: { tokenHash },
|
||||||
|
select: { accountId: true, account: { select: { welcomedAt: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.currentSessionToken) {
|
||||||
|
await revokeStudentSessionByToken(tx, input.currentSessionToken, now);
|
||||||
|
}
|
||||||
|
const sessionToken = await createStudentSession(tx, {
|
||||||
|
accountId: row.accountId,
|
||||||
|
userAgent: input.userAgent,
|
||||||
|
now,
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ sessionToken, firstLogin: row.account.welcomedAt === null });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { type StudentAttendeeQuery, StudentAttendeeQuerySchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { validationProblem } from '@/http/problem-builders';
|
||||||
|
import { problemJson, resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
import { ReportStudentPayment } from '../payment-reports/use-case';
|
||||||
|
import { GetStudentFees } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
|
||||||
|
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
|
||||||
|
});
|
||||||
|
|
||||||
|
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
|
||||||
|
route.post('/payment-reports', studentSession, async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
// Reject oversized bodies before buffering them (10 MB + room for the fields).
|
||||||
|
const length = Number(c.req.header('Content-Length') ?? 0);
|
||||||
|
if (length > RECEIPT_MAX_BYTES + 64 * 1024) {
|
||||||
|
return problemJson(c, validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
let form: FormData;
|
||||||
|
try {
|
||||||
|
form = await c.req.formData();
|
||||||
|
} catch {
|
||||||
|
return problemJson(c, validationProblem({ detail: 'Invalid form data' }));
|
||||||
|
}
|
||||||
|
const attendeeId = form.get('attendeeId');
|
||||||
|
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
|
||||||
|
const file = form.get('file');
|
||||||
|
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
|
||||||
|
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await new ReportStudentPayment().execute(accountId, {
|
||||||
|
attendeeId,
|
||||||
|
paymentIds,
|
||||||
|
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
|
||||||
|
});
|
||||||
|
return resultJson(c, result, { status: 201 });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, StudentFeeStatus, StudentFeesDto } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
|
||||||
|
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
|
||||||
|
|
||||||
|
type GetStudentFeesDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'attendee' | 'payment' | 'reportedPayment'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const REPORTS_SHOWN = 10;
|
||||||
|
|
||||||
|
const REPORT_STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
|
||||||
|
|
||||||
|
/* Unpaid fees of the attendee and their latest reports. A fee inside a report
|
||||||
|
the teacher hasn't reviewed shows as "reported" (the Payment row itself is
|
||||||
|
not touched until the teacher confirms). */
|
||||||
|
export class GetStudentFees {
|
||||||
|
constructor(private readonly deps: GetStudentFeesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string, attendeeId: string): Promise<Result<StudentFeesDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
|
||||||
|
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||||
|
const startOfToday = startOfDayInTimeZone(now, teacherTimeZone(attendee.group.owner.country));
|
||||||
|
|
||||||
|
const [payments, reports] = await Promise.all([
|
||||||
|
db.payment.findMany({
|
||||||
|
where: { attendeeId, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
orderBy: { dueDate: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
description: true,
|
||||||
|
amount: true,
|
||||||
|
currency: true,
|
||||||
|
dueDate: true,
|
||||||
|
status: true,
|
||||||
|
checkoutUrl: true,
|
||||||
|
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
db.reportedPayment.findMany({
|
||||||
|
where: { attendeeId },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: REPORTS_SHOWN,
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
totalAmount: true,
|
||||||
|
currency: true,
|
||||||
|
status: true,
|
||||||
|
createdAt: true,
|
||||||
|
reviewedAt: true,
|
||||||
|
rejectionReason: true,
|
||||||
|
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const { transferAlias, transferHolder } = attendee.group.owner;
|
||||||
|
return ok({
|
||||||
|
attendeeId,
|
||||||
|
fees: payments.map((payment) => {
|
||||||
|
let status: StudentFeeStatus = 'pending';
|
||||||
|
if (payment.reportedItems.length > 0) status = 'reported';
|
||||||
|
else if (payment.status === 'OVERDUE' || payment.dueDate < startOfToday) status = 'overdue';
|
||||||
|
return {
|
||||||
|
id: payment.id,
|
||||||
|
description: payment.description,
|
||||||
|
amount: payment.amount.toNumber(),
|
||||||
|
currency: payment.currency,
|
||||||
|
dueDate: payment.dueDate.toISOString(),
|
||||||
|
status,
|
||||||
|
checkoutUrl: payment.checkoutUrl,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,
|
||||||
|
reports: reports.map((report) => ({
|
||||||
|
id: report.id,
|
||||||
|
totalAmount: report.totalAmount.toNumber(),
|
||||||
|
currency: report.currency,
|
||||||
|
status: REPORT_STATUS[report.status],
|
||||||
|
createdAt: report.createdAt.toISOString(),
|
||||||
|
reviewedAt: report.reviewedAt?.toISOString() ?? null,
|
||||||
|
rejectionReason: report.rejectionReason,
|
||||||
|
fees: report.items.map(({ payment }) => ({
|
||||||
|
id: payment.id,
|
||||||
|
description: payment.description,
|
||||||
|
dueDate: payment.dueDate.toISOString(),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { GetStudentLinkInfo } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/links/:token', async (c) => {
|
||||||
|
const result = await new GetStudentLinkInfo().execute(c.req.param('token'));
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { hashToken } from '../../lib';
|
||||||
|
|
||||||
|
type GetStudentLinkInfoDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'studentAccessToken'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||||
|
|
||||||
|
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
||||||
|
scanners open it). Every unusable link answers the same `invalid`. */
|
||||||
|
export class GetStudentLinkInfo {
|
||||||
|
constructor(private readonly deps: GetStudentLinkInfoDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(token: string): Promise<Result<StudentLinkInfo, ProblemDetails>> {
|
||||||
|
if (!TOKEN_PATTERN.test(token)) return ok({ status: 'invalid' });
|
||||||
|
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const row = await db.studentAccessToken.findUnique({
|
||||||
|
where: { tokenHash: hashToken(token) },
|
||||||
|
select: {
|
||||||
|
kind: true,
|
||||||
|
usedAt: true,
|
||||||
|
revokedAt: true,
|
||||||
|
expiresAt: true,
|
||||||
|
account: {
|
||||||
|
select: {
|
||||||
|
name: true,
|
||||||
|
attendees: {
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
take: 1,
|
||||||
|
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (
|
||||||
|
!row
|
||||||
|
|| row.kind === 'EMAIL_CONFIRMATION'
|
||||||
|
|| row.usedAt
|
||||||
|
|| row.revokedAt
|
||||||
|
|| row.expiresAt <= now
|
||||||
|
) {
|
||||||
|
return ok({ status: 'invalid' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const group = row.account.attendees[0]?.attendee.group ?? null;
|
||||||
|
return ok({
|
||||||
|
status: 'valid',
|
||||||
|
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||||
|
name: row.account.name,
|
||||||
|
teacherName: group?.owner.name ?? null,
|
||||||
|
groupName: group?.name ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { clearStudentSessionCookie } from '../../lib';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
// Closes this device only. Reinviting from the teacher's side closes all of them.
|
||||||
|
route.post('/logout', studentSession, async (c) => {
|
||||||
|
const student = currentStudent(c);
|
||||||
|
await prisma.studentSession.updateMany({
|
||||||
|
where: { id: student.sessionId, revokedAt: null },
|
||||||
|
data: { revokedAt: new Date() },
|
||||||
|
});
|
||||||
|
clearStudentSessionCookie(c);
|
||||||
|
return c.body(null, 204);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
19
apps/backend/src/modules/student-portal/features/me/route.ts
Normal file
19
apps/backend/src/modules/student-portal/features/me/route.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
import { GetStudentMe, MarkStudentWelcomed } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.get('/me', studentSession, async (c) => {
|
||||||
|
const student = currentStudent(c);
|
||||||
|
return resultJson(c, await new GetStudentMe().execute(student.accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/me/welcome', studentSession, async (c) => {
|
||||||
|
const student = currentStudent(c);
|
||||||
|
return resultJson(c, await new MarkStudentWelcomed().execute(student.accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
|
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
||||||
|
|
||||||
|
export class GetStudentMe {
|
||||||
|
constructor(private readonly deps: StudentMeDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const account = await db.studentAccount.findUnique({
|
||||||
|
where: { id: accountId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
recoveryEmail: true,
|
||||||
|
pendingRecoveryEmail: true,
|
||||||
|
welcomedAt: true,
|
||||||
|
_count: { select: { passkeys: true } },
|
||||||
|
attendees: {
|
||||||
|
where: { attendee: { status: { not: 'DROPPED' } } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
attendee: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
fullName: true,
|
||||||
|
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!account) return err(unauthorizedProblem('/student-portal/me'));
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
account: {
|
||||||
|
id: account.id,
|
||||||
|
name: account.name,
|
||||||
|
recoveryEmail: account.recoveryEmail,
|
||||||
|
pendingRecoveryEmail: account.pendingRecoveryEmail,
|
||||||
|
hasPasskey: account._count.passkeys > 0,
|
||||||
|
welcomed: account.welcomedAt !== null,
|
||||||
|
},
|
||||||
|
students: account.attendees.map(({ attendee }) => ({
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
fullName: attendee.fullName,
|
||||||
|
groupId: attendee.group.id,
|
||||||
|
groupName: attendee.group.name,
|
||||||
|
teacherName: attendee.group.owner.name,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The welcome screen is shown until the student goes past it once. */
|
||||||
|
export class MarkStudentWelcomed {
|
||||||
|
constructor(private readonly deps: StudentMeDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
await db.studentAccount.updateMany({
|
||||||
|
where: { id: accountId, welcomedAt: null },
|
||||||
|
data: { welcomedAt: this.deps.now ?? new Date() },
|
||||||
|
});
|
||||||
|
return new GetStudentMe({ db }).execute(accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { type PasskeyVerify, PasskeyVerifySchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
import { GetStudentMe } from '../me/use-case';
|
||||||
|
import { StudentPasskeys } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.post('/passkeys/register/options', studentSession, async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
return resultJson(c, await new StudentPasskeys().registrationOptions(accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/passkeys/register/verify', studentSession, validate.json(PasskeyVerifySchema), async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
const input = c.req.valid('json') as PasskeyVerify;
|
||||||
|
const result = await new StudentPasskeys().verifyRegistration(accountId, input, userAgent(c));
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.delete('/passkeys', studentSession, async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
await new StudentPasskeys().removeAll(accountId);
|
||||||
|
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/passkeys/login/options', async (c) => {
|
||||||
|
return resultJson(c, await new StudentPasskeys().loginOptions(clientIp(c)));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/passkeys/login/verify', validate.json(PasskeyVerifySchema), async (c) => {
|
||||||
|
const input = c.req.valid('json') as PasskeyVerify;
|
||||||
|
const result = await new StudentPasskeys().verifyLogin(input, {
|
||||||
|
userAgent: userAgent(c),
|
||||||
|
currentSessionToken: readStudentSessionCookie(c),
|
||||||
|
});
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
writeStudentSessionCookie(c, result.value.sessionToken);
|
||||||
|
return c.json({ firstLogin: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { PasskeyOptionsResult, PasskeyVerify, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import {
|
||||||
|
type AuthenticationResponseJSON,
|
||||||
|
type AuthenticatorTransportFuture,
|
||||||
|
generateAuthenticationOptions,
|
||||||
|
generateRegistrationOptions,
|
||||||
|
type RegistrationResponseJSON,
|
||||||
|
verifyAuthenticationResponse,
|
||||||
|
verifyRegistrationResponse,
|
||||||
|
} from '@simplewebauthn/server';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import {
|
||||||
|
consumeRateLimit,
|
||||||
|
createStudentSession,
|
||||||
|
describeDevice,
|
||||||
|
passkeyInvalidProblem,
|
||||||
|
revokeStudentSessionByToken,
|
||||||
|
tooManyRequestsProblem,
|
||||||
|
WEBAUTHN_CHALLENGE_TTL_MS,
|
||||||
|
webauthnConfig,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
|
type PasskeyDb = Pick<
|
||||||
|
PrismaClient,
|
||||||
|
'studentAccount' | 'studentPasskey' | 'studentWebauthnChallenge' | 'studentSession' | 'rateLimitEvent'
|
||||||
|
>;
|
||||||
|
|
||||||
|
/* The library is injectable so the tests don't need a real authenticator. */
|
||||||
|
export type WebauthnLib = {
|
||||||
|
generateRegistrationOptions: typeof generateRegistrationOptions;
|
||||||
|
verifyRegistrationResponse: typeof verifyRegistrationResponse;
|
||||||
|
generateAuthenticationOptions: typeof generateAuthenticationOptions;
|
||||||
|
verifyAuthenticationResponse: typeof verifyAuthenticationResponse;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultWebauthn: WebauthnLib = {
|
||||||
|
generateRegistrationOptions,
|
||||||
|
verifyRegistrationResponse,
|
||||||
|
generateAuthenticationOptions,
|
||||||
|
verifyAuthenticationResponse,
|
||||||
|
};
|
||||||
|
|
||||||
|
type PasskeyDeps = {
|
||||||
|
db?: PasskeyDb;
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
webauthn?: WebauthnLib;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LOGIN_OPTIONS_PER_IP = 30;
|
||||||
|
|
||||||
|
/* Optional passkeys ("Entrar con Face ID o huella"): registered from a signed-in
|
||||||
|
session; the login is discoverable (no account typed), so it works from the
|
||||||
|
"Ingresar" and "Link ya usado" pages without the teacher. */
|
||||||
|
export class StudentPasskeys {
|
||||||
|
constructor(private readonly deps: PasskeyDeps = {}) {}
|
||||||
|
|
||||||
|
private get db(): PasskeyDb {
|
||||||
|
return this.deps.db ?? prisma;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get webauthn(): WebauthnLib {
|
||||||
|
return this.deps.webauthn ?? defaultWebauthn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get now(): Date {
|
||||||
|
return this.deps.now ?? new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
async registrationOptions(accountId: string): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
|
||||||
|
const { rpID, rpName } = webauthnConfig();
|
||||||
|
const account = await this.db.studentAccount.findUniqueOrThrow({
|
||||||
|
where: { id: accountId },
|
||||||
|
select: { name: true, passkeys: { select: { credentialId: true, transports: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
const options = await this.webauthn.generateRegistrationOptions({
|
||||||
|
rpName,
|
||||||
|
rpID,
|
||||||
|
userID: new TextEncoder().encode(accountId),
|
||||||
|
userName: account.name,
|
||||||
|
userDisplayName: account.name,
|
||||||
|
attestationType: 'none',
|
||||||
|
excludeCredentials: account.passkeys.map((passkey) => ({
|
||||||
|
id: passkey.credentialId,
|
||||||
|
transports: passkey.transports as AuthenticatorTransportFuture[],
|
||||||
|
})),
|
||||||
|
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const challengeId = await this.storeChallenge(options.challenge, 'REGISTER', accountId);
|
||||||
|
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyRegistration(
|
||||||
|
accountId: string,
|
||||||
|
input: PasskeyVerify,
|
||||||
|
userAgent: string | null,
|
||||||
|
): Promise<Result<{ registered: true }, ProblemDetails>> {
|
||||||
|
const challenge = await this.takeChallenge(input.challengeId, 'REGISTER', accountId);
|
||||||
|
if (!challenge) return err(passkeyInvalidProblem());
|
||||||
|
|
||||||
|
const { rpID, origin } = webauthnConfig();
|
||||||
|
let verification: Awaited<ReturnType<typeof verifyRegistrationResponse>>;
|
||||||
|
try {
|
||||||
|
verification = await this.webauthn.verifyRegistrationResponse({
|
||||||
|
response: input.response as unknown as RegistrationResponseJSON,
|
||||||
|
expectedChallenge: challenge,
|
||||||
|
expectedOrigin: origin,
|
||||||
|
expectedRPID: rpID,
|
||||||
|
requireUserVerification: false,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn({ error: (error as Error).message }, 'Student passkey registration rejected');
|
||||||
|
return err(passkeyInvalidProblem());
|
||||||
|
}
|
||||||
|
if (!verification.verified || !verification.registrationInfo) return err(passkeyInvalidProblem());
|
||||||
|
|
||||||
|
const { credential } = verification.registrationInfo;
|
||||||
|
await this.db.studentPasskey.upsert({
|
||||||
|
where: { credentialId: credential.id },
|
||||||
|
create: {
|
||||||
|
accountId,
|
||||||
|
credentialId: credential.id,
|
||||||
|
publicKey: Uint8Array.from(credential.publicKey),
|
||||||
|
counter: credential.counter,
|
||||||
|
transports: credential.transports ?? [],
|
||||||
|
device: describeDevice(userAgent),
|
||||||
|
createdAt: this.now,
|
||||||
|
},
|
||||||
|
// Same authenticator again (excludeCredentials failed open): keep it, no takeover.
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
return ok({ registered: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async loginOptions(ip: string | null): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
|
||||||
|
const allowed = await consumeRateLimit(this.db, `passkey-login:ip:${ip ?? 'unknown'}`, {
|
||||||
|
limit: LOGIN_OPTIONS_PER_IP,
|
||||||
|
windowMs: 15 * 60 * 1000,
|
||||||
|
now: this.now,
|
||||||
|
});
|
||||||
|
if (!allowed) return err(tooManyRequestsProblem());
|
||||||
|
|
||||||
|
const { rpID } = webauthnConfig();
|
||||||
|
const options = await this.webauthn.generateAuthenticationOptions({
|
||||||
|
rpID,
|
||||||
|
userVerification: 'preferred',
|
||||||
|
});
|
||||||
|
const challengeId = await this.storeChallenge(options.challenge, 'LOGIN', null);
|
||||||
|
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyLogin(
|
||||||
|
input: PasskeyVerify,
|
||||||
|
request: { userAgent: string | null; currentSessionToken?: string },
|
||||||
|
): Promise<Result<{ sessionToken: string }, ProblemDetails>> {
|
||||||
|
const challenge = await this.takeChallenge(input.challengeId, 'LOGIN', null);
|
||||||
|
if (!challenge) return err(passkeyInvalidProblem());
|
||||||
|
|
||||||
|
const response = input.response as unknown as AuthenticationResponseJSON;
|
||||||
|
if (typeof response.id !== 'string') return err(passkeyInvalidProblem());
|
||||||
|
const passkey = await this.db.studentPasskey.findUnique({ where: { credentialId: response.id } });
|
||||||
|
if (!passkey) return err(passkeyInvalidProblem());
|
||||||
|
|
||||||
|
const { rpID, origin } = webauthnConfig();
|
||||||
|
let verification: Awaited<ReturnType<typeof verifyAuthenticationResponse>>;
|
||||||
|
try {
|
||||||
|
verification = await this.webauthn.verifyAuthenticationResponse({
|
||||||
|
response,
|
||||||
|
expectedChallenge: challenge,
|
||||||
|
expectedOrigin: origin,
|
||||||
|
expectedRPID: rpID,
|
||||||
|
credential: {
|
||||||
|
id: passkey.credentialId,
|
||||||
|
publicKey: Uint8Array.from(passkey.publicKey),
|
||||||
|
counter: passkey.counter,
|
||||||
|
transports: passkey.transports as AuthenticatorTransportFuture[],
|
||||||
|
},
|
||||||
|
requireUserVerification: false,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn({ error: (error as Error).message }, 'Student passkey login rejected');
|
||||||
|
return err(passkeyInvalidProblem());
|
||||||
|
}
|
||||||
|
if (!verification.verified) return err(passkeyInvalidProblem());
|
||||||
|
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
return unitOfWork.executeResult(async (tx) => {
|
||||||
|
await tx.studentPasskey.update({
|
||||||
|
where: { id: passkey.id },
|
||||||
|
data: { counter: verification.authenticationInfo.newCounter, lastUsedAt: this.now },
|
||||||
|
});
|
||||||
|
if (request.currentSessionToken) {
|
||||||
|
await revokeStudentSessionByToken(tx, request.currentSessionToken, this.now);
|
||||||
|
}
|
||||||
|
const sessionToken = await createStudentSession(tx, {
|
||||||
|
accountId: passkey.accountId,
|
||||||
|
userAgent: request.userAgent,
|
||||||
|
now: this.now,
|
||||||
|
});
|
||||||
|
return ok({ sessionToken });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "Quitar Face ID": removes every passkey of the account. */
|
||||||
|
async removeAll(accountId: string): Promise<Result<null, ProblemDetails>> {
|
||||||
|
await this.db.studentPasskey.deleteMany({ where: { accountId } });
|
||||||
|
return ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async storeChallenge(
|
||||||
|
challenge: string,
|
||||||
|
purpose: 'REGISTER' | 'LOGIN',
|
||||||
|
accountId: string | null,
|
||||||
|
): Promise<string> {
|
||||||
|
await this.db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: this.now } } });
|
||||||
|
const row = await this.db.studentWebauthnChallenge.create({
|
||||||
|
data: {
|
||||||
|
challenge,
|
||||||
|
purpose,
|
||||||
|
accountId,
|
||||||
|
expiresAt: new Date(this.now.getTime() + WEBAUTHN_CHALLENGE_TTL_MS),
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return row.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Single use: whoever deletes the row gets the challenge. */
|
||||||
|
private async takeChallenge(
|
||||||
|
challengeId: string,
|
||||||
|
purpose: 'REGISTER' | 'LOGIN',
|
||||||
|
accountId: string | null,
|
||||||
|
): Promise<string | null> {
|
||||||
|
const row = await this.db.studentWebauthnChallenge.findUnique({ where: { id: challengeId } });
|
||||||
|
if (!row || row.purpose !== purpose || row.accountId !== accountId || row.expiresAt <= this.now) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const deleted = await this.db.studentWebauthnChallenge.deleteMany({ where: { id: challengeId } });
|
||||||
|
return deleted.count === 1 ? row.challenge : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { conflictProblem, validationProblem } from '@/http/problem-builders';
|
||||||
|
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { type FileStorage, getFileStorage } from '@/lib/storage';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { findLinkedAttendee, storageNotAvailableProblem, studentAttendeeNotFoundProblem } from '../../lib';
|
||||||
|
|
||||||
|
type ReportPaymentDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'attendee' | 'payment'>;
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
storage?: FileStorage | null;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ReportPaymentInput = {
|
||||||
|
attendeeId: string;
|
||||||
|
paymentIds: string[];
|
||||||
|
file: { name: string; bytes: Uint8Array };
|
||||||
|
};
|
||||||
|
|
||||||
|
/* "Informar pago": the receipt goes to private storage and the report stays
|
||||||
|
REPORTED until the teacher reviews it; nothing about the fees changes here.
|
||||||
|
The fees are locked (FOR UPDATE) while checking that none of them is already
|
||||||
|
in another unreviewed report, so two concurrent reports can't overlap. */
|
||||||
|
export class ReportStudentPayment {
|
||||||
|
constructor(private readonly deps: ReportPaymentDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string, input: ReportPaymentInput): Promise<Result<{ id: string }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||||
|
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||||
|
|
||||||
|
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
|
||||||
|
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||||
|
}
|
||||||
|
const mime = detectReceiptType(input.file.bytes);
|
||||||
|
if (!mime) {
|
||||||
|
return err(validationProblem({ detail: 'El comprobante tiene que ser JPG, PNG, WEBP, HEIC o PDF.', errors: { file: ['invalid_type'] } }));
|
||||||
|
}
|
||||||
|
if (!storage) return err(storageNotAvailableProblem());
|
||||||
|
|
||||||
|
const paymentIds = [...new Set(input.paymentIds)];
|
||||||
|
const payments = await db.payment.findMany({
|
||||||
|
where: { id: { in: paymentIds }, attendeeId: attendee.id, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
select: { id: true, amount: true, currency: true },
|
||||||
|
});
|
||||||
|
if (payments.length !== paymentIds.length) {
|
||||||
|
return err(validationProblem({ detail: 'Alguna de las cuotas elegidas ya no está pendiente.', errors: { paymentIds: ['invalid'] } }));
|
||||||
|
}
|
||||||
|
const currencies = new Set(payments.map((payment) => payment.currency));
|
||||||
|
if (currencies.size !== 1) {
|
||||||
|
return err(validationProblem({ detail: 'Las cuotas tienen que ser de la misma moneda.' }));
|
||||||
|
}
|
||||||
|
const total = payments.reduce((sum, payment) => sum.add(payment.amount), new Prisma.Decimal(0));
|
||||||
|
|
||||||
|
const key = `receipts/${attendee.group.createdById}/${attendee.id}/${randomBytes(16).toString('hex')}.${RECEIPT_EXTENSIONS[mime]}`;
|
||||||
|
await storage.put(key, input.file.bytes, mime);
|
||||||
|
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const result = await unitOfWork.executeResult(async (tx) => {
|
||||||
|
await tx.$queryRaw`SELECT id FROM payments WHERE id IN (${Prisma.join(paymentIds)}) FOR UPDATE`;
|
||||||
|
const taken = await tx.reportedPaymentItem.count({
|
||||||
|
where: { paymentId: { in: paymentIds }, reportedPayment: { status: 'REPORTED' } },
|
||||||
|
});
|
||||||
|
if (taken > 0) {
|
||||||
|
return err(conflictProblem({ detail: 'Ya informaste el pago de alguna de estas cuotas.', code: 'payment_already_reported' }));
|
||||||
|
}
|
||||||
|
const report = await tx.reportedPayment.create({
|
||||||
|
data: {
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
groupId: attendee.groupId,
|
||||||
|
accountId,
|
||||||
|
totalAmount: total,
|
||||||
|
currency: [...currencies][0] as string,
|
||||||
|
receiptKey: key,
|
||||||
|
receiptMime: mime,
|
||||||
|
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
|
||||||
|
receiptSize: input.file.bytes.length,
|
||||||
|
createdAt: now,
|
||||||
|
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return ok({ id: report.id });
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
await storage.remove(key).catch((error) => logger.warn({ error }, 'Orphan receipt could not be removed'));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import {
|
||||||
|
type ConfirmRecoveryEmail as ConfirmRecoveryEmailInput,
|
||||||
|
ConfirmRecoveryEmailSchema,
|
||||||
|
type SetRecoveryEmail as SetRecoveryEmailInput,
|
||||||
|
SetRecoveryEmailSchema,
|
||||||
|
} from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { currentStudent, studentSession } from '../../middleware';
|
||||||
|
import { GetStudentMe } from '../me/use-case';
|
||||||
|
import { ConfirmRecoveryEmail, RemoveRecoveryEmail, SetRecoveryEmail } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.put('/me/recovery-email', studentSession, validate.json(SetRecoveryEmailSchema), async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
const { email } = c.req.valid('json') as SetRecoveryEmailInput;
|
||||||
|
const result = await new SetRecoveryEmail().execute(accountId, email);
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.delete('/me/recovery-email', studentSession, async (c) => {
|
||||||
|
const { accountId } = currentStudent(c);
|
||||||
|
await new RemoveRecoveryEmail().execute(accountId);
|
||||||
|
return resultJson(c, await new GetStudentMe().execute(accountId));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.post('/recovery-email/confirm', validate.json(ConfirmRecoveryEmailSchema), async (c) => {
|
||||||
|
const { token } = c.req.valid('json') as ConfirmRecoveryEmailInput;
|
||||||
|
return resultJson(c, await new ConfirmRecoveryEmail().execute(token));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { EMAIL_CONFIRMATION_TTL_HOURS, err, ok } from '@gruperly/shared';
|
||||||
|
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||||
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import {
|
||||||
|
consumeRateLimit,
|
||||||
|
generateAccessToken,
|
||||||
|
hashToken,
|
||||||
|
studentLinkInvalidProblem,
|
||||||
|
tooManyRequestsProblem,
|
||||||
|
webUrl,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
|
type RecoveryEmailDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
|
||||||
|
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||||
|
email?: Pick<EmailProvider, 'sendStudentEmailConfirmation'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CONFIRMATIONS_PER_HOUR = 5;
|
||||||
|
|
||||||
|
/* The student loads an optional recovery email. It stays "pending" until they
|
||||||
|
open the confirmation link: an unconfirmed address is never used to recover. */
|
||||||
|
export class SetRecoveryEmail {
|
||||||
|
constructor(private readonly deps: RecoveryEmailDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string, email: string): Promise<Result<{ pending: boolean }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const account = await db.studentAccount.findUniqueOrThrow({
|
||||||
|
where: { id: accountId },
|
||||||
|
select: { name: true, recoveryEmail: true },
|
||||||
|
});
|
||||||
|
if (account.recoveryEmail === email) {
|
||||||
|
await db.studentAccount.update({ where: { id: accountId }, data: { pendingRecoveryEmail: null } });
|
||||||
|
return ok({ pending: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowed = await consumeRateLimit(db, `confirm-email:account:${accountId}`, {
|
||||||
|
limit: CONFIRMATIONS_PER_HOUR,
|
||||||
|
windowMs: 60 * 60 * 1000,
|
||||||
|
now,
|
||||||
|
});
|
||||||
|
if (!allowed) return err(tooManyRequestsProblem());
|
||||||
|
|
||||||
|
const token = generateAccessToken();
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
await unitOfWork.executeResult(async (tx) => {
|
||||||
|
await tx.studentAccessToken.updateMany({
|
||||||
|
where: { accountId, kind: 'EMAIL_CONFIRMATION', usedAt: null, revokedAt: null },
|
||||||
|
data: { revokedAt: now },
|
||||||
|
});
|
||||||
|
await tx.studentAccessToken.create({
|
||||||
|
data: {
|
||||||
|
accountId,
|
||||||
|
kind: 'EMAIL_CONFIRMATION',
|
||||||
|
email,
|
||||||
|
tokenHash: hashToken(token),
|
||||||
|
expiresAt: new Date(now.getTime() + EMAIL_CONFIRMATION_TTL_HOURS * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.studentAccount.update({
|
||||||
|
where: { id: accountId },
|
||||||
|
data: { pendingRecoveryEmail: email },
|
||||||
|
});
|
||||||
|
return ok(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
const sender = this.deps.email ?? emailProvider;
|
||||||
|
try {
|
||||||
|
await sender.sendStudentEmailConfirmation({
|
||||||
|
email,
|
||||||
|
name: account.name,
|
||||||
|
url: `${webUrl()}/acceso/mail/${token}`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent');
|
||||||
|
}
|
||||||
|
return ok({ pending: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RemoveRecoveryEmail {
|
||||||
|
constructor(private readonly deps: Pick<RecoveryEmailDeps, 'db' | 'now'> = {}) {}
|
||||||
|
|
||||||
|
async execute(accountId: string): Promise<Result<null, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
await db.studentAccessToken.updateMany({
|
||||||
|
where: { accountId, kind: { in: ['EMAIL_CONFIRMATION', 'RECOVERY'] }, usedAt: null, revokedAt: null },
|
||||||
|
data: { revokedAt: this.deps.now ?? new Date() },
|
||||||
|
});
|
||||||
|
await db.studentAccount.update({
|
||||||
|
where: { id: accountId },
|
||||||
|
data: { recoveryEmail: null, recoveryEmailVerifiedAt: null, pendingRecoveryEmail: null },
|
||||||
|
});
|
||||||
|
return ok(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Public: the link may open in the mail app's browser, without the session. */
|
||||||
|
export class ConfirmRecoveryEmail {
|
||||||
|
constructor(private readonly deps: Pick<RecoveryEmailDeps, 'unitOfWork' | 'now'> = {}) {}
|
||||||
|
|
||||||
|
async execute(token: string): Promise<Result<{ email: string }, ProblemDetails>> {
|
||||||
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
const tokenHash = hashToken(token);
|
||||||
|
|
||||||
|
return unitOfWork.executeResult(async (tx) => {
|
||||||
|
const claimed = await tx.studentAccessToken.updateMany({
|
||||||
|
where: {
|
||||||
|
tokenHash,
|
||||||
|
kind: 'EMAIL_CONFIRMATION',
|
||||||
|
usedAt: null,
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: { gt: now },
|
||||||
|
},
|
||||||
|
data: { usedAt: now },
|
||||||
|
});
|
||||||
|
if (claimed.count !== 1) return err(studentLinkInvalidProblem());
|
||||||
|
|
||||||
|
const row = await tx.studentAccessToken.findUniqueOrThrow({
|
||||||
|
where: { tokenHash },
|
||||||
|
select: { accountId: true, email: true, account: { select: { pendingRecoveryEmail: true } } },
|
||||||
|
});
|
||||||
|
if (!row.email) return err(studentLinkInvalidProblem());
|
||||||
|
|
||||||
|
await tx.studentAccount.update({
|
||||||
|
where: { id: row.accountId },
|
||||||
|
data: {
|
||||||
|
recoveryEmail: row.email,
|
||||||
|
recoveryEmailVerifiedAt: now,
|
||||||
|
...(row.account.pendingRecoveryEmail === row.email ? { pendingRecoveryEmail: null } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return ok({ email: row.email });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { type RequestRecoveryLink as RequestRecoveryLinkInput, RequestRecoveryLinkSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { clientIp } from '../../lib';
|
||||||
|
import { RequestRecoveryLink } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.post('/recovery', validate.json(RequestRecoveryLinkSchema), async (c) => {
|
||||||
|
const { email } = c.req.valid('json') as RequestRecoveryLinkInput;
|
||||||
|
const result = await new RequestRecoveryLink().execute({ email, ip: clientIp(c) });
|
||||||
|
if (!result.ok) {
|
||||||
|
c.header('Retry-After', '900');
|
||||||
|
return problemJson(c, result.error);
|
||||||
|
}
|
||||||
|
return c.json({ accepted: true }, 202);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok, RECOVERY_TTL_MINUTES } from '@gruperly/shared';
|
||||||
|
import { type EmailProvider, emailProvider } from '@/lib/email';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import {
|
||||||
|
consumeRateLimit,
|
||||||
|
generateAccessToken,
|
||||||
|
hashToken,
|
||||||
|
studentLinkUrl,
|
||||||
|
tooManyRequestsProblem,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
|
type RequestRecoveryLinkDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
|
||||||
|
email?: Pick<EmailProvider, 'sendStudentRecoveryLinks'>;
|
||||||
|
/** Runs the lookup + send after answering, so the response time doesn't
|
||||||
|
* tell whether the email exists. Tests run it inline. */
|
||||||
|
defer?: (task: () => Promise<void>) => void;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const RECOVERY_LIMIT_PER_EMAIL = 3;
|
||||||
|
export const RECOVERY_LIMIT_PER_IP = 10;
|
||||||
|
const WINDOW_MS = 15 * 60 * 1000;
|
||||||
|
|
||||||
|
function runInBackground(task: () => Promise<void>) {
|
||||||
|
void task().catch((error) => logger.error({ error }, 'Student recovery link could not be sent'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "Pedir un link a mi mail". The answer is identical whether the email exists
|
||||||
|
or not; only the rate limit (3 per email and 10 per IP every 15 minutes,
|
||||||
|
counted the same for unknown emails) can say no. */
|
||||||
|
export class RequestRecoveryLink {
|
||||||
|
constructor(private readonly deps: RequestRecoveryLinkDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(input: { email: string; ip: string | null }): Promise<Result<{ accepted: true }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const ipAllowed = await consumeRateLimit(db, `recovery:ip:${input.ip ?? 'unknown'}`, {
|
||||||
|
limit: RECOVERY_LIMIT_PER_IP,
|
||||||
|
windowMs: WINDOW_MS,
|
||||||
|
now,
|
||||||
|
});
|
||||||
|
if (!ipAllowed) return err(tooManyRequestsProblem());
|
||||||
|
|
||||||
|
const emailKey = createHash('sha256').update(input.email).digest('hex');
|
||||||
|
const emailAllowed = await consumeRateLimit(db, `recovery:email:${emailKey}`, {
|
||||||
|
limit: RECOVERY_LIMIT_PER_EMAIL,
|
||||||
|
windowMs: WINDOW_MS,
|
||||||
|
now,
|
||||||
|
});
|
||||||
|
if (!emailAllowed) return err(tooManyRequestsProblem());
|
||||||
|
|
||||||
|
(this.deps.defer ?? runInBackground)(() => this.send(db, input.email, now));
|
||||||
|
return ok({ accepted: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async send(
|
||||||
|
db: NonNullable<RequestRecoveryLinkDeps['db']>,
|
||||||
|
email: string,
|
||||||
|
now: Date,
|
||||||
|
): Promise<void> {
|
||||||
|
const accounts = await db.studentAccount.findMany({
|
||||||
|
where: { recoveryEmail: email, recoveryEmailVerifiedAt: { not: null } },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
if (accounts.length === 0) return;
|
||||||
|
|
||||||
|
const links: { name: string; url: string }[] = [];
|
||||||
|
for (const account of accounts) {
|
||||||
|
const token = generateAccessToken();
|
||||||
|
await db.studentAccessToken.create({
|
||||||
|
data: {
|
||||||
|
accountId: account.id,
|
||||||
|
kind: 'RECOVERY',
|
||||||
|
tokenHash: hashToken(token),
|
||||||
|
expiresAt: new Date(now.getTime() + RECOVERY_TTL_MINUTES * 60 * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
links.push({ name: account.name, url: studentLinkUrl(token) });
|
||||||
|
}
|
||||||
|
await (this.deps.email ?? emailProvider).sendStudentRecoveryLinks({ email, links });
|
||||||
|
}
|
||||||
|
}
|
||||||
1
apps/backend/src/modules/student-portal/index.ts
Normal file
1
apps/backend/src/modules/student-portal/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { default as studentPortalRoutes } from './routes';
|
||||||
49
apps/backend/src/modules/student-portal/lib/access.ts
Normal file
49
apps/backend/src/modules/student-portal/lib/access.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import type { Prisma } from '@generated/prisma/client';
|
||||||
|
|
||||||
|
export type StudentAccessDb = {
|
||||||
|
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* The authorization rule of every student endpoint: only the attendees linked
|
||||||
|
to the session's account. Anything else is a 404 (we don't confirm ids). */
|
||||||
|
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
|
||||||
|
const links = await db.studentAccountAttendee.findMany({
|
||||||
|
// A DROPPED attendee loses access; a PAUSED one keeps it.
|
||||||
|
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
|
||||||
|
select: { attendeeId: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
});
|
||||||
|
return links.map((link) => link.attendeeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||||
|
|
||||||
|
/* One attendee of the session, with what the student screens need from the
|
||||||
|
group. null for an attendee not linked to the account (or DROPPED): routes
|
||||||
|
answer 404, the same as for an id that doesn't exist. */
|
||||||
|
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||||
|
return db.attendee.findFirst({
|
||||||
|
where: {
|
||||||
|
id: attendeeId,
|
||||||
|
status: { not: 'DROPPED' },
|
||||||
|
studentAccounts: { some: { accountId } },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
fullName: true,
|
||||||
|
groupId: true,
|
||||||
|
group: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
days: true,
|
||||||
|
time: true,
|
||||||
|
createdById: true,
|
||||||
|
owner: { select: { name: true, country: true, transferAlias: true, transferHolder: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LinkedAttendee = NonNullable<Awaited<ReturnType<typeof findLinkedAttendee>>>;
|
||||||
31
apps/backend/src/modules/student-portal/lib/device.ts
Normal file
31
apps/backend/src/modules/student-portal/lib/device.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
/* Human-readable device from the user agent ("iPhone · Safari"), shown to the
|
||||||
|
teacher in "Acceso a la app". Best effort: never used for security. */
|
||||||
|
export function describeDevice(userAgent: string | null | undefined): string {
|
||||||
|
const ua = userAgent ?? '';
|
||||||
|
const platform = detectPlatform(ua);
|
||||||
|
const browser = detectBrowser(ua);
|
||||||
|
if (platform && browser) return `${platform} · ${browser}`;
|
||||||
|
return platform ?? browser ?? 'Dispositivo desconocido';
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectPlatform(ua: string): string | null {
|
||||||
|
if (/iPhone/i.test(ua)) return 'iPhone';
|
||||||
|
if (/iPad/i.test(ua)) return 'iPad';
|
||||||
|
if (/Android/i.test(ua)) return /Mobile/i.test(ua) ? 'Android' : 'Tablet Android';
|
||||||
|
if (/CrOS/i.test(ua)) return 'Chromebook';
|
||||||
|
if (/Macintosh|Mac OS X/i.test(ua)) return 'Mac';
|
||||||
|
if (/Windows/i.test(ua)) return 'Windows';
|
||||||
|
if (/Linux/i.test(ua)) return 'Linux';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectBrowser(ua: string): string | null {
|
||||||
|
// Order matters: Edge, Opera and Samsung also say "Chrome"; every iOS browser says "Safari".
|
||||||
|
if (/EdgiOS|Edg\//i.test(ua)) return 'Edge';
|
||||||
|
if (/OPR\/|OPiOS/i.test(ua)) return 'Opera';
|
||||||
|
if (/SamsungBrowser/i.test(ua)) return 'Samsung Internet';
|
||||||
|
if (/FxiOS|Firefox\//i.test(ua)) return 'Firefox';
|
||||||
|
if (/CriOS|Chrome\//i.test(ua)) return 'Chrome';
|
||||||
|
if (/Safari\//i.test(ua)) return 'Safari';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
9
apps/backend/src/modules/student-portal/lib/index.ts
Normal file
9
apps/backend/src/modules/student-portal/lib/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export * from './access';
|
||||||
|
export * from './device';
|
||||||
|
export * from './problems';
|
||||||
|
export * from './rate-limit';
|
||||||
|
export * from './request';
|
||||||
|
export * from './schedule';
|
||||||
|
export * from './session';
|
||||||
|
export * from './tokens';
|
||||||
|
export * from './webauthn';
|
||||||
72
apps/backend/src/modules/student-portal/lib/problems.ts
Normal file
72
apps/backend/src/modules/student-portal/lib/problems.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import type { ProblemDetails } from '@gruperly/shared';
|
||||||
|
import { problemDetails } from '@/http/problem-details';
|
||||||
|
import { PROBLEM_DOMAIN } from '@/http/problem-domain';
|
||||||
|
|
||||||
|
export function studentLinkInvalidProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/student-link-invalid`,
|
||||||
|
title: 'Gone',
|
||||||
|
status: 410,
|
||||||
|
detail: 'Este link ya fue usado o venció.',
|
||||||
|
code: 'student_link_invalid',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function passkeyInvalidProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/passkey-invalid`,
|
||||||
|
title: 'Bad Request',
|
||||||
|
status: 400,
|
||||||
|
detail: 'No pudimos verificar la llave de acceso.',
|
||||||
|
code: 'passkey_invalid',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tooManyRequestsProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/too-many-requests`,
|
||||||
|
title: 'Too Many Requests',
|
||||||
|
status: 429,
|
||||||
|
detail: 'Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos.',
|
||||||
|
code: 'too_many_requests',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function crossOriginProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/forbidden`,
|
||||||
|
title: 'Forbidden',
|
||||||
|
status: 403,
|
||||||
|
detail: 'Origen no permitido.',
|
||||||
|
code: 'cross_origin_request',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function studentAttendeeNotFoundProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
title: 'Not Found',
|
||||||
|
status: 404,
|
||||||
|
detail: 'The requested resource was not found.',
|
||||||
|
code: 'not_found',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function classAlreadyStartedProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
||||||
|
title: 'Conflict',
|
||||||
|
status: 409,
|
||||||
|
detail: 'La clase ya empezó: el aviso solo se puede dar o deshacer antes.',
|
||||||
|
code: 'class_already_started',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function storageNotAvailableProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
type: `${PROBLEM_DOMAIN}/problems/service-unavailable`,
|
||||||
|
title: 'Service Unavailable',
|
||||||
|
status: 503,
|
||||||
|
detail: 'Por ahora no se pueden adjuntar comprobantes.',
|
||||||
|
code: 'storage_not_available',
|
||||||
|
});
|
||||||
|
}
|
||||||
19
apps/backend/src/modules/student-portal/lib/rate-limit.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/rate-limit.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { Prisma } from '@generated/prisma/client';
|
||||||
|
|
||||||
|
export type RateLimitDb = { rateLimitEvent: Prisma.RateLimitEventDelegate };
|
||||||
|
|
||||||
|
/* Sliding window counted in `rate_limit_events`: returns false (and records
|
||||||
|
nothing) once `key` reached `limit` hits inside the window. Old hits of the
|
||||||
|
same key are swept on the way. */
|
||||||
|
export async function consumeRateLimit(
|
||||||
|
db: RateLimitDb,
|
||||||
|
key: string,
|
||||||
|
options: { limit: number; windowMs: number; now: Date },
|
||||||
|
): Promise<boolean> {
|
||||||
|
const windowStart = new Date(options.now.getTime() - options.windowMs);
|
||||||
|
await db.rateLimitEvent.deleteMany({ where: { key, createdAt: { lt: windowStart } } });
|
||||||
|
const hits = await db.rateLimitEvent.count({ where: { key, createdAt: { gte: windowStart } } });
|
||||||
|
if (hits >= options.limit) return false;
|
||||||
|
await db.rateLimitEvent.create({ data: { key, createdAt: options.now } });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
19
apps/backend/src/modules/student-portal/lib/request.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/request.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { Context } from 'hono';
|
||||||
|
|
||||||
|
/* Client IP for the rate limit and the token audit. Each proxy appends to
|
||||||
|
X-Forwarded-For, so the client is the entry `TRUSTED_PROXY_HOPS` from the end
|
||||||
|
(1 = only our nginx; 2 = Traefik + nginx). Entries further left can be forged
|
||||||
|
by the client and are ignored. */
|
||||||
|
export function clientIp(c: Context): string | null {
|
||||||
|
const hops = Math.max(1, Number(process.env.TRUSTED_PROXY_HOPS ?? 1) || 1);
|
||||||
|
const chain = (c.req.header('X-Forwarded-For') ?? '')
|
||||||
|
.split(',')
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (chain.length >= hops) return chain[chain.length - hops] ?? null;
|
||||||
|
return c.req.header('X-Real-IP') ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function userAgent(c: Context): string | null {
|
||||||
|
return c.req.header('User-Agent')?.slice(0, 512) ?? null;
|
||||||
|
}
|
||||||
7
apps/backend/src/modules/student-portal/lib/schedule.ts
Normal file
7
apps/backend/src/modules/student-portal/lib/schedule.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { COUNTRY_TIME_ZONES, type CountryCode } from '@gruperly/shared';
|
||||||
|
import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler';
|
||||||
|
|
||||||
|
// The class schedule runs on the teacher's clock (their country).
|
||||||
|
export function teacherTimeZone(country: string | null | undefined): string {
|
||||||
|
return (country && COUNTRY_TIME_ZONES[country as CountryCode]) || DEFAULT_TIME_ZONE;
|
||||||
|
}
|
||||||
99
apps/backend/src/modules/student-portal/lib/session.ts
Normal file
99
apps/backend/src/modules/student-portal/lib/session.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import type { Prisma } from '@generated/prisma/client';
|
||||||
|
import { STUDENT_SESSION_TTL_DAYS } from '@gruperly/shared';
|
||||||
|
import type { Context } from 'hono';
|
||||||
|
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||||
|
import { describeDevice } from './device';
|
||||||
|
import { generateAccessToken, hashToken, webUrl } from './tokens';
|
||||||
|
|
||||||
|
export type StudentSessionDb = { studentSession: Prisma.StudentSessionDelegate };
|
||||||
|
|
||||||
|
const COOKIE_NAME = 'gruperly_student';
|
||||||
|
const SESSION_TTL_MS = STUDENT_SESSION_TTL_DAYS * 24 * 60 * 60 * 1000;
|
||||||
|
// Sliding renewal is written at most once per hour, not on every request.
|
||||||
|
const TOUCH_INTERVAL_MS = 60 * 60 * 1000;
|
||||||
|
|
||||||
|
// Its own cookie, never Better Auth's: a student session can't reach the
|
||||||
|
// teacher's endpoints and a teacher session can't reach the student's.
|
||||||
|
// With HTTPS it carries the `__Host-` prefix (Secure, Path=/, no Domain).
|
||||||
|
function isSecure(): boolean {
|
||||||
|
return webUrl().startsWith('https://');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readStudentSessionCookie(c: Context): string | undefined {
|
||||||
|
return isSecure() ? getCookie(c, COOKIE_NAME, 'host') : getCookie(c, COOKIE_NAME);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeStudentSessionCookie(c: Context, token: string): void {
|
||||||
|
setCookie(c, COOKIE_NAME, token, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: isSecure(),
|
||||||
|
sameSite: 'Lax',
|
||||||
|
path: '/',
|
||||||
|
maxAge: SESSION_TTL_MS / 1000,
|
||||||
|
...(isSecure() ? { prefix: 'host' as const } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearStudentSessionCookie(c: Context): void {
|
||||||
|
deleteCookie(c, COOKIE_NAME, {
|
||||||
|
path: '/',
|
||||||
|
secure: isSecure(),
|
||||||
|
...(isSecure() ? { prefix: 'host' as const } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A brand-new identifier on every sign-in (link or passkey): sessions are never
|
||||||
|
reused or upgraded. Returns the raw token for the cookie. */
|
||||||
|
export async function createStudentSession(
|
||||||
|
db: StudentSessionDb,
|
||||||
|
input: { accountId: string; userAgent: string | null | undefined; now: Date },
|
||||||
|
): Promise<string> {
|
||||||
|
const token = generateAccessToken();
|
||||||
|
await db.studentSession.create({
|
||||||
|
data: {
|
||||||
|
accountId: input.accountId,
|
||||||
|
tokenHash: hashToken(token),
|
||||||
|
device: describeDevice(input.userAgent),
|
||||||
|
createdAt: input.now,
|
||||||
|
lastUsedAt: input.now,
|
||||||
|
expiresAt: new Date(input.now.getTime() + SESSION_TTL_MS),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ResolvedStudentSession = {
|
||||||
|
sessionId: string;
|
||||||
|
accountId: string;
|
||||||
|
/** The expiry moved forward: the cookie has to be written again. */
|
||||||
|
renewed: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function resolveStudentSession(
|
||||||
|
db: StudentSessionDb,
|
||||||
|
token: string,
|
||||||
|
now: Date,
|
||||||
|
): Promise<ResolvedStudentSession | null> {
|
||||||
|
const session = await db.studentSession.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||||
|
if (!session || session.revokedAt || session.expiresAt <= now) return null;
|
||||||
|
|
||||||
|
const renewed = now.getTime() - session.lastUsedAt.getTime() >= TOUCH_INTERVAL_MS;
|
||||||
|
if (renewed) {
|
||||||
|
await db.studentSession.update({
|
||||||
|
where: { id: session.id },
|
||||||
|
data: { lastUsedAt: now, expiresAt: new Date(now.getTime() + SESSION_TTL_MS) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { sessionId: session.id, accountId: session.accountId, renewed };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeStudentSessionByToken(
|
||||||
|
db: StudentSessionDb,
|
||||||
|
token: string,
|
||||||
|
now: Date,
|
||||||
|
): Promise<void> {
|
||||||
|
await db.studentSession.updateMany({
|
||||||
|
where: { tokenHash: hashToken(token), revokedAt: null },
|
||||||
|
data: { revokedAt: now },
|
||||||
|
});
|
||||||
|
}
|
||||||
19
apps/backend/src/modules/student-portal/lib/tokens.ts
Normal file
19
apps/backend/src/modules/student-portal/lib/tokens.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { createHash, randomBytes } from 'node:crypto';
|
||||||
|
|
||||||
|
// 32 bytes from the CSPRNG, base64url: what travels in links and cookies.
|
||||||
|
export function generateAccessToken(): string {
|
||||||
|
return randomBytes(32).toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only this goes to the database.
|
||||||
|
export function hashToken(token: string): string {
|
||||||
|
return createHash('sha256').update(token).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function webUrl(): string {
|
||||||
|
return (process.env.WEB_URL ?? 'http://localhost:6173').replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function studentLinkUrl(token: string): string {
|
||||||
|
return `${webUrl()}/i/${token}`;
|
||||||
|
}
|
||||||
14
apps/backend/src/modules/student-portal/lib/webauthn.ts
Normal file
14
apps/backend/src/modules/student-portal/lib/webauthn.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { webUrl } from './tokens';
|
||||||
|
|
||||||
|
// Relying party: the web's host. Override them when the web is served from
|
||||||
|
// another origin than WEB_URL (e.g. a tunnel to test on a phone).
|
||||||
|
export function webauthnConfig() {
|
||||||
|
const origin = process.env.WEBAUTHN_ORIGIN || webUrl();
|
||||||
|
return {
|
||||||
|
rpName: 'Gruperly',
|
||||||
|
rpID: process.env.WEBAUTHN_RP_ID || new URL(origin).hostname,
|
||||||
|
origin,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const WEBAUTHN_CHALLENGE_TTL_MS = 5 * 60 * 1000;
|
||||||
57
apps/backend/src/modules/student-portal/middleware.ts
Normal file
57
apps/backend/src/modules/student-portal/middleware.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import type { Context, MiddlewareHandler } from 'hono';
|
||||||
|
import type { BackendEnv, StudentContext } from '@/http/env';
|
||||||
|
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import {
|
||||||
|
crossOriginProblem,
|
||||||
|
readStudentSessionCookie,
|
||||||
|
resolveStudentSession,
|
||||||
|
type StudentSessionDb,
|
||||||
|
webUrl,
|
||||||
|
writeStudentSessionCookie,
|
||||||
|
} from './lib';
|
||||||
|
|
||||||
|
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||||
|
|
||||||
|
/* CSRF: besides SameSite=Lax, every state-changing request must come from the
|
||||||
|
web's origin. Browsers always send `Origin` on POST/PATCH/DELETE, so a
|
||||||
|
missing header is rejected too. */
|
||||||
|
export const studentOriginGuard: MiddlewareHandler = async (c, next) => {
|
||||||
|
if (SAFE_METHODS.has(c.req.method)) {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const allowed = new Set([webUrl(), process.env.WEBAUTHN_ORIGIN].filter(Boolean));
|
||||||
|
const origin = c.req.header('Origin');
|
||||||
|
if (!origin || !allowed.has(origin)) {
|
||||||
|
return problemJson(c, crossOriginProblem());
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
};
|
||||||
|
|
||||||
|
export function requireStudentSession(
|
||||||
|
deps: { db?: StudentSessionDb; now?: () => Date } = {},
|
||||||
|
): MiddlewareHandler {
|
||||||
|
return async (c, next) => {
|
||||||
|
const token = readStudentSessionCookie(c);
|
||||||
|
const session = token
|
||||||
|
? await resolveStudentSession(deps.db ?? prisma, token, (deps.now ?? (() => new Date()))())
|
||||||
|
: null;
|
||||||
|
if (!token || !session) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
// Sliding session: the cookie's Max-Age moves with the stored expiry.
|
||||||
|
if (session.renewed) writeStudentSessionCookie(c, token);
|
||||||
|
c.set('student', { accountId: session.accountId, sessionId: session.sessionId });
|
||||||
|
await next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const studentSession = requireStudentSession();
|
||||||
|
|
||||||
|
/** The signed-in student, on a route behind `studentSession`. */
|
||||||
|
export function currentStudent(c: Context<BackendEnv>): StudentContext {
|
||||||
|
const student = c.get('student');
|
||||||
|
if (!student) throw new Error('currentStudent() used on a route without studentSession');
|
||||||
|
return student;
|
||||||
|
}
|
||||||
31
apps/backend/src/modules/student-portal/routes.ts
Normal file
31
apps/backend/src/modules/student-portal/routes.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import classesRoute from './features/classes/route';
|
||||||
|
import consumeLinkRoute from './features/consume-link/route';
|
||||||
|
import feesRoute from './features/fees/route';
|
||||||
|
import linkInfoRoute from './features/link-info/route';
|
||||||
|
import logoutRoute from './features/logout/route';
|
||||||
|
import meRoute from './features/me/route';
|
||||||
|
import passkeysRoute from './features/passkeys/route';
|
||||||
|
import recoveryEmailRoute from './features/recovery-email/route';
|
||||||
|
import requestRecoveryRoute from './features/request-recovery/route';
|
||||||
|
import { studentOriginGuard } from './middleware';
|
||||||
|
|
||||||
|
/* Student API. Outside the teacher's session middleware (public prefix): each
|
||||||
|
private route declares `studentSession`, which only accepts the student
|
||||||
|
cookie. Every state-changing request passes the Origin check (CSRF). */
|
||||||
|
const routes = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
routes.use('*', studentOriginGuard);
|
||||||
|
|
||||||
|
routes.route('/', linkInfoRoute);
|
||||||
|
routes.route('/', consumeLinkRoute);
|
||||||
|
routes.route('/', requestRecoveryRoute);
|
||||||
|
routes.route('/', meRoute);
|
||||||
|
routes.route('/', logoutRoute);
|
||||||
|
routes.route('/', recoveryEmailRoute);
|
||||||
|
routes.route('/', passkeysRoute);
|
||||||
|
routes.route('/', classesRoute);
|
||||||
|
routes.route('/', feesRoute);
|
||||||
|
|
||||||
|
export default routes;
|
||||||
@@ -60,6 +60,8 @@ export class SendPaymentReminders {
|
|||||||
checkoutUrl: { not: null },
|
checkoutUrl: { not: null },
|
||||||
dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
|
dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
|
||||||
attendee: { status: 'ACTIVE' },
|
attendee: { status: 'ACTIVE' },
|
||||||
|
// Already reported by the student: the teacher is reviewing it.
|
||||||
|
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { CountryCode } from '@gruperly/shared';
|
import type { CountryCode } from '@gruperly/shared';
|
||||||
import { DEFAULT_COUNTRY } from '@gruperly/shared';
|
import { COUNTRY_TIME_ZONES, DEFAULT_COUNTRY } from '@gruperly/shared';
|
||||||
|
|
||||||
/* Amounts and dates go inside a WhatsApp message, so they are formatted the way
|
/* Amounts and dates go inside a WhatsApp message, so they are formatted the way
|
||||||
people in the teacher's country write them (the student is there too). */
|
people in the teacher's country write them (the student is there too). */
|
||||||
@@ -14,15 +14,7 @@ const LOCALES: Record<CountryCode, string> = {
|
|||||||
UY: 'es-UY',
|
UY: 'es-UY',
|
||||||
};
|
};
|
||||||
|
|
||||||
const TIME_ZONES: Record<CountryCode, string> = {
|
const TIME_ZONES = COUNTRY_TIME_ZONES;
|
||||||
AR: 'America/Argentina/Buenos_Aires',
|
|
||||||
BR: 'America/Sao_Paulo',
|
|
||||||
CL: 'America/Santiago',
|
|
||||||
CO: 'America/Bogota',
|
|
||||||
MX: 'America/Mexico_City',
|
|
||||||
PE: 'America/Lima',
|
|
||||||
UY: 'America/Montevideo',
|
|
||||||
};
|
|
||||||
|
|
||||||
/** `25000` ARS → `$ 25.000`; cents only when there are any. */
|
/** `25000` ARS → `$ 25.000`; cents only when there are any. */
|
||||||
export function formatAmount(
|
export function formatAmount(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { logger } from '@/logger';
|
|||||||
import { startBillingJobs } from '@/modules/billing';
|
import { startBillingJobs } from '@/modules/billing';
|
||||||
import { startMpJobs } from '@/modules/mp';
|
import { startMpJobs } from '@/modules/mp';
|
||||||
import { startPaymentJobs } from '@/modules/payments';
|
import { startPaymentJobs } from '@/modules/payments';
|
||||||
|
import { startStudentAccessJobs } from '@/modules/student-access';
|
||||||
import { startWhatsappJobs } from '@/modules/whatsapp';
|
import { startWhatsappJobs } from '@/modules/whatsapp';
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 4000);
|
const port = Number(process.env.PORT ?? 4000);
|
||||||
@@ -19,6 +20,7 @@ startMpJobs();
|
|||||||
startPaymentJobs();
|
startPaymentJobs();
|
||||||
startWhatsappJobs();
|
startWhatsappJobs();
|
||||||
startBillingJobs();
|
startBillingJobs();
|
||||||
|
startStudentAccessJobs();
|
||||||
|
|
||||||
async function shutdown(): Promise<void> {
|
async function shutdown(): Promise<void> {
|
||||||
server.stop(true);
|
server.stop(true);
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cuenta el motivo: faltas seguidas y asistencia baja, 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'),
|
||||||
@@ -113,6 +113,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||||
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
|
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
|
||||||
|
{ id: 's7', groupId: 'group-1', startsAt: at(15) },
|
||||||
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
|
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
|
||||||
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
||||||
]);
|
]);
|
||||||
@@ -121,11 +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)),
|
||||||
// No streak, but attends less than half of the month's classes.
|
// No streak (they came to s2), but 4 of their last 5 classes missed:
|
||||||
attendance('a-2', 's1', 'PRESENT', at(1)),
|
// high risk through the window, not through the streak.
|
||||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
attendance('a-2', 's1', 'ABSENT', at(1)),
|
||||||
|
attendance('a-2', 's2', 'PRESENT', at(2)),
|
||||||
attendance('a-2', 's3', 'ABSENT', at(3)),
|
attendance('a-2', 's3', 'ABSENT', at(3)),
|
||||||
attendance('a-2', 's4', 'ABSENT', at(4)),
|
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)),
|
||||||
@@ -144,7 +147,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
{
|
{
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
groupName: 'Funcional',
|
groupName: 'Funcional',
|
||||||
riskLevel: 'MEDIUM',
|
riskLevel: 'HIGH',
|
||||||
absenceStreakCount: 1,
|
absenceStreakCount: 1,
|
||||||
lowAttendanceCount: 1,
|
lowAttendanceCount: 1,
|
||||||
},
|
},
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
import { describe, expect, it } from 'bun:test';
|
import { describe, expect, it } from 'bun:test';
|
||||||
import {
|
import { lastAttendedAt, monthlyAttendanceRate } from '@/modules/analytics/lib/risk';
|
||||||
classifyRisk,
|
|
||||||
lastAttendedAt,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '@/modules/analytics/lib/risk';
|
|
||||||
|
|
||||||
const day = 24 * 60 * 60 * 1000;
|
const day = 24 * 60 * 60 * 1000;
|
||||||
const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
||||||
@@ -12,25 +7,6 @@ const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
|||||||
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
||||||
return { status, occurredAt: at(offsetDays) };
|
return { status, occurredAt: at(offsetDays) };
|
||||||
}
|
}
|
||||||
describe('trailingAbsentStreak', () => {
|
|
||||||
it('devuelve 0 sin registros', () => {
|
|
||||||
expect(trailingAbsentStreak([])).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('cuenta ausencias consecutivas sin justificar desde la más reciente', () => {
|
|
||||||
expect(trailingAbsentStreak([entry('ABSENT', 0)])).toBe(1);
|
|
||||||
expect(trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('ABSENT', 14)])).toBe(3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rompe la cadena con PRESENT o EXCUSED', () => {
|
|
||||||
expect(
|
|
||||||
trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('PRESENT', 14)]),
|
|
||||||
).toBe(2);
|
|
||||||
expect(trailingAbsentStreak([entry('EXCUSED', 0), entry('ABSENT', 7)])).toBe(0);
|
|
||||||
expect(trailingAbsentStreak([entry('PRESENT', 0)])).toBe(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('lastAttendedAt', () => {
|
describe('lastAttendedAt', () => {
|
||||||
it('devuelve la clase PRESENT más reciente', () => {
|
it('devuelve la clase PRESENT más reciente', () => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -59,21 +35,3 @@ describe('monthlyAttendanceRate', () => {
|
|||||||
expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0);
|
expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('classifyRisk', () => {
|
|
||||||
it('HIGH con 3 o más ausencias consecutivas', () => {
|
|
||||||
expect(classifyRisk(3, 80)).toBe('HIGH');
|
|
||||||
expect(classifyRisk(5, 20)).toBe('HIGH');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('MEDIUM con 2 ausencias consecutivas o asistencia menor al 50%', () => {
|
|
||||||
expect(classifyRisk(2, 90)).toBe('MEDIUM');
|
|
||||||
expect(classifyRisk(1, 40)).toBe('MEDIUM');
|
|
||||||
expect(classifyRisk(2, 40)).toBe('MEDIUM');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sin riesgo si no cumple ningún umbral', () => {
|
|
||||||
expect(classifyRisk(1, 60)).toBeNull();
|
|
||||||
expect(classifyRisk(0, 60)).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -16,6 +16,7 @@ const db = {
|
|||||||
},
|
},
|
||||||
attendance: {
|
attendance: {
|
||||||
findMany: mock(),
|
findMany: mock(),
|
||||||
|
findFirst: mock(),
|
||||||
},
|
},
|
||||||
slotRelease: {
|
slotRelease: {
|
||||||
count: mock(),
|
count: mock(),
|
||||||
@@ -133,24 +134,35 @@ describe('analytics routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('GET /groups/:groupId/students-at-risk', () => {
|
describe('GET /groups/:groupId/students-at-risk', () => {
|
||||||
const sessions = [at(0), at(7), at(14), at(21)];
|
// Every 3 days: with weekly classes two absences already add up to 14 days
|
||||||
|
// without coming, and the inactivity rule would turn the MEDIUM case HIGH.
|
||||||
|
const sessions = [at(0), at(3), at(6), at(9)];
|
||||||
|
const sessionRows = sessions.map((startsAt, index) => ({ id: `s${index}`, startsAt: new Date(startsAt) }));
|
||||||
|
const enrolled = new Date(at(60));
|
||||||
|
// `offset` is the index in `sessions`: 0 is the most recent class.
|
||||||
|
const row = (attendeeId: string, status: string, offset: number) => ({
|
||||||
|
attendeeId,
|
||||||
|
classSessionId: `s${offset}`,
|
||||||
|
status,
|
||||||
|
classSession: { startsAt: new Date(sessions[offset]) },
|
||||||
|
});
|
||||||
|
|
||||||
it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => {
|
it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt })));
|
prisma.classSession.findMany.mockResolvedValue(sessionRows);
|
||||||
prisma.attendee.findMany.mockResolvedValue([
|
prisma.attendee.findMany.mockResolvedValue([
|
||||||
{ id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111' },
|
{ id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111', createdAt: enrolled },
|
||||||
{ id: 'a-2', fullName: 'Bruno Díaz', phone: null },
|
{ id: 'a-2', fullName: 'Bruno Díaz', phone: null, createdAt: enrolled },
|
||||||
]);
|
]);
|
||||||
prisma.attendance.findMany.mockResolvedValue([
|
prisma.attendance.findMany.mockResolvedValue([
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } },
|
row('a-1', 'ABSENT', 0),
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } },
|
row('a-1', 'ABSENT', 1),
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(14)) } },
|
row('a-1', 'ABSENT', 2),
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } },
|
row('a-1', 'PRESENT', 3),
|
||||||
{ attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } },
|
row('a-2', 'ABSENT', 0),
|
||||||
{ attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } },
|
row('a-2', 'ABSENT', 1),
|
||||||
{ attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(14)) } },
|
row('a-2', 'PRESENT', 2),
|
||||||
{ attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } },
|
row('a-2', 'PRESENT', 3),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
||||||
@@ -165,7 +177,7 @@ describe('analytics routes', () => {
|
|||||||
phone: '+521111111111',
|
phone: '+521111111111',
|
||||||
riskLevel: 'HIGH',
|
riskLevel: 'HIGH',
|
||||||
consecutiveAbsences: 3,
|
consecutiveAbsences: 3,
|
||||||
lastAttendedAt: at(21),
|
lastAttendedAt: sessions[3],
|
||||||
monthlyAttendanceRate: 25,
|
monthlyAttendanceRate: 25,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -174,7 +186,7 @@ describe('analytics routes', () => {
|
|||||||
phone: null,
|
phone: null,
|
||||||
riskLevel: 'MEDIUM',
|
riskLevel: 'MEDIUM',
|
||||||
consecutiveAbsences: 2,
|
consecutiveAbsences: 2,
|
||||||
lastAttendedAt: at(14),
|
lastAttendedAt: sessions[2],
|
||||||
monthlyAttendanceRate: 50,
|
monthlyAttendanceRate: 50,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -183,14 +195,11 @@ describe('analytics routes', () => {
|
|||||||
|
|
||||||
it('devuelve lista vacía cuando nadie está en riesgo', async () => {
|
it('devuelve lista vacía cuando nadie está en riesgo', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt })));
|
prisma.classSession.findMany.mockResolvedValue(sessionRows);
|
||||||
prisma.attendee.findMany.mockResolvedValue([
|
prisma.attendee.findMany.mockResolvedValue([
|
||||||
{ id: 'a-1', fullName: 'Ana Pérez', phone: null },
|
{ id: 'a-1', fullName: 'Ana Pérez', phone: null, createdAt: enrolled },
|
||||||
]);
|
|
||||||
prisma.attendance.findMany.mockResolvedValue([
|
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(0)) } },
|
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(7)) } },
|
|
||||||
]);
|
]);
|
||||||
|
prisma.attendance.findMany.mockResolvedValue([row('a-1', 'PRESENT', 0), row('a-1', 'PRESENT', 1)]);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
||||||
|
|
||||||
@@ -243,6 +252,29 @@ describe('analytics routes', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('arranca en la primera clase registrada si es anterior al alta', async () => {
|
||||||
|
// Loaded on 1/10 with classes already marked since 20/9: the history
|
||||||
|
// starts at the first one, as the risk rule and the group list count it.
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue({
|
||||||
|
id: 'a-1',
|
||||||
|
fullName: 'Ana Pérez',
|
||||||
|
createdAt: new Date('2026-10-01T00:00:00.000Z'),
|
||||||
|
});
|
||||||
|
prisma.attendance.findFirst.mockResolvedValueOnce({
|
||||||
|
classSession: { startsAt: new Date('2026-09-20T10:00:00.000Z') },
|
||||||
|
});
|
||||||
|
prisma.classSession.findMany.mockResolvedValue([]);
|
||||||
|
|
||||||
|
await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1/history');
|
||||||
|
|
||||||
|
expect(prisma.classSession.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: { groupId: 'group-1', startsAt: { gte: new Date('2026-09-20T10:00:00.000Z') } },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('devuelve 404 si el alumno no pertenece al grupo', async () => {
|
it('devuelve 404 si el alumno no pertenece al grupo', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
|
|||||||
@@ -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,63 +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('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
|
it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => {
|
||||||
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
|
const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
|
||||||
// Two streak absences: attention comes from the streak, and exactly 10 days
|
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||||
// does not move the level.
|
expect(señales.highWindow.absences).toBe(3);
|
||||||
expect(
|
expect(señales.attentionWindow).toEqual({ absences: 2, classes: 4 });
|
||||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
|
|
||||||
).toBe('atencion');
|
|
||||||
expect(
|
|
||||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
|
|
||||||
).toBe('riesgo_alto');
|
|
||||||
});
|
|
||||||
|
|
||||||
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');
|
expect(señales.level).toBe('atencion');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('perder una sola clase no es tendencia', () => {
|
it('2 faltas en las últimas 4 clases dan atención', () => {
|
||||||
// Same case as the previous one with one class fewer missed in the recent
|
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
|
||||||
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
|
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion');
|
||||||
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', () => {
|
it('una sola falta reciente no alcanza', () => {
|
||||||
// 5 marked classes: the previous window would be left with a single one, so
|
const alumno = member(dense(['ABSENT', 'ABSENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT']));
|
||||||
// there is nothing to compare against.
|
// The two old absences fall outside the short window (last 4).
|
||||||
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
|
expect(summarizeMemberAttendance(alumno, NOW).attentionWindow.absences).toBe(1);
|
||||||
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
|
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('la racha manda sobre la tendencia', () => {
|
it('los días sin venir se informan pero no mueven el nivel', () => {
|
||||||
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
|
// The group stopped recording classes: 30 days since the last presence,
|
||||||
// absences and one attended class. The trend alone would give attention;
|
// but the attendee missed nothing.
|
||||||
// the 3 trailing absences give high risk, which is what has to win.
|
const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]]));
|
||||||
|
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||||
|
expect(señales.daysSinceLastAttendance).toBe(30);
|
||||||
|
expect(señales.level).toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tres faltas seguidas son riesgo alto con buena historia detrás', () => {
|
||||||
|
// 16 classes at 81%: the 3 trailing absences are what decides the level.
|
||||||
const alumno = member(dense([
|
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',
|
||||||
@@ -167,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', () => {
|
||||||
@@ -184,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();
|
||||||
|
});
|
||||||
|
});
|
||||||
144
apps/backend/test/db/payment-review.db.test.ts
Normal file
144
apps/backend/test/db/payment-review.db.test.ts
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
/* Teacher review of reported payments against a real Postgres (see
|
||||||
|
student-access.db.test.ts): confirm/reject/undo, the overdue alert and access
|
||||||
|
between teachers. */
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
||||||
|
import { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import type { FileStorage } from '@/lib/storage';
|
||||||
|
import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case';
|
||||||
|
import { ReportedPayments } from '@/modules/payments/features/reported/use-case';
|
||||||
|
import { sendReviewNotification } from '@/modules/payments/lib/review-notifications';
|
||||||
|
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
|
||||||
|
|
||||||
|
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
|
||||||
|
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]);
|
||||||
|
const storage: FileStorage = {
|
||||||
|
put: async () => {},
|
||||||
|
signedUrl: (key, ttl) => `https://storage.test/${key}?ttl=${ttl}`,
|
||||||
|
remove: async () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
describe.skipIf(!url)('payment review (real database)', () => {
|
||||||
|
let db: PrismaClient;
|
||||||
|
let unitOfWork: UnitOfWork;
|
||||||
|
const notified: string[] = [];
|
||||||
|
const ids = {
|
||||||
|
teacher: `r-teacher-${suffix}`,
|
||||||
|
other: `r-other-${suffix}`,
|
||||||
|
group: `r-group-${suffix}`,
|
||||||
|
ana: `r-ana-${suffix}`,
|
||||||
|
account: `r-acc-${suffix}`,
|
||||||
|
fee: `r-fee-${suffix}`,
|
||||||
|
};
|
||||||
|
const NOW = new Date('2026-10-28T15:00:00.000Z');
|
||||||
|
const reviews = (now = NOW) =>
|
||||||
|
new ReportedPayments({ db, unitOfWork, storage, now, notify: (id) => void notified.push(id) });
|
||||||
|
|
||||||
|
const overdueFor = async () => {
|
||||||
|
const overview = await new GetAttentionOverview({ db: db as never, now: NOW }).execute(ids.teacher);
|
||||||
|
if (!overview.ok) throw new Error('overview failed');
|
||||||
|
const member = overview.value.groups.flatMap((group) => group.members).find((item) => item.attendeeId === ids.ana);
|
||||||
|
return { alerts: member?.alerts.map((alert) => alert.tipo) ?? [], overdue: member?.overduePayments.length ?? 0 };
|
||||||
|
};
|
||||||
|
|
||||||
|
const report = async () => {
|
||||||
|
const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.account, {
|
||||||
|
attendeeId: ids.ana,
|
||||||
|
paymentIds: [ids.fee],
|
||||||
|
file: { name: 'captura.png', bytes: PNG },
|
||||||
|
});
|
||||||
|
if (!result.ok) throw new Error(result.error.detail);
|
||||||
|
return result.value.id;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
|
||||||
|
unitOfWork = new UnitOfWork(db);
|
||||||
|
await db.user.createMany({
|
||||||
|
data: [
|
||||||
|
{ id: ids.teacher, name: 'Caro', email: `${ids.teacher}@test.local`, country: 'AR' },
|
||||||
|
{ id: ids.other, name: 'Otro', email: `${ids.other}@test.local`, country: 'AR' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } });
|
||||||
|
await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } });
|
||||||
|
await db.studentAccount.create({
|
||||||
|
data: {
|
||||||
|
id: ids.account,
|
||||||
|
name: 'Ana',
|
||||||
|
createdById: ids.teacher,
|
||||||
|
recoveryEmail: 'ana@test.local',
|
||||||
|
recoveryEmailVerifiedAt: NOW,
|
||||||
|
attendees: { create: { attendeeId: ids.ana } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await db.payment.create({
|
||||||
|
data: { id: ids.fee, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z') },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await db.user.deleteMany({ where: { id: { in: [ids.teacher, ids.other] } } });
|
||||||
|
await db.$disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un pago informado saca la cuota de la alerta y otro profe no lo ve', async () => {
|
||||||
|
expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 });
|
||||||
|
const reportId = await report();
|
||||||
|
expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 });
|
||||||
|
|
||||||
|
const mine = await reviews().list(ids.teacher);
|
||||||
|
if (!mine.ok) throw new Error('list failed');
|
||||||
|
expect(mine.value.data.map((item) => item.id)).toEqual([reportId]);
|
||||||
|
expect(mine.value.data[0]?.receipt.thumbnailUrl).toContain('ttl=300');
|
||||||
|
|
||||||
|
const theirs = await reviews().list(ids.other);
|
||||||
|
expect(theirs).toEqual({ ok: true, value: { data: [] } });
|
||||||
|
const foreign = await reviews().confirm(ids.other, reportId);
|
||||||
|
expect(!foreign.ok && foreign.error.status).toBe(404);
|
||||||
|
const foreignReceipt = await reviews().receiptUrl(ids.other, reportId);
|
||||||
|
expect(foreignReceipt.ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rechazar devuelve la alerta y deshacer la vuelve a sacar', async () => {
|
||||||
|
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
|
||||||
|
const rejected = await reviews().reject(ids.teacher, reportId, 'No se ve el monto');
|
||||||
|
expect(rejected.ok && rejected.value.status).toBe('rejected');
|
||||||
|
expect(notified).toContain(reportId);
|
||||||
|
expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 });
|
||||||
|
|
||||||
|
const again = await reviews().confirm(ids.teacher, reportId);
|
||||||
|
expect(!again.ok && again.error.status).toBe(409);
|
||||||
|
|
||||||
|
const undone = await reviews().undo(ids.teacher, reportId);
|
||||||
|
expect(undone.ok && undone.value.status).toBe('reported');
|
||||||
|
expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('confirmar marca las cuotas como pagadas; deshacer las vuelve a vencidas', async () => {
|
||||||
|
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
|
||||||
|
const confirmed = await reviews().confirm(ids.teacher, reportId);
|
||||||
|
expect(confirmed.ok && confirmed.value.status).toBe('confirmed');
|
||||||
|
expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'PAID', paidAt: NOW });
|
||||||
|
|
||||||
|
// Email only if the review still stands.
|
||||||
|
const sent: string[] = [];
|
||||||
|
const email = { sendStudentPaymentReviewed: async (data: { email: string }) => void sent.push(data.email) };
|
||||||
|
expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(true);
|
||||||
|
expect(sent).toEqual(['ana@test.local']);
|
||||||
|
|
||||||
|
const undone = await reviews().undo(ids.teacher, reportId);
|
||||||
|
expect(undone.ok).toBe(true);
|
||||||
|
expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'OVERDUE', paidAt: null });
|
||||||
|
expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deshacer vence a los pocos minutos', async () => {
|
||||||
|
const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id;
|
||||||
|
expect((await reviews().confirm(ids.teacher, reportId)).ok).toBe(true);
|
||||||
|
const late = await reviews(new Date(NOW.getTime() + 11 * 60 * 1000)).undo(ids.teacher, reportId);
|
||||||
|
expect(!late.ok && late.error.status).toBe(409);
|
||||||
|
});
|
||||||
|
});
|
||||||
149
apps/backend/test/db/student-access.db.test.ts
Normal file
149
apps/backend/test/db/student-access.db.test.ts
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
/* Against a real Postgres: the single-use guarantee lives in the database
|
||||||
|
(conditional UPDATE under concurrency), so a mock can't prove it. Skipped
|
||||||
|
unless DB_TESTS=1 (`bun run test:db`), which uses DATABASE_URL from .env.
|
||||||
|
Creates its own teacher/group/attendee and deletes them at the end. */
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
||||||
|
import { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case';
|
||||||
|
import { InviteStudent } from '@/modules/student-access/features/invite/use-case';
|
||||||
|
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
|
||||||
|
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
|
||||||
|
import { hashToken } from '@/modules/student-portal/lib/tokens';
|
||||||
|
|
||||||
|
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
|
||||||
|
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
|
||||||
|
describe.skipIf(!url)('student access (real database)', () => {
|
||||||
|
let db: PrismaClient;
|
||||||
|
// Same contract as UnitOfWork.executeResult, built on this file's own client
|
||||||
|
// (other test files mock '@/lib/prisma').
|
||||||
|
let unitOfWork: { executeResult: unknown };
|
||||||
|
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` };
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
|
||||||
|
unitOfWork = {
|
||||||
|
executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => {
|
||||||
|
const rollback = Symbol('rollback');
|
||||||
|
try {
|
||||||
|
return await db.$transaction(async (tx) => {
|
||||||
|
const result = await callback(tx);
|
||||||
|
if (!result.ok) throw { [rollback]: result };
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error && typeof error === 'object' && rollback in error) {
|
||||||
|
return (error as Record<symbol, unknown>)[rollback];
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}) as never,
|
||||||
|
};
|
||||||
|
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
|
||||||
|
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
|
||||||
|
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await db.user.deleteMany({ where: { id: ids.user } });
|
||||||
|
await db.$disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
const invite = (now = new Date()) =>
|
||||||
|
new InviteStudent({ db, unitOfWork: unitOfWork as never, now }).execute(ids.group, ids.attendee, ids.user);
|
||||||
|
const tokenOf = (link: string) => link.split('/i/')[1] as string;
|
||||||
|
const consume = (token: string, now = new Date()) =>
|
||||||
|
new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now }).execute({
|
||||||
|
token,
|
||||||
|
ip: '203.0.113.7',
|
||||||
|
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1',
|
||||||
|
});
|
||||||
|
|
||||||
|
it('guarda solo el hash del token', async () => {
|
||||||
|
const result = await invite();
|
||||||
|
if (!result.ok) throw new Error('invite failed');
|
||||||
|
const token = tokenOf(result.value.url);
|
||||||
|
expect(token).toHaveLength(43);
|
||||||
|
expect(await db.studentAccessToken.count({ where: { tokenHash: token } })).toBe(0);
|
||||||
|
expect(await db.studentAccessToken.count({ where: { tokenHash: hashToken(token) } })).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el GET no consume el link', async () => {
|
||||||
|
const result = await invite();
|
||||||
|
if (!result.ok) throw new Error('invite failed');
|
||||||
|
const token = tokenOf(result.value.url);
|
||||||
|
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
const info = await new GetStudentLinkInfo({ db }).execute(token);
|
||||||
|
expect(info).toMatchObject({ ok: true, value: { status: 'valid', name: 'Ana Pérez', teacherName: 'Profe Test', groupName: 'Natación' } });
|
||||||
|
}
|
||||||
|
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
|
||||||
|
expect(row.usedAt).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bajo concurrencia, solo un dispositivo consume el link', async () => {
|
||||||
|
const result = await invite();
|
||||||
|
if (!result.ok) throw new Error('invite failed');
|
||||||
|
const token = tokenOf(result.value.url);
|
||||||
|
|
||||||
|
const attempts = await Promise.all(Array.from({ length: 10 }, () => consume(token)));
|
||||||
|
const winners = attempts.filter((attempt) => attempt.ok);
|
||||||
|
const losers = attempts.filter((attempt) => !attempt.ok);
|
||||||
|
expect(winners).toHaveLength(1);
|
||||||
|
expect(losers).toHaveLength(9);
|
||||||
|
for (const loser of losers) {
|
||||||
|
if (!loser.ok) expect(loser.error.status).toBe(410);
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||||
|
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
|
||||||
|
expect(sessions).toHaveLength(1);
|
||||||
|
expect(sessions[0]?.device).toBe('iPhone · Safari');
|
||||||
|
|
||||||
|
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
|
||||||
|
expect(row.usedIp).toBe('203.0.113.7');
|
||||||
|
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un link vencido no sirve', async () => {
|
||||||
|
const past = new Date(Date.now() - 73 * 60 * 60 * 1000);
|
||||||
|
const result = await invite(past);
|
||||||
|
if (!result.ok) throw new Error('invite failed');
|
||||||
|
const token = tokenOf(result.value.url);
|
||||||
|
|
||||||
|
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
|
||||||
|
const attempt = await consume(token);
|
||||||
|
expect(attempt.ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reinvitar revoca las sesiones y los links anteriores', async () => {
|
||||||
|
const first = await invite();
|
||||||
|
if (!first.ok) throw new Error('invite failed');
|
||||||
|
const consumed = await consume(tokenOf(first.value.url));
|
||||||
|
expect(consumed.ok).toBe(true);
|
||||||
|
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||||
|
await db.studentPasskey.create({
|
||||||
|
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
|
||||||
|
});
|
||||||
|
const pendingOld = await invite();
|
||||||
|
// A lost phone must not keep a way in: passkeys go too.
|
||||||
|
expect(await db.studentPasskey.count({ where: { accountId: linked.accountId } })).toBe(0);
|
||||||
|
if (!pendingOld.ok) throw new Error('invite failed');
|
||||||
|
|
||||||
|
const access = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
|
||||||
|
expect(access).toMatchObject({ ok: true, value: { status: 'invited', devices: [] } });
|
||||||
|
|
||||||
|
// Both previous links are dead: the consumed one and the pending one.
|
||||||
|
expect((await consume(tokenOf(first.value.url))).ok).toBe(false);
|
||||||
|
const reinvite = await invite();
|
||||||
|
if (!reinvite.ok) throw new Error('invite failed');
|
||||||
|
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
|
||||||
|
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
|
||||||
|
|
||||||
|
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||||
|
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
|
||||||
|
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
|
||||||
|
expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
|
||||||
|
});
|
||||||
|
});
|
||||||
176
apps/backend/test/db/student-portal.db.test.ts
Normal file
176
apps/backend/test/db/student-portal.db.test.ts
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
/* Student endpoints against a real Postgres (see student-access.db.test.ts):
|
||||||
|
absence notices, payment reports and authorization by linked attendee. */
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
||||||
|
import { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { UnitOfWork } from '@/lib/prisma';
|
||||||
|
import type { FileStorage } from '@/lib/storage';
|
||||||
|
import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case';
|
||||||
|
import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case';
|
||||||
|
import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case';
|
||||||
|
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
|
||||||
|
|
||||||
|
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
|
||||||
|
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]);
|
||||||
|
|
||||||
|
function memoryStorage() {
|
||||||
|
const objects = new Map<string, Uint8Array>();
|
||||||
|
const storage: FileStorage = {
|
||||||
|
put: async (key, body) => void objects.set(key, body),
|
||||||
|
signedUrl: (key) => `https://storage.test/${key}?sig=1`,
|
||||||
|
remove: async (key) => void objects.delete(key),
|
||||||
|
};
|
||||||
|
return { objects, storage };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe.skipIf(!url)('student portal (real database)', () => {
|
||||||
|
let db: PrismaClient;
|
||||||
|
let unitOfWork: UnitOfWork;
|
||||||
|
const ids = {
|
||||||
|
user: `t-user-${suffix}`,
|
||||||
|
group: `t-group-${suffix}`,
|
||||||
|
ana: `t-ana-${suffix}`,
|
||||||
|
beto: `t-beto-${suffix}`,
|
||||||
|
accountAna: `t-acc-ana-${suffix}`,
|
||||||
|
accountBeto: `t-acc-beto-${suffix}`,
|
||||||
|
};
|
||||||
|
// Wednesday 2026-10-28 12:00 in Buenos Aires: the group meets Mon/Wed/Fri at 18:00.
|
||||||
|
const NOW = new Date('2026-10-28T15:00:00.000Z');
|
||||||
|
const WED_18 = '2026-10-28T21:00:00.000Z';
|
||||||
|
const FRI_18 = '2026-10-30T21:00:00.000Z';
|
||||||
|
const MON_18 = '2026-10-26T21:00:00.000Z';
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
|
||||||
|
unitOfWork = new UnitOfWork(db);
|
||||||
|
await db.user.create({
|
||||||
|
data: { id: ids.user, name: 'Caro', email: `${ids.user}@test.local`, country: 'AR', transferAlias: 'caro.natacion', transferHolder: 'Carolina Gómez' },
|
||||||
|
});
|
||||||
|
await db.group.create({
|
||||||
|
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
|
||||||
|
});
|
||||||
|
await db.attendee.createMany({
|
||||||
|
data: [
|
||||||
|
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
|
||||||
|
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await db.studentAccount.create({
|
||||||
|
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
|
||||||
|
});
|
||||||
|
await db.studentAccount.create({
|
||||||
|
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
|
||||||
|
});
|
||||||
|
await db.payment.createMany({
|
||||||
|
data: [
|
||||||
|
{ id: `t-p1-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z'), description: 'Septiembre' },
|
||||||
|
{ id: `t-p2-${suffix}`, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z'), description: 'Noviembre' },
|
||||||
|
{ id: `t-p3-${suffix}`, groupId: ids.group, attendeeId: ids.beto, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'PENDING', dueDate: new Date('2026-11-10T12:00:00Z') },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await db.user.deleteMany({ where: { id: ids.user } });
|
||||||
|
await db.$disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lista las clases de la semana en la hora del profe', async () => {
|
||||||
|
const result = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana);
|
||||||
|
if (!result.ok) throw new Error('classes failed');
|
||||||
|
expect(result.value.timeZone).toBe('America/Argentina/Buenos_Aires');
|
||||||
|
const starts = result.value.classes.map((item) => item.startsAt);
|
||||||
|
expect(starts.slice(0, 3)).toEqual([new Date(MON_18).toISOString(), new Date(WED_18).toISOString(), new Date(FRI_18).toISOString()]);
|
||||||
|
expect(result.value.classes[0]?.started).toBe(true);
|
||||||
|
expect(result.value.classes[1]?.started).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('avisar falta la justifica y deshacer la revierte', async () => {
|
||||||
|
const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW, releaseHours: 12 });
|
||||||
|
const result = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18, FRI_18], reason: 'health', message: 'Fiebre' });
|
||||||
|
if (!result.ok) throw new Error(result.error.detail);
|
||||||
|
expect(result.value.notified).toHaveLength(2);
|
||||||
|
|
||||||
|
// Idempotent: notifying again creates nothing.
|
||||||
|
const again = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [WED_18] });
|
||||||
|
expect(again).toEqual({ ok: true, value: { notified: [] } });
|
||||||
|
|
||||||
|
const attendances = await db.attendance.findMany({ where: { attendeeId: ids.ana } });
|
||||||
|
expect(attendances.map((row) => row.status)).toEqual(['EXCUSED', 'EXCUSED']);
|
||||||
|
|
||||||
|
const classes = await new GetStudentClasses({ db, now: NOW }).execute(ids.accountAna, ids.ana);
|
||||||
|
if (!classes.ok) throw new Error('classes failed');
|
||||||
|
const wednesday = classes.value.classes.find((item) => item.startsAt === new Date(WED_18).toISOString());
|
||||||
|
expect(wednesday?.notice).toMatchObject({ reason: 'health', message: 'Fiebre' });
|
||||||
|
|
||||||
|
const noticeId = result.value.notified[1]?.id as string;
|
||||||
|
expect((await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountAna, noticeId)).ok).toBe(true);
|
||||||
|
expect(await db.attendance.count({ where: { attendeeId: ids.ana } })).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('no se puede avisar una clase que ya empezó ni una que no existe', async () => {
|
||||||
|
const notify = new NotifyStudentAbsences({ db, unitOfWork, now: NOW });
|
||||||
|
const started = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: [MON_18] });
|
||||||
|
expect(!started.ok && started.error.status).toBe(409);
|
||||||
|
const invented = await notify.execute(ids.accountAna, { attendeeId: ids.ana, startsAt: ['2026-10-29T21:00:00.000Z'] });
|
||||||
|
expect(!invented.ok && invented.error.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => {
|
||||||
|
expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
|
||||||
|
expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
|
||||||
|
const notify = await new NotifyStudentAbsences({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, { attendeeId: ids.ana, startsAt: [FRI_18] });
|
||||||
|
expect(!notify.ok && notify.error.status).toBe(404);
|
||||||
|
|
||||||
|
const anaNotice = await db.absenceNotice.findFirstOrThrow({ where: { attendeeId: ids.ana, cancelledAt: null } });
|
||||||
|
const cancel = await new CancelStudentAbsence({ db, unitOfWork, now: NOW }).execute(ids.accountBeto, anaNotice.id);
|
||||||
|
expect(!cancel.ok && cancel.error.status).toBe(404);
|
||||||
|
|
||||||
|
const { storage } = memoryStorage();
|
||||||
|
// Beto's account reporting Ana's fee, and Beto reporting Ana's fee id under his own attendee.
|
||||||
|
const asAna = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, {
|
||||||
|
attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG },
|
||||||
|
});
|
||||||
|
expect(!asAna.ok && asAna.error.status).toBe(404);
|
||||||
|
const crossFee = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, {
|
||||||
|
attendeeId: ids.beto, paymentIds: [`t-p1-${suffix}`], file: { name: 'a.png', bytes: PNG },
|
||||||
|
});
|
||||||
|
expect(!crossFee.ok && crossFee.error.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('informar pago guarda el comprobante privado y marca las cuotas como informadas', async () => {
|
||||||
|
const { objects, storage } = memoryStorage();
|
||||||
|
const report = new ReportStudentPayment({ db, unitOfWork, storage, now: NOW });
|
||||||
|
const result = await report.execute(ids.accountAna, {
|
||||||
|
attendeeId: ids.ana, paymentIds: [`t-p1-${suffix}`, `t-p2-${suffix}`], file: { name: 'captura.png', bytes: PNG },
|
||||||
|
});
|
||||||
|
if (!result.ok) throw new Error(result.error.detail);
|
||||||
|
expect(objects.size).toBe(1);
|
||||||
|
const row = await db.reportedPayment.findUniqueOrThrow({ where: { id: result.value.id } });
|
||||||
|
expect(row).toMatchObject({ status: 'REPORTED', receiptMime: 'image/png', currency: 'ARS' });
|
||||||
|
expect(row.totalAmount.toNumber()).toBe(30000);
|
||||||
|
expect([...objects.keys()][0]).toBe(row.receiptKey as string);
|
||||||
|
|
||||||
|
const fees = await new GetStudentFees({ db, now: NOW }).execute(ids.accountAna, ids.ana);
|
||||||
|
if (!fees.ok) throw new Error('fees failed');
|
||||||
|
expect(fees.value.fees.map((fee) => fee.status)).toEqual(['reported', 'reported']);
|
||||||
|
expect(fees.value.transfer).toEqual({ alias: 'caro.natacion', holder: 'Carolina Gómez' });
|
||||||
|
|
||||||
|
// The same fee can't be in two unreviewed reports; the orphan file is removed.
|
||||||
|
const twice = await report.execute(ids.accountAna, {
|
||||||
|
attendeeId: ids.ana, paymentIds: [`t-p2-${suffix}`], file: { name: 'otra.png', bytes: PNG },
|
||||||
|
});
|
||||||
|
expect(!twice.ok && twice.error.status).toBe(409);
|
||||||
|
expect(objects.size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('valida el tipo real del archivo, no el nombre', async () => {
|
||||||
|
const { storage } = memoryStorage();
|
||||||
|
const fake = new TextEncoder().encode('<html><script>alert(1)</script></html>');
|
||||||
|
const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.accountBeto, {
|
||||||
|
attendeeId: ids.beto, paymentIds: [`t-p3-${suffix}`], file: { name: 'comprobante.png', bytes: fake },
|
||||||
|
});
|
||||||
|
expect(!result.ok && result.error.status).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -36,7 +36,7 @@ const groupA = {
|
|||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
capacity: 8,
|
capacity: 8,
|
||||||
_count: { attendees: 3 },
|
_count: { attendees: 3, preRegistrations: 2 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const groupB = {
|
const groupB = {
|
||||||
@@ -48,7 +48,7 @@ const groupB = {
|
|||||||
billingType: null,
|
billingType: null,
|
||||||
dueDay: null,
|
dueDay: null,
|
||||||
capacity: null,
|
capacity: null,
|
||||||
_count: { attendees: 2 },
|
_count: { attendees: 2, preRegistrations: 0 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const madeUpAmount = (value: string) => ({ toString: () => value });
|
const madeUpAmount = (value: string) => ({ toString: () => value });
|
||||||
@@ -113,6 +113,8 @@ describe('GetHomeSummary', () => {
|
|||||||
attendeeName: 'Ana García',
|
attendeeName: 'Ana García',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
// Only the groups with something waiting: Cuadrilla B has none.
|
||||||
|
pendingPreRegistrations: [{ groupId: 'g1', groupName: 'Cuadrilla A', count: 2 }],
|
||||||
});
|
});
|
||||||
|
|
||||||
const where = {
|
const where = {
|
||||||
@@ -160,7 +162,7 @@ describe('GetHomeSummary', () => {
|
|||||||
billingType: null,
|
billingType: null,
|
||||||
dueDay: null,
|
dueDay: null,
|
||||||
capacity: null,
|
capacity: null,
|
||||||
_count: { attendees: 0 },
|
_count: { attendees: 0, preRegistrations: 0 },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -212,7 +214,7 @@ describe('GetHomeSummary', () => {
|
|||||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 10:23 in Buenos Aires, but the default zone is CDMX → 07:23 CDMX (not started yet).
|
// 10:23 in Buenos Aires, the default zone: the 10:00 class already started.
|
||||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||||
const result = await useCase.execute(userId);
|
const result = await useCase.execute(userId);
|
||||||
|
|
||||||
@@ -220,8 +222,8 @@ describe('GetHomeSummary', () => {
|
|||||||
if (!result.ok) return;
|
if (!result.ok) return;
|
||||||
|
|
||||||
expect(result.value.nextClass).toMatchObject({
|
expect(result.value.nextClass).toMatchObject({
|
||||||
occurrenceAt: '2026-09-23T16:00:00.000Z',
|
occurrenceAt: '2026-09-23T13:00:00.000Z',
|
||||||
isNow: false,
|
isNow: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -238,6 +240,7 @@ describe('GetHomeSummary', () => {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
expect(prisma.payment.aggregate).not.toHaveBeenCalled();
|
expect(prisma.payment.aggregate).not.toHaveBeenCalled();
|
||||||
expect(prisma.payment.findMany).not.toHaveBeenCalled();
|
expect(prisma.payment.findMany).not.toHaveBeenCalled();
|
||||||
@@ -259,6 +262,7 @@ describe('home routes', () => {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
394
apps/backend/test/student-portal-auth.test.ts
Normal file
394
apps/backend/test/student-portal-auth.test.ts
Normal file
@@ -0,0 +1,394 @@
|
|||||||
|
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { isPublicApiRequest } from '@/http/session-auth';
|
||||||
|
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
|
||||||
|
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
|
||||||
|
import { StudentPasskeys } from '@/modules/student-portal/features/passkeys/use-case';
|
||||||
|
import {
|
||||||
|
RECOVERY_LIMIT_PER_EMAIL,
|
||||||
|
RECOVERY_LIMIT_PER_IP,
|
||||||
|
RequestRecoveryLink,
|
||||||
|
} from '@/modules/student-portal/features/request-recovery/use-case';
|
||||||
|
import { describeDevice } from '@/modules/student-portal/lib/device';
|
||||||
|
import { hashToken } from '@/modules/student-portal/lib/tokens';
|
||||||
|
import { requireStudentSession, studentOriginGuard } from '@/modules/student-portal/middleware';
|
||||||
|
|
||||||
|
const NOW = new Date('2026-10-27T15:00:00.000Z');
|
||||||
|
const WEB = process.env.WEB_URL ?? 'http://localhost:6173';
|
||||||
|
|
||||||
|
/* In-memory rate limit table: enough to count hits by key and window. */
|
||||||
|
function fakeRateLimit() {
|
||||||
|
let rows: { key: string; createdAt: Date }[] = [];
|
||||||
|
return {
|
||||||
|
deleteMany: mock(async ({ where }: { where: { key: string; createdAt: { lt: Date } } }) => {
|
||||||
|
rows = rows.filter((row) => !(row.key === where.key && row.createdAt < where.createdAt.lt));
|
||||||
|
return { count: 0 };
|
||||||
|
}),
|
||||||
|
count: mock(async ({ where }: { where: { key: string; createdAt: { gte: Date } } }) =>
|
||||||
|
rows.filter((row) => row.key === where.key && row.createdAt >= where.createdAt.gte).length),
|
||||||
|
create: mock(async ({ data }: { data: { key: string; createdAt: Date } }) => {
|
||||||
|
rows.push(data);
|
||||||
|
return data;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('link del alumno', () => {
|
||||||
|
it('un token mal formado es inválido sin tocar la base', async () => {
|
||||||
|
const db = { studentAccessToken: { findUnique: mock() } };
|
||||||
|
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute('abc');
|
||||||
|
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
|
||||||
|
expect(db.studentAccessToken.findUnique).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('usado, revocado o vencido responde lo mismo, sin datos del dueño', async () => {
|
||||||
|
const token = 'a'.repeat(43);
|
||||||
|
const base = {
|
||||||
|
kind: 'INVITATION',
|
||||||
|
usedAt: null,
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: new Date(NOW.getTime() + 1000),
|
||||||
|
account: { name: 'Ana', attendees: [] },
|
||||||
|
};
|
||||||
|
for (const row of [
|
||||||
|
{ ...base, usedAt: NOW },
|
||||||
|
{ ...base, revokedAt: NOW },
|
||||||
|
{ ...base, expiresAt: NOW },
|
||||||
|
{ ...base, kind: 'EMAIL_CONFIRMATION' },
|
||||||
|
null,
|
||||||
|
]) {
|
||||||
|
const db = { studentAccessToken: { findUnique: mock(async () => row) } };
|
||||||
|
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
|
||||||
|
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el GET solo lee: busca por hash y nunca actualiza', async () => {
|
||||||
|
const token = 'b'.repeat(43);
|
||||||
|
const db = {
|
||||||
|
studentAccessToken: {
|
||||||
|
findUnique: mock(async () => ({
|
||||||
|
kind: 'INVITATION',
|
||||||
|
usedAt: null,
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: new Date(NOW.getTime() + 1000),
|
||||||
|
account: {
|
||||||
|
name: 'Ana',
|
||||||
|
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
updateMany: mock(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
|
||||||
|
expect(result).toEqual({
|
||||||
|
ok: true,
|
||||||
|
value: { status: 'valid', kind: 'invitation', name: 'Ana', teacherName: 'Caro', groupName: 'Natación' },
|
||||||
|
});
|
||||||
|
expect(db.studentAccessToken.findUnique.mock.calls[0]?.[0]).toMatchObject({ where: { tokenHash: hashToken(token) } });
|
||||||
|
expect(db.studentAccessToken.updateMany).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el POST consume con un update condicional y reemplaza la sesión del dispositivo', async () => {
|
||||||
|
const tx = {
|
||||||
|
studentAccessToken: {
|
||||||
|
updateMany: mock(async () => ({ count: 1 })),
|
||||||
|
findUniqueOrThrow: mock(async () => ({ accountId: 'acc-1', account: { welcomedAt: null } })),
|
||||||
|
},
|
||||||
|
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 1 })) },
|
||||||
|
};
|
||||||
|
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
|
||||||
|
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
|
||||||
|
token: 'tok',
|
||||||
|
ip: '1.2.3.4',
|
||||||
|
userAgent: 'UA',
|
||||||
|
currentSessionToken: 'old-session',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.ok && result.value.firstLogin).toBe(true);
|
||||||
|
expect(tx.studentAccessToken.updateMany.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
where: { tokenHash: hashToken('tok'), usedAt: null, revokedAt: null, expiresAt: { gt: NOW } },
|
||||||
|
});
|
||||||
|
expect(tx.studentSession.updateMany.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
where: { tokenHash: hashToken('old-session') },
|
||||||
|
});
|
||||||
|
// A new identifier: the stored hash is not the old session's.
|
||||||
|
const created = (tx.studentSession.create.mock.calls[0] as unknown as [{ data: { tokenHash: string } }])[0];
|
||||||
|
expect(created.data.tokenHash).not.toBe(hashToken('old-session'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('si otro dispositivo ganó, responde 410 y no crea sesión', async () => {
|
||||||
|
const tx = {
|
||||||
|
studentAccessToken: { updateMany: mock(async () => ({ count: 0 })), findUniqueOrThrow: mock() },
|
||||||
|
studentSession: { create: mock() },
|
||||||
|
};
|
||||||
|
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
|
||||||
|
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
|
||||||
|
token: 'tok',
|
||||||
|
ip: null,
|
||||||
|
userAgent: null,
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
if (!result.ok) expect(result.error.status).toBe(410);
|
||||||
|
expect(tx.studentSession.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pedir un link al mail', () => {
|
||||||
|
function setup(accounts: { id: string; name: string }[]) {
|
||||||
|
const db = {
|
||||||
|
rateLimitEvent: fakeRateLimit(),
|
||||||
|
studentAccount: { findMany: mock(async () => accounts) },
|
||||||
|
studentAccessToken: { create: mock(async () => ({})) },
|
||||||
|
};
|
||||||
|
const email = { sendStudentRecoveryLinks: mock(async () => {}) };
|
||||||
|
const tasks: Promise<void>[] = [];
|
||||||
|
const useCase = new RequestRecoveryLink({
|
||||||
|
db: db as never,
|
||||||
|
email,
|
||||||
|
now: NOW,
|
||||||
|
defer: (task) => tasks.push(task()),
|
||||||
|
});
|
||||||
|
return { db, email, useCase, flush: () => Promise.all(tasks) };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('responde idéntico exista o no el mail', async () => {
|
||||||
|
const known = setup([{ id: 'acc-1', name: 'Ana' }]);
|
||||||
|
const unknown = setup([]);
|
||||||
|
const a = await known.useCase.execute({ email: 'ana@mail.com', ip: '1.1.1.1' });
|
||||||
|
const b = await unknown.useCase.execute({ email: 'nadie@mail.com', ip: '1.1.1.1' });
|
||||||
|
expect(a).toEqual(b);
|
||||||
|
await Promise.all([known.flush(), unknown.flush()]);
|
||||||
|
expect(known.email.sendStudentRecoveryLinks).toHaveBeenCalledTimes(1);
|
||||||
|
expect(unknown.email.sendStudentRecoveryLinks).not.toHaveBeenCalled();
|
||||||
|
// Only verified emails recover.
|
||||||
|
expect(known.db.studentAccount.findMany.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
where: { recoveryEmail: 'ana@mail.com', recoveryEmailVerifiedAt: { not: null } },
|
||||||
|
});
|
||||||
|
const sent = (known.email.sendStudentRecoveryLinks.mock.calls[0] as unknown as [{ links: { url: string }[] }])[0];
|
||||||
|
expect(sent.links[0]?.url).toStartWith(`${WEB}/i/`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`limita a ${RECOVERY_LIMIT_PER_EMAIL} pedidos por mail, exista o no`, async () => {
|
||||||
|
for (const accounts of [[{ id: 'acc-1', name: 'Ana' }], []]) {
|
||||||
|
const { useCase } = setup(accounts);
|
||||||
|
for (let i = 0; i < RECOVERY_LIMIT_PER_EMAIL; i++) {
|
||||||
|
expect((await useCase.execute({ email: 'x@mail.com', ip: `10.0.0.${i}` })).ok).toBe(true);
|
||||||
|
}
|
||||||
|
const blocked = await useCase.execute({ email: 'x@mail.com', ip: '10.0.0.99' });
|
||||||
|
expect(blocked.ok).toBe(false);
|
||||||
|
if (!blocked.ok) expect(blocked.error.status).toBe(429);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`limita a ${RECOVERY_LIMIT_PER_IP} pedidos por IP`, async () => {
|
||||||
|
const { useCase } = setup([]);
|
||||||
|
for (let i = 0; i < RECOVERY_LIMIT_PER_IP; i++) {
|
||||||
|
expect((await useCase.execute({ email: `u${i}@mail.com`, ip: '9.9.9.9' })).ok).toBe(true);
|
||||||
|
}
|
||||||
|
expect((await useCase.execute({ email: 'otro@mail.com', ip: '9.9.9.9' })).ok).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('passkeys', () => {
|
||||||
|
function setup() {
|
||||||
|
const challenges = new Map<string, Record<string, unknown>>();
|
||||||
|
let nextId = 0;
|
||||||
|
const db = {
|
||||||
|
rateLimitEvent: fakeRateLimit(),
|
||||||
|
studentAccount: {
|
||||||
|
findUniqueOrThrow: mock(async () => ({ name: 'Ana', passkeys: [] })),
|
||||||
|
},
|
||||||
|
studentWebauthnChallenge: {
|
||||||
|
deleteMany: mock(async ({ where }: { where: { id?: string } }) => {
|
||||||
|
if (!where.id) return { count: 0 };
|
||||||
|
return { count: challenges.delete(where.id) ? 1 : 0 };
|
||||||
|
}),
|
||||||
|
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
|
||||||
|
const id = `ch-${nextId++}`;
|
||||||
|
challenges.set(id, { id, ...data });
|
||||||
|
return { id };
|
||||||
|
}),
|
||||||
|
findUnique: mock(async ({ where }: { where: { id: string } }) => challenges.get(where.id) ?? null),
|
||||||
|
},
|
||||||
|
studentPasskey: {
|
||||||
|
upsert: mock(async () => ({})),
|
||||||
|
findUnique: mock(async () => ({
|
||||||
|
id: 'pk-1',
|
||||||
|
accountId: 'acc-1',
|
||||||
|
credentialId: 'cred-1',
|
||||||
|
publicKey: new Uint8Array([1, 2, 3]),
|
||||||
|
counter: 4,
|
||||||
|
transports: ['internal'],
|
||||||
|
})),
|
||||||
|
update: mock(async () => ({})),
|
||||||
|
deleteMany: mock(async () => ({ count: 1 })),
|
||||||
|
},
|
||||||
|
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 0 })) },
|
||||||
|
};
|
||||||
|
const webauthn = {
|
||||||
|
generateRegistrationOptions: mock(async () => ({ challenge: 'reg-challenge' })),
|
||||||
|
verifyRegistrationResponse: mock(async () => ({
|
||||||
|
verified: true,
|
||||||
|
registrationInfo: { credential: { id: 'cred-1', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'] } },
|
||||||
|
})),
|
||||||
|
generateAuthenticationOptions: mock(async () => ({ challenge: 'login-challenge' })),
|
||||||
|
verifyAuthenticationResponse: mock(async () => ({ verified: true, authenticationInfo: { newCounter: 5 } })),
|
||||||
|
};
|
||||||
|
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(db) };
|
||||||
|
const passkeys = new StudentPasskeys({
|
||||||
|
db: db as never,
|
||||||
|
webauthn: webauthn as never,
|
||||||
|
unitOfWork: unitOfWork as never,
|
||||||
|
now: NOW,
|
||||||
|
});
|
||||||
|
return { db, webauthn, passkeys };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('registra una passkey con preferred en residentKey y userVerification', async () => {
|
||||||
|
const { db, webauthn, passkeys } = setup();
|
||||||
|
const options = await passkeys.registrationOptions('acc-1');
|
||||||
|
if (!options.ok) throw new Error('options failed');
|
||||||
|
expect(webauthn.generateRegistrationOptions.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const iPhone = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1';
|
||||||
|
const result = await passkeys.verifyRegistration('acc-1', { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, iPhone);
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
expect(webauthn.verifyRegistrationResponse.mock.calls[0]?.[0]).toMatchObject({ expectedChallenge: 'reg-challenge' });
|
||||||
|
expect(db.studentPasskey.upsert.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
create: { accountId: 'acc-1', credentialId: 'cred-1', device: 'iPhone · Safari' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el challenge sirve una sola vez y solo para su cuenta', async () => {
|
||||||
|
const { passkeys } = setup();
|
||||||
|
const options = await passkeys.registrationOptions('acc-1');
|
||||||
|
if (!options.ok) throw new Error('options failed');
|
||||||
|
const input = { challengeId: options.value.challengeId, response: { id: 'cred-1' } };
|
||||||
|
|
||||||
|
expect((await passkeys.verifyRegistration('acc-2', input, null)).ok).toBe(false);
|
||||||
|
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(true);
|
||||||
|
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el login con passkey crea una sesión nueva y actualiza el contador', async () => {
|
||||||
|
const { db, passkeys } = setup();
|
||||||
|
const options = await passkeys.loginOptions('1.1.1.1');
|
||||||
|
if (!options.ok) throw new Error('options failed');
|
||||||
|
const result = await passkeys.verifyLogin(
|
||||||
|
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
|
||||||
|
{ userAgent: null },
|
||||||
|
);
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
expect(db.studentPasskey.update.mock.calls[0]?.[0]).toMatchObject({ data: { counter: 5 } });
|
||||||
|
expect(db.studentSession.create.mock.calls[0]?.[0]).toMatchObject({ data: { accountId: 'acc-1' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un challenge de registro no sirve para login', async () => {
|
||||||
|
const { passkeys } = setup();
|
||||||
|
const options = await passkeys.registrationOptions('acc-1');
|
||||||
|
if (!options.ok) throw new Error('options failed');
|
||||||
|
const result = await passkeys.verifyLogin(
|
||||||
|
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
|
||||||
|
{ userAgent: null },
|
||||||
|
);
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('una firma inválida no inicia sesión', async () => {
|
||||||
|
const { db, webauthn, passkeys } = setup();
|
||||||
|
webauthn.verifyAuthenticationResponse.mockImplementationOnce(async () => {
|
||||||
|
throw new Error('bad signature');
|
||||||
|
});
|
||||||
|
const options = await passkeys.loginOptions('1.1.1.1');
|
||||||
|
if (!options.ok) throw new Error('options failed');
|
||||||
|
const result = await passkeys.verifyLogin(
|
||||||
|
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
|
||||||
|
{ userAgent: null },
|
||||||
|
);
|
||||||
|
expect(result.ok).toBe(false);
|
||||||
|
expect(db.studentSession.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('separación de roles y CSRF', () => {
|
||||||
|
const session = (overrides: Record<string, unknown> = {}) => ({
|
||||||
|
id: 'ses-1',
|
||||||
|
accountId: 'acc-1',
|
||||||
|
revokedAt: null,
|
||||||
|
expiresAt: new Date(NOW.getTime() + 1000 * 60 * 60 * 24),
|
||||||
|
lastUsedAt: NOW,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
let db: { studentSession: { findUnique: ReturnType<typeof mock>; update: ReturnType<typeof mock> } };
|
||||||
|
|
||||||
|
function app() {
|
||||||
|
const hono = new Hono();
|
||||||
|
hono.use('*', studentOriginGuard);
|
||||||
|
hono.get('/me', requireStudentSession({ db: db as never, now: () => NOW }), (c) => c.json(c.get('student')));
|
||||||
|
hono.post('/action', (c) => c.json({ ok: true }));
|
||||||
|
return hono;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
db = { studentSession: { findUnique: mock(async () => session()), update: mock(async () => ({})) } };
|
||||||
|
});
|
||||||
|
|
||||||
|
it('las rutas del alumno quedan fuera del middleware del profe, y las del profe no', () => {
|
||||||
|
expect(isPublicApiRequest('GET', '/api/v1/student-portal/me')).toBe(true);
|
||||||
|
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
|
||||||
|
expect(isPublicApiRequest('GET', '/api/v1/students/status')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la cookie de sesión del profe no sirve en las rutas del alumno', async () => {
|
||||||
|
const res = await app().request('/me', {
|
||||||
|
headers: { Cookie: 'better-auth.session_token=teacher-token' },
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
expect(db.studentSession.findUnique).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('con la cookie del alumno setea su cuenta', async () => {
|
||||||
|
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ accountId: 'acc-1', sessionId: 'ses-1' });
|
||||||
|
expect(db.studentSession.findUnique.mock.calls[0]?.[0]).toEqual({ where: { tokenHash: hashToken('student-token') } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('una sesión revocada o vencida no entra', async () => {
|
||||||
|
for (const row of [session({ revokedAt: NOW }), session({ expiresAt: NOW })]) {
|
||||||
|
db.studentSession.findUnique.mockImplementationOnce(async () => row);
|
||||||
|
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la sesión se desliza: con más de una hora sin uso se renueva por 90 días', async () => {
|
||||||
|
db.studentSession.findUnique.mockImplementationOnce(async () =>
|
||||||
|
session({ lastUsedAt: new Date(NOW.getTime() - 2 * 60 * 60 * 1000) }));
|
||||||
|
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(db.studentSession.update.mock.calls[0]?.[0]).toMatchObject({
|
||||||
|
data: { lastUsedAt: NOW, expiresAt: new Date(NOW.getTime() + 90 * 24 * 60 * 60 * 1000) },
|
||||||
|
});
|
||||||
|
expect(res.headers.get('Set-Cookie')).toContain('HttpOnly');
|
||||||
|
expect(res.headers.get('Set-Cookie')).toContain('SameSite=Lax');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un POST sin Origin o de otro origen se rechaza', async () => {
|
||||||
|
expect((await app().request('/action', { method: 'POST' })).status).toBe(403);
|
||||||
|
expect((await app().request('/action', { method: 'POST', headers: { Origin: 'https://evil.test' } })).status).toBe(403);
|
||||||
|
expect((await app().request('/action', { method: 'POST', headers: { Origin: WEB } })).status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('dispositivo legible', () => {
|
||||||
|
it('describe navegador y plataforma', () => {
|
||||||
|
expect(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/130.0 Mobile/15E148 Safari/604.1')).toBe('iPhone · Chrome');
|
||||||
|
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36')).toBe('Android · Chrome');
|
||||||
|
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/26.0 Chrome/122.0 Mobile Safari/537.36')).toBe('Android · Samsung Internet');
|
||||||
|
expect(describeDevice(null)).toBe('Dispositivo desconocido');
|
||||||
|
});
|
||||||
|
});
|
||||||
67
apps/backend/test/student-portal-files.test.ts
Normal file
67
apps/backend/test/student-portal-files.test.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test';
|
||||||
|
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||||
|
import type { FileStorage } from '@/lib/storage';
|
||||||
|
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||||
|
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
|
||||||
|
|
||||||
|
const pad = (head: number[]) => new Uint8Array([...head, ...new Array(16).fill(0)]);
|
||||||
|
const ascii = (text: string) => [...text].map((char) => char.charCodeAt(0));
|
||||||
|
|
||||||
|
describe('tipo real del comprobante (magic bytes)', () => {
|
||||||
|
it('reconoce JPG, PNG, WEBP, HEIC y PDF', () => {
|
||||||
|
expect(detectReceiptType(pad([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg');
|
||||||
|
expect(detectReceiptType(pad([0x89, ...ascii('PNG'), 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png');
|
||||||
|
expect(detectReceiptType(pad([...ascii('RIFF'), 0, 0, 0, 0, ...ascii('WEBP')]))).toBe('image/webp');
|
||||||
|
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypheic')]))).toBe('image/heic');
|
||||||
|
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypmif1')]))).toBe('image/heic');
|
||||||
|
expect(detectReceiptType(pad(ascii('%PDF-1.7')))).toBe('application/pdf');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rechaza lo demás aunque se llame .png', () => {
|
||||||
|
expect(detectReceiptType(pad(ascii('<svg xmlns=')))).toBeNull();
|
||||||
|
expect(detectReceiptType(pad(ascii('GIF89a')))).toBeNull();
|
||||||
|
expect(detectReceiptType(pad([0x50, 0x4b, 0x03, 0x04]))).toBeNull(); // zip/docx
|
||||||
|
expect(detectReceiptType(pad([0, 0, 0, 0x18, ...ascii('ftypmp42')]))).toBeNull(); // video
|
||||||
|
expect(detectReceiptType(new Uint8Array([0xff, 0xd8]))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('valida tamaño y tipo antes de tocar el storage', async () => {
|
||||||
|
const puts: string[] = [];
|
||||||
|
const storage: FileStorage = { put: async (key) => void puts.push(key), signedUrl: () => '', remove: async () => {} };
|
||||||
|
const attendee = {
|
||||||
|
id: 'a1',
|
||||||
|
groupId: 'g1',
|
||||||
|
group: { createdById: 't1', owner: { country: 'AR' } },
|
||||||
|
};
|
||||||
|
const db = { attendee: { findFirst: async () => attendee }, payment: { findMany: async () => [] } };
|
||||||
|
const useCase = new ReportStudentPayment({ db: db as never, storage });
|
||||||
|
|
||||||
|
const big = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: new Uint8Array(RECEIPT_MAX_BYTES + 1) } });
|
||||||
|
expect(!big.ok && big.error.errors).toEqual({ file: ['too_large'] });
|
||||||
|
const html = await useCase.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.png', bytes: pad(ascii('<html>')) } });
|
||||||
|
expect(!html.ok && html.error.errors).toEqual({ file: ['invalid_type'] });
|
||||||
|
expect(puts).toEqual([]);
|
||||||
|
|
||||||
|
const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
|
||||||
|
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
|
||||||
|
expect(!unavailable.ok && unavailable.error.status).toBe(503);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('clases de un rango en la hora del profe', () => {
|
||||||
|
const TZ = 'America/Argentina/Buenos_Aires';
|
||||||
|
|
||||||
|
it('lista lunes y miércoles a las 18 de una semana', () => {
|
||||||
|
const from = startOfWeekInTimeZone(new Date('2026-10-28T15:00:00Z'), TZ);
|
||||||
|
expect(from.toISOString()).toBe('2026-10-26T03:00:00.000Z');
|
||||||
|
const to = new Date(from.getTime() + 7 * 24 * 60 * 60 * 1000);
|
||||||
|
const starts = occurrencesBetween({ days: ['MONDAY', 'WEDNESDAY'], time: '18:00', from, to, timeZone: TZ });
|
||||||
|
expect(starts.map((date) => date.toISOString())).toEqual(['2026-10-26T21:00:00.000Z', '2026-10-28T21:00:00.000Z']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sin horario no hay clases', () => {
|
||||||
|
const now = new Date();
|
||||||
|
expect(occurrencesBetween({ days: ['MONDAY'], time: null, from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]);
|
||||||
|
expect(occurrencesBetween({ days: [], time: '18:00', from: now, to: new Date(now.getTime() + 1e9), timeZone: TZ })).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -273,20 +273,26 @@ describe('payment reminders', () => {
|
|||||||
describe('re-engagement messages', () => {
|
describe('re-engagement messages', () => {
|
||||||
function atRiskGroup() {
|
function atRiskGroup() {
|
||||||
// Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
|
// Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
|
||||||
db.classSession.findMany.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
|
const s1 = new Date('2026-10-16T10:00:00Z');
|
||||||
|
const s2 = new Date('2026-10-14T10:00:00Z');
|
||||||
|
const enrolled = new Date('2026-09-01T10:00:00Z');
|
||||||
|
db.classSession.findMany.mockResolvedValue([
|
||||||
|
{ id: 's1', startsAt: s1 },
|
||||||
|
{ id: 's2', startsAt: s2 },
|
||||||
|
]);
|
||||||
db.attendee.findMany
|
db.attendee.findMany
|
||||||
.mockResolvedValueOnce([
|
.mockResolvedValueOnce([
|
||||||
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789' },
|
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled },
|
||||||
{ id: 'att-2', fullName: 'Beto', phone: '1198765432' },
|
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled },
|
||||||
])
|
])
|
||||||
.mockResolvedValueOnce([
|
.mockResolvedValueOnce([
|
||||||
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
|
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
|
||||||
]);
|
]);
|
||||||
db.attendance.findMany.mockResolvedValue([
|
db.attendance.findMany.mockResolvedValue([
|
||||||
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
|
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },
|
||||||
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
|
{ attendeeId: 'att-1', classSessionId: 's2', status: 'ABSENT', classSession: { startsAt: s2 } },
|
||||||
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
|
{ attendeeId: 'att-2', classSessionId: 's1', status: 'PRESENT', classSession: { startsAt: s1 } },
|
||||||
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
|
{ attendeeId: 'att-2', classSessionId: 's2', status: 'PRESENT', classSession: { startsAt: s2 } },
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
"@fontsource-variable/inter": "^5.3.0",
|
"@fontsource-variable/inter": "^5.3.0",
|
||||||
"@gruperly/shared": "workspace:*",
|
"@gruperly/shared": "workspace:*",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
|
"@simplewebauthn/browser": "13.3.0",
|
||||||
"@tanstack/react-query": "^5.62.0",
|
"@tanstack/react-query": "^5.62.0",
|
||||||
"@tanstack/react-router": "^1.170.38",
|
"@tanstack/react-router": "^1.170.38",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
|
import { NavBadge } from './NavBadge'
|
||||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function BottomNav() {
|
export function BottomNav() {
|
||||||
@@ -8,7 +9,7 @@ export function BottomNav() {
|
|||||||
return (
|
return (
|
||||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
||||||
<div className="mx-auto grid max-w-md grid-cols-4">
|
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
|
||||||
const isActive = isNavItemActive(location.pathname, to)
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -24,11 +25,12 @@ export function BottomNav() {
|
|||||||
color + background, not only by the text tone. */}
|
color + background, not only by the text tone. */}
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',
|
'relative flex size-8 items-center justify-center rounded-lg transition-colors duration-150',
|
||||||
isActive && 'bg-accent-soft',
|
isActive && 'bg-accent-soft',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
||||||
|
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
|
||||||
</span>
|
</span>
|
||||||
<span className="leading-none">{label}</span>
|
<span className="leading-none">{label}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ export function Header() {
|
|||||||
<Breadcrumb />
|
<Breadcrumb />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<ThemeToggle />
|
{/* On mobile the theme lives only in Ajustes → Apariencia: in the
|
||||||
|
header it took the space next to the avatar for something you
|
||||||
|
change once. On desktop there is room for the shortcut. */}
|
||||||
|
<div className="hidden lg:block">
|
||||||
|
<ThemeToggle />
|
||||||
|
</div>
|
||||||
<UserMenu />
|
<UserMenu />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
20
apps/web/src/components/layout/NavBadge.tsx
Normal file
20
apps/web/src/components/layout/NavBadge.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
|
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
|
||||||
|
number is in the accessible name too (sr-only), not only in the dot. */
|
||||||
|
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
|
||||||
|
const count = useReportedPaymentsCount()
|
||||||
|
if (kind !== 'reported-payments' || count === 0) return null
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'flex min-w-5 items-center justify-center rounded-full bg-accent px-1.5 text-[11px] font-semibold leading-5 text-on-accent',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{count > 99 ? '99+' : count}
|
||||||
|
<span className="sr-only"> pagos para verificar</span>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
|
import { NavBadge } from './NavBadge'
|
||||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||||
@@ -23,7 +24,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
|||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<nav className="flex flex-col gap-1">
|
<nav className="flex flex-col gap-1">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
|
||||||
const isActive = isNavItemActive(location.pathname, to)
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -39,6 +40,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
|||||||
>
|
>
|
||||||
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
||||||
{label}
|
{label}
|
||||||
|
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ export type NavItem = {
|
|||||||
label: string
|
label: string
|
||||||
to: string
|
to: string
|
||||||
icon: LucideIcon
|
icon: LucideIcon
|
||||||
|
/** Counter shown on the item (see NavBadge). */
|
||||||
|
badge?: 'reported-payments'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const NAV_ITEMS: NavItem[] = [
|
export const NAV_ITEMS: NavItem[] = [
|
||||||
{ label: 'Inicio', to: '/', icon: Home },
|
{ label: 'Inicio', to: '/', icon: Home },
|
||||||
{ label: 'Grupos', to: '/groups', icon: Users },
|
{ label: 'Grupos', to: '/groups', icon: Users },
|
||||||
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
{ label: 'Cobros', to: '/payments', icon: Wallet, badge: 'reported-payments' },
|
||||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user