9 Commits

Author SHA1 Message Date
Jose Selesan
d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00
Jose Selesan
f1829fb5a9 feat: cambiar a un miembro de grupo
- `POST /groups/:gid/attendees/:aid/move` mueve al mismo attendee a otro
  grupo del profesor: conserva historial, cuotas (siguen del grupo anterior)
  y acceso a la app de alumnos. Cancela las faltas avisadas y libera lo
  reservado en clases futuras del grupo anterior.
- Cupo y teléfono duplicado se validan con `checkCanJoinGroup`, compartido
  con el paso desde la lista de espera.
- Ficha del miembro: "Cambiar de grupo" abre un diálogo con el selector de
  grupo destino y navega a la ficha en el grupo nuevo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:21:32 -03:00
Jose Selesan
fc12ec3ae0 feat: pasar de la lista de espera a otro grupo del profesor
- `POST /groups/:gid/waitlist/:entryId/promote` acepta `targetGroupId`
  opcional (por defecto, el grupo en el que se anotó). El destino tiene que
  ser del mismo profesor; cupo y teléfono duplicado se validan ahí.
- Detalle de la lista de espera: selector "Asignar a" con los grupos llenos
  deshabilitados.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:39:55 -03:00
Jose Selesan
d397e9663c feat: filtro de grupo en cobros con cuotas pendientes por grupo
- El listado de grupos devuelve `unpaidPaymentsCount` (PENDING y OVERDUE).
- Cobros: nuevo selector de grupo (GroupFilter) junto a los filtros de estado;
  con un grupo filtrado no se repite su nombre en cada card.
- Sheet: entra deslizando desde abajo en mobile (salvo reduced motion).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:59:33 -03:00
Jose Selesan
b6f22ae67d feat: add payment report notes 2026-10-28 16:45:55 -03:00
b22b6da2e1 Merge pull request 'feat: add payment options on student portal' (#13) from feat/student-payment-management into development
Reviewed-on: #13
2026-10-28 19:35:13 +00:00
Jose Selesan
9e4d34b5d8 feat: add payment options on student portal 2026-10-28 16:34:28 -03:00
Jose Selesan
bc5f676cea refactor(web): rutas de la app de alumnos en inglés
/acceso → /access, /alumno/* → /student/* (welcome, classes, payments,
profile, notify-absence, report-payment). El link del mail de confirmación
pasa a /access/email/:token. AGENTS.md documenta que los paths van en inglés.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:50:55 -03:00
f6a7b7344e Merge pull request 'feat/improve-ui' (#11) from feat/improve-ui into development
Reviewed-on: #11
2026-10-28 18:40:21 +00:00
133 changed files with 3288 additions and 649 deletions

View File

@@ -65,22 +65,31 @@ 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.
- **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).
- **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:
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/access`, `/student/*`)**: 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**.
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) 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`.
- **Personas y membresías (`Person` / `Attendee`)**: una persona puede estar en varios grupos del mismo profe. Ojo con esto:
1. `Person` (`people`, del profe vía `created_by_id`) tiene los datos de contacto y las notas; `Attendee` es la **membresía** (`group_id` + `person_id` + `status` + `notify_token`), con `@@unique([groupId, personId])`. Asistencia, cuotas, alertas y mensajes siguen siendo por attendee (por grupo). (`Member` ya existe: es la organización de Better Auth.)
2. El teléfono es único por profe con un índice **parcial** a mano (`people_owner_phone_key`, `WHERE phone IS NOT NULL`): Prisma no lo modela y un choque llega como `P2002` (`isUniqueViolation` en `modules/people/lib/people.ts`). Los teléfonos se guardan normalizados (`normalizePhone`, también al editar); `phoneVariants` cubre filas viejas.
3. Las altas resuelven a la persona por teléfono: el alta individual sin `personId` con un teléfono existente responde `409 person_exists` (la web lo detecta antes con `GET /people/lookup?groupId=&phone=` y manda `personId`); bulk, lista de espera y preinscripciones vinculan solas (`findOrCreatePerson`). Ya estar en el grupo es `attendee_already_registered`; una membresía `DROPPED` se reactiva.
4. `POST /groups/:gid/attendees/:aid/add-to-group` ("Agregar a otro grupo") crea otra membresía de la misma persona; `move` sigue cambiando el `groupId` de la misma membresía. Ambas validan con `checkCanJoinGroup(db, group, personId)`.
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
## Convenciones repo-específicas
- **Frontend en español**: copy de UI, comentarios y textos en español.
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
- **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`).

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;

View File

@@ -0,0 +1,182 @@
-- A person (contact data, per teacher) can now be in several groups: `attendees`
-- becomes the membership and points to `people`. Existing attendees of the same
-- teacher with the same phone (digits only) are merged into one person, and
-- their student-app accounts into one account.
-- All or nothing: a half-applied data migration cannot be retried.
BEGIN;
-- CreateTable
CREATE TABLE "people" (
"id" TEXT NOT NULL,
"created_by_id" TEXT NOT NULL,
"full_name" TEXT NOT NULL,
"email" TEXT,
"phone" TEXT,
"guardian_name" TEXT,
"guardian_phone" TEXT,
"notes" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "people_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_account_people" (
"account_id" TEXT NOT NULL,
"person_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id")
);
-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare)
-- rows that already shared a phone inside one group, which the per-group unique
-- membership would reject: the extra ones become their own person.
CREATE TEMP TABLE "_attendee_keys" AS
SELECT
a."id" AS attendee_id,
a."group_id",
a."created_at",
g."created_by_id",
NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits,
ROW_NUMBER() OVER (
PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '')
ORDER BY a."created_at", a."id"
) AS group_rank
FROM "attendees" a
JOIN "groups" g ON g."id" = a."group_id";
CREATE TEMP TABLE "_attendee_person" AS
SELECT
k.attendee_id,
k.created_by_id,
-- The person reuses the id of its oldest attendee.
FIRST_VALUE(k.attendee_id) OVER (
PARTITION BY k.created_by_id,
CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END
ORDER BY k.created_at, k.attendee_id
) AS person_id,
(k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash
FROM "_attendee_keys" k;
INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at")
SELECT
p.person_id,
MIN(p.created_by_id),
MIN(rep."full_name"),
(ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1],
CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END,
(ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1],
(ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1],
NULLIF(CONCAT_WS(E'\n\n',
STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'),
CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END
), ''),
MIN(a."created_at"),
CURRENT_TIMESTAMP
FROM "_attendee_person" p
JOIN "attendees" a ON a."id" = p.attendee_id
JOIN "attendees" rep ON rep."id" = p.person_id
GROUP BY p.person_id;
-- AlterTable: attendees -> membership
ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT;
UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id";
ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL;
-- Student accounts: link them to the person instead of the membership.
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
SELECT sa."account_id", p.person_id, MIN(sa."created_at")
FROM "student_account_attendees" sa
JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id"
GROUP BY sa."account_id", p.person_id;
-- A merged person may end up with several accounts: keep the one used most
-- recently (else the oldest) and fold the others into it.
CREATE TEMP TABLE "_account_merge" AS
WITH ranked AS (
SELECT
sap."person_id",
sap."account_id",
ROW_NUMBER() OVER (
PARTITION BY sap."person_id"
ORDER BY (
SELECT MAX(s."last_used_at") FROM "student_sessions" s
WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL
) DESC NULLS LAST, acc."created_at", acc."id"
) AS rn
FROM "student_account_people" sap
JOIN "student_accounts" acc ON acc."id" = sap."account_id"
)
SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id
FROM ranked d
JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1
WHERE d.rn > 1 AND d."account_id" <> k."account_id"
ORDER BY d."account_id";
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
SELECT m.keep_id, sap."person_id", sap."created_at"
FROM "student_account_people" sap
JOIN "_account_merge" m ON m.old_id = sap."account_id"
ON CONFLICT DO NOTHING;
UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id;
UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id;
UPDATE "student_accounts" k
SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at"
FROM "_account_merge" m
JOIN "student_accounts" o ON o."id" = m.old_id
WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL;
-- Sessions, tokens and passkeys of the folded accounts go with them (cascade);
-- their links are removed by hand because that FK is created further down.
DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge");
DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge");
-- DropTable
DROP TABLE "student_account_attendees";
-- AlterTable
ALTER TABLE "attendees"
DROP COLUMN "full_name",
DROP COLUMN "email",
DROP COLUMN "phone",
DROP COLUMN "guardian_name",
DROP COLUMN "guardian_phone",
DROP COLUMN "notes";
-- CreateIndex
CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id");
-- One person per phone and teacher. Partial: Prisma does not model it.
CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL;
-- CreateIndex
CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id");
-- CreateIndex
CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id");
-- CreateIndex
CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id");
-- AddForeignKey
ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
DROP TABLE "_account_merge";
DROP TABLE "_attendee_person";
DROP TABLE "_attendee_keys";
COMMIT;

View File

@@ -28,6 +28,7 @@ model User {
whatsappAccount WhatsappAccount?
subscription BillingSubscription?
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
people Person[] @relation("OwnerPeople")
@@map("users")
}

View File

@@ -72,31 +72,55 @@ enum AttendeeStatus {
DROPPED
}
model Attendee {
// A person the teacher works with (student, or the guardian's child). Contact
// data lives here once; `Attendee` is their membership in each group, so one
// person can be in several groups of the same teacher. The phone is unique per
// teacher through a hand-written partial index (`people_owner_phone_key`,
// `WHERE phone IS NOT NULL`): Prisma does not model it.
model Person {
id String @id @default(cuid())
groupId String @map("group_id")
createdById String @map("created_by_id")
fullName String @map("full_name")
email String?
phone String?
guardianName String? @map("guardian_name")
guardianPhone String? @map("guardian_phone")
notes String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
attendees Attendee[]
studentAccounts StudentAccountPerson[]
@@index([createdById])
@@map("people")
}
// Membership of a person in a group. Status, attendance, fees and the absence
// link (`notifyToken`) are per group.
model Attendee {
id String @id @default(cuid())
groupId String @map("group_id")
personId String @map("person_id")
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
status AttendeeStatus @default(ACTIVE)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
payments Payment[]
attendances Attendance[]
slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[]
studentAccounts StudentAccountAttendee[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@unique([groupId, personId])
@@index([groupId], map: "attendees_groupId_idx")
@@index([personId])
@@map("attendees")
}

View File

@@ -24,7 +24,7 @@ model StudentAccount {
updatedAt DateTime @updatedAt @map("updated_at")
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
attendees StudentAccountAttendee[]
people StudentAccountPerson[]
tokens StudentAccessToken[]
sessions StudentSession[]
passkeys StudentPasskey[]
@@ -37,17 +37,20 @@ model StudentAccount {
@@map("student_accounts")
}
model StudentAccountAttendee {
// The account is linked to people, not to memberships: it sees every group the
// person is in (also the ones added later). A guardian may be linked to several
// children (N:N).
model StudentAccountPerson {
accountId String @map("account_id")
attendeeId String @map("attendee_id")
personId String @map("person_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)
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
@@id([accountId, attendeeId])
@@index([attendeeId])
@@map("student_account_attendees")
@@id([accountId, personId])
@@index([personId])
@@map("student_account_people")
}
enum StudentTokenKind {
@@ -203,6 +206,8 @@ model ReportedPayment {
receiptMime String @map("receipt_mime")
receiptName String @map("receipt_name")
receiptSize Int @map("receipt_size")
// Optional message from the student to the teacher.
note String?
status ReportedPaymentStatus @default(REPORTED)
reviewedById String? @map("reviewed_by_id")
reviewedAt DateTime? @map("reviewed_at")

View File

@@ -27,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
import { mpRoutes } from './modules/mp';
import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments';
import { peopleRoutes } from './modules/people';
import { studentPortalRoutes } from './modules/student-portal';
import { waitlistRoutes } from './modules/waitlist';
import { whatsappRoutes } from './modules/whatsapp';
@@ -68,6 +69,7 @@ api.route('/classes', classesRoutes);
api.route('/students', studentStatusRoutes);
api.route('/groups-risk', groupsRiskOverviewRoute);
api.route('/attention', attentionRoutes);
api.route('/people', peopleRoutes);
api.route('/student-portal', studentPortalRoutes);
app.notFound((c) => {

View File

@@ -8,6 +8,7 @@ import type {
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
export const HISTORY_SESSIONS_LIMIT = 20;
@@ -33,8 +34,8 @@ export class GetAttendeeHistory {
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { id: true, fullName: true, createdAt: true },
});
select: { id: true, createdAt: true, person: { select: { fullName: true } } },
}).then((row) => row && flattenPerson(row));
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}

View File

@@ -15,6 +15,7 @@ import {
URGENT_MEMBERS_LIMIT,
} from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
@@ -76,8 +77,8 @@ export class GetGroupsRiskOverview {
const [attendees, sessions, attendances] = await Promise.all([
db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, createdAt: true },
}) as Promise<AttendeeRow[]>,
select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
select: { id: true, groupId: true, startsAt: true },

View File

@@ -8,6 +8,7 @@ import type {
} from '@gruperly/shared';
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
@@ -73,8 +74,8 @@ export async function findStudentsAtRisk(
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true, createdAt: true },
}),
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
}).then((rows) => rows.map(flattenPerson)),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {

View File

@@ -0,0 +1,24 @@
import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
import { AddAttendeeToGroupSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { AddAttendeeToGroup } from './use-case';
const route = new Hono();
route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new AddAttendeeToGroup();
const result = await useCase.execute({
groupId: c.req.param('groupId'),
attendeeId: c.req.param('attendeeId'),
userId: user.id,
targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
});
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,88 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
type AddAttendeeToGroupDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
};
type AddAttendeeToGroupCommand = {
groupId: string;
attendeeId: string;
userId: string;
targetGroupId: string;
};
/* "Agregar a otro grupo": the same person gets a membership in another group of
the teacher and keeps this one. It does not take a new student slot of the
plan (the person is already counted) but the target's capacity applies. A
former membership there (DROPPED) is reactivated, history included. */
export class AddAttendeeToGroup {
constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
async execute(command: AddAttendeeToGroupCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
const { groupId, attendeeId, userId, targetGroupId } = command;
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
if (!sourceResult.ok) return sourceResult;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
if (targetGroupId === groupId) {
return err(
conflictProblem({
detail: 'El miembro ya pertenece a este grupo.',
code: 'attendee_same_group',
}),
);
}
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) return targetResult;
const target = targetResult.value;
try {
return await unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
const former = await tx.attendee.findFirst({
where: { groupId: targetGroupId, personId: attendee.personId },
select: { id: true, status: true },
});
if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
const canJoin = await checkCanJoinGroup(tx, target, null);
if (!canJoin.ok) return canJoin;
const membership = former
? await tx.attendee.update({
where: { id: former.id },
data: { status: 'ACTIVE' },
include: attendeeWithPerson,
})
: await tx.attendee.create({
data: { groupId: targetGroupId, personId: attendee.personId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(membership));
},
);
} catch (error) {
// Two clicks at once: the unique (group, person) lets only one through.
if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
throw error;
}
}
}

View File

@@ -8,6 +8,7 @@ import {
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { phoneVariants } from '@/modules/people/lib/people';
import { normalizePhone } from '../../lib/helpers';
type AddToGroupWaitlistDeps = {
@@ -72,10 +73,7 @@ export class AddToGroupWaitlist {
const existingAttendee = await db.attendee.findFirst({
where: {
groupId,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
person: { phone: { in: phoneVariants(payload.phone) } },
},
});

View File

@@ -9,10 +9,10 @@ import { err, ok } from '@gruperly/shared';
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type BulkCreateAttendeesDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -43,23 +43,29 @@ export class BulkCreateAttendeesUseCase {
return err(noGroupAccessProblem());
}
// Load the group's existing phone numbers
const existingAttendees = await db.attendee.findMany({
where: { groupId },
select: { phone: true },
/* The teacher's people by phone: a row whose phone is already someone they
have is added to this group as that person (linked), unless that person
is already in the group (duplicate). */
const people = await db.person.findMany({
where: { createdById: group.createdById, phone: { not: null } },
select: {
id: true,
phone: true,
attendees: { select: { groupId: true, status: true } },
},
});
const existingPhones = new Set<string>();
for (const a of existingAttendees) {
if (a.phone) {
existingPhones.add(normalizePhone(a.phone));
}
const peopleByPhone = new Map<string, (typeof people)[number]>();
for (const person of people) {
if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
}
let duplicatesCount = 0;
let invalidCount = 0;
const toCreateData: Array<{
groupId: string;
// Only people not active in any group take a new slot of the plan.
let newlyCounted = 0;
const seenPhones = new Set<string>();
const toLink: string[] = [];
const toCreate: Array<{
fullName: string;
phone: string;
email: string | null;
@@ -75,14 +81,21 @@ export class BulkCreateAttendeesUseCase {
continue;
}
if (existingPhones.has(phone)) {
const existing = peopleByPhone.get(phone);
if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
duplicatesCount++;
continue;
}
seenPhones.add(phone);
existingPhones.add(phone);
toCreateData.push({
groupId,
if (existing) {
toLink.push(existing.id);
if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
continue;
}
newlyCounted++;
toCreate.push({
fullName: rawFullName,
phone,
email: item.email?.trim() || null,
@@ -94,26 +107,44 @@ export class BulkCreateAttendeesUseCase {
// reason about than a clear "your plan allows N".
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
group.createdById,
toCreateData.length,
newlyCounted,
);
if (!allowed.ok) {
return allowed;
}
const createdRecords: AttendeeRecord[] = [];
for (const data of toCreateData) {
const record = await db.attendee.create({ data });
createdRecords.push(record as unknown as AttendeeRecord);
for (const personId of toLink) {
createdRecords.push(
await db.attendee.create({
data: { groupId, personId },
include: attendeeWithPerson,
}),
);
}
for (const data of toCreate) {
createdRecords.push(
await db.attendee.create({
data: {
group: { connect: { id: groupId } },
person: { create: { ...data, createdById: group.createdById } },
},
include: attendeeWithPerson,
}),
);
}
const createdCount = createdRecords.length;
const linkedCount = toLink.length;
const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
const message = duplicatesCount > 0
? `${createdCount} alumnos agregados con éxito, ${duplicatesCount} duplicados omitidos.`
: `${createdCount} alumnos agregados con éxito.`;
? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
: `${createdCount} alumnos agregados con éxito${linkedNote}.`;
return ok({
totalProcessed: payload.attendees.length,
createdCount,
linkedCount,
duplicatesCount,
invalidCount,
message,

View File

@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
import {
alreadyWaitlistedProblem,
capacityReachedProblem,
conflictProblem,
noGroupAccessProblem,
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
import {
alreadyInGroupProblem,
findPersonByPhone,
isUniqueViolation,
personExistsProblem,
} from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
}
const phone = normalizePhone(payload.phone);
const existing = await db.attendee.findFirst({
where: {
groupId,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
},
});
if (existing) {
/* The person: the one the form picked (`personId`, after the "ya existe"
hint) or a new one. A phone the teacher already has is never duplicated. */
let person: { id: string; fullName: string } | null = null;
if (payload.personId) {
person = await db.person.findFirst({
where: { id: payload.personId, createdById: group.createdById },
select: { id: true, fullName: true },
});
if (!person) {
return err(notFoundResourceProblem('Person', payload.personId));
}
} else {
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
if (samePhone) {
return err(
conflictProblem({
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
code: 'attendee_already_registered',
}),
samePhone.attendees.some((membership) => membership.groupId === groupId)
? alreadyInGroupProblem()
: personExistsProblem(),
);
}
}
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
// A former member (DROPPED) comes back on the same membership: history included.
const membership = person
? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
: null;
if (membership && membership.status !== 'DROPPED') {
return err(alreadyInGroupProblem());
}
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
if (group.capacity !== null) {
const currentCount = await db.attendee.count({
@@ -108,25 +125,51 @@ export class CreateAttendeeUseCase {
}
}
// The owner's plan pays for the attendee, whoever adds it.
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
// The owner's plan pays for the attendee, whoever adds it. It counts people:
// someone already active in another group does not take a new slot.
const alreadyCounted = person
? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
: false;
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
group.createdById,
alreadyCounted ? 0 : 1,
);
if (!allowed.ok) {
return allowed;
}
const attendee = await db.attendee.create({
try {
const attendee = membership
? await db.attendee.update({
where: { id: membership.id },
data: { status: 'ACTIVE' },
include: attendeeWithPerson,
})
: await db.attendee.create({
data: {
groupId,
group: { connect: { id: groupId } },
person: person
? { connect: { id: person.id } }
: {
create: {
createdById: group.createdById,
fullName,
phone,
email: payload.email?.trim() || null,
notes: payload.notes?.trim() || null,
},
},
},
include: attendeeWithPerson,
});
return ok({
outcome: 'created',
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord),
});
return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
} catch (error) {
// Lost a race: someone created that person or membership meanwhile.
if (isUniqueViolation(error)) {
return err(person ? alreadyInGroupProblem() : personExistsProblem());
}
throw error;
}
}
}

View File

@@ -4,7 +4,7 @@ import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma';
import { toAttendeeListItemDto } from '../../lib/helpers';
import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
type ListAttendeesDeps = {
db?: Pick<PrismaClient, 'attendee'>;
@@ -28,6 +28,7 @@ export class ListAttendees {
take: query.pageSize,
orderBy: { createdAt: 'desc' },
include: {
...attendeeWithPerson,
// By class date, not by `markedAt`: marking attendance late must not
// change which class counts as recent.
attendances: {

View File

@@ -4,8 +4,8 @@ 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 { toAttendeeDetailDto } from '../../lib/helpers';
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
type GetAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
@@ -31,6 +31,7 @@ export class GetAttendee {
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
include: {
person: { select: { ...personContactSelect, ...personMembershipsSelect } },
payments: {
where: {
status: { not: 'CANCELLED' },
@@ -46,7 +47,14 @@ export class GetAttendee {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
return ok(toAttendeeDetailDto(attendee));
const { attendees: memberships, ...person } = attendee.person;
return ok(
toAttendeeDetailDto({
...attendee,
person,
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
}),
);
}
}

View File

@@ -0,0 +1,24 @@
import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
import { MoveAttendeeSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { MoveAttendee } from './use-case';
const route = new Hono();
route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new MoveAttendee();
const result = await useCase.execute({
groupId: c.req.param('groupId'),
attendeeId: c.req.param('attendeeId'),
userId: user.id,
targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
});
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,77 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
type MoveAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
unitOfWork?: UnitOfWork;
now?: () => Date;
};
type MoveAttendeeCommand = {
groupId: string;
attendeeId: string;
userId: string;
targetGroupId: string;
};
/* Moves a member to another group of the same teacher. It is the same attendee
with another `groupId`: past attendance, fees (they stay owed to the old
group) and the student app access go with them. Only what was booked for
the old group's future classes is undone: absence notices, the EXCUSED rows
they left and the released slots. */
export class MoveAttendee {
constructor(private readonly deps: MoveAttendeeDeps = {}) {}
async execute(command: MoveAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
const { groupId, attendeeId, userId, targetGroupId } = command;
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const now = this.deps.now?.() ?? new Date();
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
if (!sourceResult.ok) return sourceResult;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
if (targetGroupId === groupId) {
return err(
conflictProblem({
detail: 'El miembro ya pertenece a este grupo.',
code: 'attendee_same_group',
}),
);
}
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) return targetResult;
return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
if (!canJoin.ok) return canJoin;
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
await tx.absenceNotice.updateMany({
where: { attendeeId, cancelledAt: null, ...futureOldClasses },
data: { cancelledAt: now },
});
await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
const moved = await tx.attendee.update({
where: { id: attendeeId },
data: { groupId: targetGroupId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(moved));
},
);
}
}

View File

@@ -36,7 +36,10 @@ export class RemoveAttendee {
}
const group = groupResult.value;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
@@ -49,6 +52,10 @@ export class RemoveAttendee {
return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
await tx.attendee.delete({ where: { id: attendeeId } });
// Their last group: the person goes too (with their student app link).
await tx.person.deleteMany({
where: { id: attendee.personId, attendees: { none: {} } },
});
if (!options.promoteFromWaitlist) {
return ok({ removedAttendeeId: attendeeId, promoted: null });

View File

@@ -4,10 +4,11 @@ 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 { toAttendeeDto } from '../../lib/helpers';
import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type UpdateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
};
type UpdateAttendeeCommand = {
@@ -26,19 +27,38 @@ export class UpdateAttendeeDetails {
const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
const updated = await db.attendee.update({
where: { id: attendeeId },
// Contact data is the person's: the change shows in every group they are in.
try {
await db.person.update({
where: { id: attendee.personId },
data: normalizeEditableFields(input),
});
} catch (error) {
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
throw error;
}
const updated = await db.attendee.findUniqueOrThrow({
where: { id: attendeeId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(updated));
}
}
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
return Object.fromEntries(
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
Object.entries(input).map(([key, value]) => {
if (value === '') return [key, null];
// Same normalization as the add form, so the phone keeps matching.
if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
return [key, value];
}),
);
}

View File

@@ -1,17 +1,37 @@
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
export type AttendeeRecord = {
/* Contact data of the person behind an attendee (shared by all their groups). */
export const personContactSelect = {
id: true,
fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
} as const;
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
export type PersonContactRecord = {
id: string;
groupId: string;
fullName: string;
email: string | null;
phone: string | null;
guardianName: string | null;
guardianPhone: string | null;
notes: string | null;
};
export type AttendeeRecord = {
id: string;
groupId: string;
personId: string;
notifyToken?: string | null;
createdAt: Date;
updatedAt: Date;
person: PersonContactRecord;
};
/** Listing item with the attendance and payment summary already resolved. */
@@ -25,18 +45,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
export type AttendeeDetailRecord = AttendeeRecord & {
payments: AttendeeListItemRecord['payments'];
otherGroups: AttendeeDetailDto['otherGroups'];
};
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
return {
id: record.id,
groupId: record.groupId,
fullName: record.fullName,
email: record.email,
phone: record.phone,
guardianName: record.guardianName,
guardianPhone: record.guardianPhone,
notes: record.notes,
personId: record.personId,
fullName: record.person.fullName,
email: record.person.email,
phone: record.person.phone,
guardianName: record.person.guardianName,
guardianPhone: record.person.guardianPhone,
notes: record.person.notes,
notifyToken: record.notifyToken ?? null,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(),
@@ -68,6 +90,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
return {
...toAttendeeDto(record),
payment: pickRelevantPayment(record.payments),
otherGroups: record.otherGroups,
};
}
@@ -91,3 +114,13 @@ export function normalizePhone(rawPhone: string): string {
const digitsOnly = trimmed.replace(/\D/g, '');
return hasPlus ? `+${digitsOnly}` : digitsOnly;
}
/* For queries that select a few person fields next to the attendee's: turns
`{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
flat rows stays as it was. */
export function flattenPerson<TRow extends { person: object }>(
row: TRow,
): Omit<TRow, 'person'> & TRow['person'] {
const { person, ...rest } = row;
return { ...rest, ...person };
}

View File

@@ -11,7 +11,9 @@ import type {
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { contactPhone } from '@/modules/people/lib/people';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = {
@@ -82,9 +84,14 @@ export class GetAttentionOverview {
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 },
select: {
id: true,
groupId: true,
createdAt: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } },
},
orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>,
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
// Past classes only, most recent first: `toMemberAttendance` keeps the
// last 20 per attendee, more than the 6-class window needs.
db.classSession.findMany({
@@ -154,7 +161,7 @@ export class GetAttentionOverview {
firma: row.signature,
}));
const phone = attendee.phone ?? attendee.guardianPhone;
const phone = contactPhone(attendee);
return {
attendeeId: attendee.id,
fullName: attendee.fullName,

View File

@@ -86,7 +86,7 @@ export type Entitlements = PlanResolution & {
};
type PlanGuardDeps = {
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'person'>;
enforced?: boolean;
graceDays?: number;
now?: () => Date;
@@ -116,7 +116,10 @@ export class PlanGuard {
select: { status: true, authorizedAt: true, paidThrough: true },
}),
db.group.count({ where: { createdById: ownerId } }),
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
// People, not memberships: someone in three groups is one student.
db.person.count({
where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } },
}),
]);
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());

View File

@@ -32,6 +32,7 @@ export class GetAbsenceDetails {
where: { notifyToken: query.token },
include: {
group: { select: { id: true, name: true, days: true, time: true } },
person: { select: { fullName: true } },
},
});
if (!attendee) {
@@ -46,7 +47,7 @@ export class GetAbsenceDetails {
if (candidates.length === 0) {
return ok({
attendeeId: attendee.id,
fullName: attendee.fullName,
fullName: attendee.person.fullName,
groupName: attendee.group.name,
sessions: [],
});
@@ -75,7 +76,7 @@ export class GetAbsenceDetails {
return ok({
attendeeId: attendee.id,
fullName: attendee.fullName,
fullName: attendee.person.fullName,
groupName: attendee.group.name,
sessions: sessions.map((session) => {
const attendanceStatus = attendanceBySession.get(session.id) ?? null;

View File

@@ -7,6 +7,7 @@ import type {
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
import {
type ClassesDb,
@@ -60,8 +61,9 @@ export class GetSessionStudents {
const [attendees, payments, attendances, releases] = await Promise.all([
db.attendee.findMany({
where: { groupId: session.groupId },
orderBy: { fullName: 'asc' },
}),
orderBy: { person: { fullName: 'asc' } },
include: { person: { select: { fullName: true } } },
}).then((rows) => rows.map(flattenPerson)),
db.payment.findMany({
where: { groupId: session.groupId },
select: { attendeeId: true, status: true, dueDate: true },

View File

@@ -8,6 +8,7 @@ import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { countsAsNewStudent } from '@/modules/people/lib/people';
import {
findGroupOwnedByUser,
type GroupWaitlistEntryRecord,
@@ -17,7 +18,7 @@ import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote'
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
type ApproveGroupPreRegistrationDeps = {
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration' | 'person'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -53,7 +54,8 @@ export class ApproveGroupPreRegistration {
);
}
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
if (!allowed.ok) {
return allowed;
}

View File

@@ -1,19 +1,26 @@
import { type PromoteGroupWaitlistEntry as PromoteBody, PromoteGroupWaitlistEntrySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { PromoteGroupWaitlistEntry } from './use-case';
const route = new Hono();
route.post('/:groupId/waitlist/:entryId/promote', async (c) => {
route.post(
'/:groupId/waitlist/:entryId/promote',
validate.json(PromoteGroupWaitlistEntrySchema),
async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const groupId = c.req.param('groupId');
const entryId = c.req.param('entryId');
const body = c.req.valid('json') as PromoteBody;
const useCase = new PromoteGroupWaitlistEntry();
const result = await useCase.execute(groupId, entryId, user.id);
const result = await useCase.execute(groupId, entryId, user.id, body.targetGroupId);
return resultJson(c, result);
});
},
);
export default route;

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { countsAsNewStudent } from '@/modules/people/lib/people';
import {
findGroupOwnedByUser,
type GroupWaitlistEntryRecord,
@@ -11,7 +12,7 @@ import {
import { promoteWaitlistEntryRecord } from '../../lib/promote';
type PromoteGroupWaitlistEntryDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -23,6 +24,7 @@ export class PromoteGroupWaitlistEntry {
groupId: string,
entryId: string,
userId: string,
targetGroupId?: string,
): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
@@ -39,7 +41,19 @@ export class PromoteGroupWaitlistEntry {
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
}
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
// The entry leaves the waitlist of its own group but can land in another
// group of the same teacher (capacity and duplicates are checked there).
let targetGroup = groupResult.value;
if (targetGroupId && targetGroupId !== groupId) {
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) {
return targetResult;
}
targetGroup = targetResult.value;
}
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
if (!allowed.ok) {
return allowed;
}
@@ -48,7 +62,7 @@ export class PromoteGroupWaitlistEntry {
async (tx: Prisma.TransactionClient) => {
const promoteResult = await promoteWaitlistEntryRecord(
tx,
groupResult.value,
targetGroup,
entry as unknown as GroupWaitlistEntryRecord,
);
if (!promoteResult.ok) {

View File

@@ -1,15 +1,17 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders';
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers';
import { capacityReachedProblem } from '@/http/problem-builders';
import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers';
import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people';
import { type GroupWaitlistEntryRecord } from './helpers';
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>;
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry' | 'person'>;
type PromoteGroup = {
id: string;
capacity: number | null;
createdById: string;
};
export async function findFirstPendingWaitlistEntry(
@@ -23,11 +25,14 @@ export async function findFirstPendingWaitlistEntry(
return record as GroupWaitlistEntryRecord | null;
}
export async function promoteWaitlistEntryRecord(
db: PromoteDb,
group: PromoteGroup,
entry: GroupWaitlistEntryRecord,
): Promise<Result<AttendeeDto, ProblemDetails>> {
/* Whether someone can join `group`: free capacity (ACTIVE members) and the
person (when there already is one) not being a member there yet. Shared by
the waitlist promotion, the member move and "Agregar a otro grupo". */
export async function checkCanJoinGroup(
db: Pick<PrismaClient, 'attendee'>,
group: Pick<PromoteGroup, 'id' | 'capacity'>,
personId: string | null,
): Promise<Result<void, ProblemDetails>> {
if (group.capacity !== null) {
const currentCount = await db.attendee.count({
where: { groupId: group.id, status: 'ACTIVE' },
@@ -37,29 +42,44 @@ export async function promoteWaitlistEntryRecord(
}
}
if (personId) {
const existing = await db.attendee.findFirst({
where: { groupId: group.id, phone: entry.phone },
where: { groupId: group.id, personId },
select: { id: true },
});
if (existing) {
return err(
conflictProblem({
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
code: 'attendee_already_registered',
}),
);
return err(alreadyInGroupProblem());
}
}
const attendee = await db.attendee.create({
data: {
groupId: group.id,
return ok(undefined);
}
/* The entry has its own contact data; if its phone is already one of the
teacher's people, the new membership goes to that person. */
export async function promoteWaitlistEntryRecord(
db: PromoteDb,
group: PromoteGroup,
entry: GroupWaitlistEntryRecord,
): Promise<Result<AttendeeDto, ProblemDetails>> {
const person = await findOrCreatePerson(db, group.createdById, {
fullName: entry.fullName,
phone: entry.phone,
email: entry.email,
notes: entry.notes,
},
});
return ok(toAttendeeDto(attendee as unknown as AttendeeRecord));
const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id);
if (!canJoin.ok) {
return canJoin;
}
const attendee = await db.attendee.create({
data: { groupId: group.id, personId: person.id },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(attendee));
}
export type PromoteFirstResult = {

View File

@@ -21,13 +21,15 @@ type ListGroupsDeps = {
now?: Date;
};
const OCCUPANCY_COUNT_INCLUDE = {
const LIST_COUNT_INCLUDE = {
_count: {
select: {
// Group members. No status filter, same as the detail page counts.
attendees: true,
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
waitlist: { where: { status: 'PENDING' as const } },
// Payments still to collect: the ones pending and the overdue ones.
payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } },
},
},
} satisfies Prisma.GroupInclude;
@@ -49,7 +51,7 @@ export class ListGroups {
// time zone (or the server's if it doesn't come along).
const records: GroupListRecord[] = await db.group.findMany({
where,
include: OCCUPANCY_COUNT_INCLUDE,
include: LIST_COUNT_INCLUDE,
});
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;

View File

@@ -26,9 +26,10 @@ export type GroupRecord = {
/* The listing adds the occupancy counters to each group so the card can show
them without asking for one endpoint per group. They come from the `_count` of
the same query: all the members (same as the detail page counts) and only the
waitlist entries still waiting for a spot (PENDING). */
waitlist entries still waiting for a spot (PENDING), plus the payments still
to collect (PENDING and OVERDUE). */
export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number };
_count?: { attendees: number; waitlist: number; payments?: number };
};
export function toGroupDto(record: GroupRecord): GroupDto {
@@ -56,6 +57,7 @@ export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
...toGroupDto(record),
attendeesCount: record._count?.attendees ?? 0,
waitlistCount: record._count?.waitlist ?? 0,
unpaidPaymentsCount: record._count?.payments ?? 0,
};
}

View File

@@ -1,10 +1,12 @@
import { Hono } from 'hono';
import analyticsRoutes from '../analytics/routes';
import addAttendeeToGroupRoute from '../attendees/features/add-to-group/route';
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
import createAttendeeRoute from '../attendees/features/create/route';
import getAttendeeRoute from '../attendees/features/get-by-id/route';
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
import moveAttendeeRoute from '../attendees/features/move/route';
import removeAttendeeRoute from '../attendees/features/remove/route';
import updateAttendeeRoute from '../attendees/features/update/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
@@ -37,6 +39,8 @@ routes.route('/', getAttendeeRoute);
routes.route('/', updateAttendeeRoute);
routes.route('/', getAttendeeStatsRoute);
routes.route('/', removeAttendeeRoute);
routes.route('/', moveAttendeeRoute);
routes.route('/', addAttendeeToGroupRoute);
routes.route('/', studentAccessRoutes);
export default routes;

View File

@@ -74,7 +74,7 @@ export class GetHomeSummary {
take: UPCOMING_PAYMENTS_LIMIT,
include: {
group: { select: { name: true } },
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
}),
]);
@@ -96,7 +96,7 @@ export class GetHomeSummary {
dueDate: payment.dueDate.toISOString(),
status: payment.status,
groupName: payment.group.name,
attendeeName: payment.attendee.fullName,
attendeeName: payment.attendee.person.fullName,
})),
pendingPreRegistrations: groups
.filter((group) => group._count.preRegistrations > 0)

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { normalizePhone } from '@/modules/attendees/lib/helpers';
import { phoneVariants } from '@/modules/people/lib/people';
type JoinViaInviteDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
@@ -36,10 +37,7 @@ export class JoinViaInvite {
const existing = await db.attendee.findFirst({
where: {
groupId: group.id,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
person: { phone: { in: phoneVariants(payload.phone) } },
},
});
@@ -58,10 +56,7 @@ export class JoinViaInvite {
const existingPreRegistration = await db.groupPreRegistration.findFirst({
where: {
groupId: group.id,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
phone: { in: phoneVariants(payload.phone) },
},
});

View File

@@ -19,6 +19,7 @@ import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH } from '../../lib';
type BatchDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
@@ -80,6 +81,7 @@ export class CreatePaymentBatch {
status: 'ACTIVE',
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
},
include: { person: { select: { fullName: true } } },
});
if (attendees.length === 0) {
return err(noAttendeesToBillProblem());
@@ -95,7 +97,7 @@ export class CreatePaymentBatch {
return token;
}
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
const dueDate = new Date(input.dueDate);
const title = input.description?.trim() || group.name;
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
@@ -149,7 +151,7 @@ export class CreatePaymentBatch {
items.push({
paymentId: payment.id,
attendeeId: attendee.id,
attendeeName: attendee.fullName,
attendeeName: attendee.person.fullName,
amount: unitPrice,
currency,
checkoutUrl: link?.initPoint ?? null,

View File

@@ -36,7 +36,7 @@ export class ListPayments {
where,
include: {
group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
skip: getPaginationOffset(query),
take: query.pageSize,

View File

@@ -12,7 +12,7 @@ import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { type PaymentRecord, toPaymentDto } from '../../lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>;
@@ -35,7 +35,7 @@ export class RenewPaymentLink {
const payment = await db.payment.findUnique({
where: { id: paymentId },
include: {
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
group: {
select: {
name: true,
@@ -83,7 +83,7 @@ export class RenewPaymentLink {
return token;
}
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
let preference: { initPoint: string; id: string };
@@ -106,7 +106,7 @@ export class RenewPaymentLink {
where: { id: payment.id },
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
include: {
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } },
},
});

View File

@@ -26,11 +26,12 @@ const reportSelect = {
createdAt: true,
totalAmount: true,
currency: true,
note: true,
receiptKey: true,
receiptMime: true,
receiptName: true,
receiptSize: true,
attendee: { select: { id: true, fullName: true } },
attendee: { select: { id: true, person: { select: { fullName: true } } } },
group: { select: { id: true, name: true } },
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
} satisfies Prisma.ReportedPaymentSelect;
@@ -201,11 +202,12 @@ export class ReportedPayments {
return {
id: row.id,
status: STATUS[row.status],
attendee: row.attendee,
attendee: { id: row.attendee.id, fullName: row.attendee.person.fullName },
group: row.group,
createdAt: row.createdAt.toISOString(),
totalAmount: row.totalAmount.toNumber(),
currency: row.currency,
note: row.note,
fees: row.items
.map(({ payment }) => ({
id: payment.id,

View File

@@ -1,5 +1,9 @@
import type { PaymentDto } from '@gruperly/shared';
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
(without a student session it falls through to /access). */
export const CHECKOUT_BACK_PATH = '/student/payments';
export type PaymentRecord = {
id: string;
groupId: string;
@@ -14,7 +18,7 @@ export type PaymentRecord = {
createdAt: Date;
updatedAt: Date;
group: { name: string; price: unknown };
attendee: { fullName: string };
attendee: { person: { fullName: string } };
};
export function toPaymentDto(record: PaymentRecord): PaymentDto {
@@ -23,7 +27,7 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
groupId: record.groupId,
groupName: record.group.name,
attendeeId: record.attendeeId,
attendeeName: record.attendee.fullName,
attendeeName: record.attendee.person.fullName,
amount: Number(record.amount.toString()),
currency: record.currency,
status: record.status,

View File

@@ -1 +1 @@
export { type PaymentRecord, toPaymentDto } from './helpers';
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -0,0 +1,18 @@
import type { PersonLookupQuery } from '@gruperly/shared';
import { PersonLookupQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { LookupPerson } from './use-case';
const route = new Hono();
route.get('/lookup', validate.query(PersonLookupQuerySchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const result = await new LookupPerson().execute(c.req.valid('query') as PersonLookupQuery, user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,24 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { PersonLookupQuery, PersonSummary, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { findPersonSummaryByPhone } from '../../lib/people';
type LookupPersonDeps = {
db?: Pick<PrismaClient, 'group' | 'person'>;
};
/* While the teacher types a phone in the add form: is it someone they already
have? `null` when not. */
export class LookupPerson {
constructor(private readonly deps: LookupPersonDeps = {}) {}
async execute(query: PersonLookupQuery, userId: string): Promise<Result<PersonSummary | null, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const access = await findGroupForUser(db, query.groupId, userId);
if (!access.ok) return access;
return ok(await findPersonSummaryByPhone(db, access.value.createdById, query.phone));
}
}

View File

@@ -0,0 +1 @@
export { default as peopleRoutes } from './routes';

View File

@@ -0,0 +1,142 @@
import { Prisma, type PrismaClient } from '@generated/prisma/client';
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
import { conflictProblem } from '@/http/problem-builders';
import { normalizePhone } from '@/modules/attendees/lib/helpers';
/* A person is the teacher's contact (student, or a guardian's child); their
`attendees` are the memberships in each group. The phone is unique per
teacher (partial index `people_owner_phone_key`), so it is how a new row is
recognized as someone the teacher already has. */
export type PeopleDb = Pick<PrismaClient, 'person'>;
/* Phones are stored normalized, but older rows may keep what was typed. */
export function phoneVariants(rawPhone: string): string[] {
const normalized = normalizePhone(rawPhone);
const trimmed = rawPhone.trim();
return normalized === trimmed ? [normalized] : [normalized, trimmed];
}
export const personMembershipsSelect = {
attendees: {
orderBy: { createdAt: 'asc' },
select: { id: true, groupId: true, status: true, group: { select: { name: true } } },
},
} as const;
type MembershipRow = {
id: string;
groupId: string;
status: PersonMembership['status'];
group: { name: string };
};
export function toMemberships(rows: MembershipRow[]): PersonMembership[] {
return rows.map((row) => ({
attendeeId: row.id,
groupId: row.groupId,
groupName: row.group.name,
status: row.status,
}));
}
export async function findPersonByPhone(db: PeopleDb, ownerId: string, rawPhone: string) {
return db.person.findFirst({
where: { createdById: ownerId, phone: { in: phoneVariants(rawPhone) } },
select: {
id: true,
fullName: true,
email: true,
phone: true,
...personMembershipsSelect,
},
});
}
export async function findPersonSummaryByPhone(
db: PeopleDb,
ownerId: string,
rawPhone: string,
): Promise<PersonSummary | null> {
const person = await findPersonByPhone(db, ownerId, rawPhone);
if (!person) return null;
return {
id: person.id,
fullName: person.fullName,
email: person.email,
phone: person.phone,
groups: toMemberships(person.attendees),
};
}
export type NewPersonData = {
fullName: string;
phone: string | null;
email?: string | null;
notes?: string | null;
};
/* Waitlist promotion, pre-registration approval and bulk import: the row has
its own contact data, and if that phone is already one of the teacher's
people the membership goes to that person (their data wins). */
export async function findOrCreatePerson(
db: PeopleDb,
ownerId: string,
data: NewPersonData,
): Promise<{ id: string; created: boolean }> {
if (data.phone) {
const existing = await findPersonByPhone(db, ownerId, data.phone);
if (existing) return { id: existing.id, created: false };
}
const person = await db.person.create({
data: {
createdById: ownerId,
fullName: data.fullName,
phone: data.phone,
email: data.email ?? null,
notes: data.notes ?? null,
},
select: { id: true },
});
return { id: person.id, created: true };
}
/* Whether adding someone with this phone takes a new student slot of the plan:
no when they are already an active member of another group. */
export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone: string | null): Promise<boolean> {
if (!rawPhone) return true;
const person = await findPersonByPhone(db, ownerId, rawPhone);
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
}
/* The number the teacher reaches the person on: theirs, or the guardian's. */
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null {
return person.phone ?? person.guardianPhone;
}
export function isUniqueViolation(error: unknown): boolean {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
}
export function alreadyInGroupProblem(): ProblemDetails {
return conflictProblem({
detail: 'Esta persona ya es miembro de este grupo.',
code: 'attendee_already_registered',
});
}
/* The phone belongs to someone the teacher already has: the web offers to add
that person (`personId`) instead of creating a duplicate. */
export function personExistsProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ya tenés registrada a una persona con este número de teléfono.',
code: 'person_exists',
});
}
export function personPhoneTakenProblem(): ProblemDetails {
return conflictProblem({
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
code: 'person_phone_taken',
});
}

View File

@@ -0,0 +1,8 @@
import { Hono } from 'hono';
import lookupRoute from './features/lookup/route';
const routes = new Hono();
routes.route('/', lookupRoute);
export default routes;

View File

@@ -7,7 +7,7 @@ import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { computeStudentAccess } from '../../lib/status';
type GetStudentAccessDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
now?: Date;
};
@@ -23,9 +23,9 @@ export class GetStudentAccess {
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 } });
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date()));
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
}
}

View File

@@ -4,11 +4,12 @@ import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { contactPhone } from '@/modules/people/lib/people';
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
import { computeStudentAccess } from '../../lib/status';
type InviteStudentDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
now?: Date;
};
@@ -36,9 +37,8 @@ export class InviteStudent {
where: { id: attendeeId, groupId },
select: {
id: true,
fullName: true,
phone: true,
guardianPhone: true,
personId: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } },
group: { select: { owner: { select: { country: true } } } },
},
});
@@ -49,8 +49,9 @@ export class InviteStudent {
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 },
// One account per person: inviting from any of their groups reuses it.
const link = await tx.studentAccountPerson.findFirst({
where: { personId: attendee.personId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
@@ -58,7 +59,11 @@ export class InviteStudent {
link?.accountId
?? (
await tx.studentAccount.create({
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
data: {
name: attendee.person.fullName,
createdById: userId,
people: { create: { personId: attendee.personId } },
},
select: { id: true },
})
).id;
@@ -90,8 +95,8 @@ export class InviteStudent {
return ok({
url: studentLinkUrl(token),
expiresAt: expiresAt.toISOString(),
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
access: await computeStudentAccess(db, attendeeId, now),
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
access: await computeStudentAccess(db, attendee.personId, now),
});
}
}

View File

@@ -39,7 +39,7 @@ export class ListGroupAbsenceNotices {
reason: true,
message: true,
createdAt: true,
attendee: { select: { id: true, fullName: true } },
attendee: { select: { id: true, person: { select: { fullName: true } } } },
classSession: { select: { startsAt: true } },
},
});
@@ -47,7 +47,7 @@ export class ListGroupAbsenceNotices {
return ok({
data: notices.map((notice) => ({
id: notice.id,
attendee: notice.attendee,
attendee: { id: notice.attendee.id, fullName: notice.attendee.person.fullName },
startsAt: notice.classSession.startsAt.toISOString(),
reason: notice.reason ? REASON[notice.reason] : null,
message: notice.message,

View File

@@ -1,17 +1,18 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { StudentAccessDto } from '@gruperly/shared';
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>;
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountPerson'>;
/* Passive state for the attendee's card: active (a live session) > invited
(a pending invitation) > expired (invited before, nothing alive) > not invited. */
(a pending invitation) > expired (invited before, nothing alive) > not invited.
It is the person's access, so every group of theirs shows the same state. */
export async function computeStudentAccess(
db: StudentAccessStatusDb,
attendeeId: string,
personId: string,
now: Date,
): Promise<StudentAccessDto> {
const link = await db.studentAccountAttendee.findFirst({
where: { attendeeId },
const link = await db.studentAccountPerson.findFirst({
where: { personId },
orderBy: { createdAt: 'asc' },
select: {
account: {

View File

@@ -127,7 +127,7 @@ export class CancelStudentAbsence {
where: {
id: noticeId,
cancelledAt: null,
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
},
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
});

View File

@@ -17,7 +17,7 @@ route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), a
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
});
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
// multipart/form-data: attendeeId, paymentIds (repeated), file and an optional note.
route.post('/payment-reports', studentSession, async (c) => {
const { accountId } = currentStudent(c);
// Reject oversized bodies before buffering them (10 MB + room for the fields).
@@ -35,6 +35,7 @@ route.post('/payment-reports', studentSession, async (c) => {
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');
const note = form.get('note');
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
}
@@ -42,6 +43,7 @@ route.post('/payment-reports', studentSession, async (c) => {
const result = await new ReportStudentPayment().execute(accountId, {
attendeeId,
paymentIds,
note: typeof note === 'string' ? note : null,
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
});
return resultJson(c, result, { status: 201 });

View File

@@ -54,6 +54,7 @@ export class GetStudentFees {
status: true,
createdAt: true,
reviewedAt: true,
note: true,
rejectionReason: true,
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
},
@@ -85,6 +86,7 @@ export class GetStudentFees {
status: REPORT_STATUS[report.status],
createdAt: report.createdAt.toISOString(),
reviewedAt: report.reviewedAt?.toISOString() ?? null,
note: report.note,
rejectionReason: report.rejectionReason,
fees: report.items.map(({ payment }) => ({
id: payment.id,

View File

@@ -32,10 +32,20 @@ export class GetStudentLinkInfo {
account: {
select: {
name: true,
people: {
orderBy: { createdAt: 'asc' },
take: 1,
select: {
person: {
select: {
attendees: {
orderBy: { createdAt: 'asc' },
take: 1,
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
},
},
},
},
},
},
},
@@ -52,7 +62,7 @@ export class GetStudentLinkInfo {
return ok({ status: 'invalid' });
}
const group = row.account.attendees[0]?.attendee.group ?? null;
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
return ok({
status: 'valid',
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',

View File

@@ -20,20 +20,26 @@ export class GetStudentMe {
pendingRecoveryEmail: true,
welcomedAt: true,
_count: { select: { passkeys: true } },
attendees: {
where: { attendee: { status: { not: 'DROPPED' } } },
// Linked people, and every group each of them is in.
people: {
orderBy: { createdAt: 'asc' },
select: {
attendee: {
person: {
select: {
fullName: true,
attendees: {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
fullName: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
},
},
},
},
},
});
if (!account) return err(unauthorizedProblem('/student-portal/me'));
@@ -46,13 +52,15 @@ export class GetStudentMe {
hasPasskey: account._count.passkeys > 0,
welcomed: account.welcomedAt !== null,
},
students: account.attendees.map(({ attendee }) => ({
students: account.people.flatMap(({ person }) =>
person.attendees.map((attendee) => ({
attendeeId: attendee.id,
fullName: attendee.fullName,
fullName: person.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
})),
),
});
}
}

View File

@@ -1,7 +1,7 @@
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 { err, ok, REPORTED_PAYMENT_NOTE_MAX } 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';
@@ -19,6 +19,7 @@ type ReportPaymentDeps = {
export type ReportPaymentInput = {
attendeeId: string;
paymentIds: string[];
note?: string | null;
file: { name: string; bytes: Uint8Array };
};
@@ -37,6 +38,11 @@ export class ReportStudentPayment {
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem());
const note = input.note?.trim() || null;
if (note && note.length > REPORTED_PAYMENT_NOTE_MAX) {
return err(validationProblem({ detail: `La nota puede tener hasta ${REPORTED_PAYMENT_NOTE_MAX} caracteres.`, errors: { note: ['too_long'] } }));
}
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'] } }));
}
@@ -83,6 +89,7 @@ export class ReportStudentPayment {
receiptMime: mime,
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
receiptSize: input.file.bytes.length,
note,
createdAt: now,
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
},

View File

@@ -75,7 +75,7 @@ export class SetRecoveryEmail {
await sender.sendStudentEmailConfirmation({
email,
name: account.name,
url: `${webUrl()}/acceso/mail/${token}`,
url: `${webUrl()}/access/email/${token}`,
});
} catch (error) {
logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent');

View File

@@ -1,36 +1,21 @@
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. */
/* The authorization rule of every student endpoint: an attendee (membership)
of a person linked to the session's account, with what the student screens
need from the group. The account is linked to the person, so every group
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
access): 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 } },
person: { studentAccounts: { some: { accountId } } },
},
select: {
id: true,
fullName: true,
groupId: true,
group: {
select: {

View File

@@ -1,6 +1,7 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { contactPhone } from '@/modules/people/lib/people';
import {
addTotals,
type DispatchItem,
@@ -69,7 +70,9 @@ export class SendPaymentReminders {
currency: true,
dueDate: true,
checkoutUrl: true,
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
attendee: {
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
},
},
orderBy: { dueDate: 'asc' },
});
@@ -82,10 +85,10 @@ export class SendPaymentReminders {
groupId: group.id,
attendeeId: payment.attendee.id,
paymentId: payment.id,
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
rawPhone: contactPhone(payment.attendee.person),
message: {
kind: 'PAYMENT_REMINDER',
studentName: payment.attendee.fullName,
studentName: payment.attendee.person.fullName,
groupName: group.name,
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
dueDate: formatDueDate(payment.dueDate, country),

View File

@@ -5,6 +5,7 @@ import {
findStudentsAtRisk,
type StudentsAtRiskDb,
} from '@/modules/analytics/features/get-students-at-risk/use-case';
import { contactPhone } from '@/modules/people/lib/people';
import {
addTotals,
type DispatchItem,
@@ -69,11 +70,11 @@ export class SendReengagementMessages {
}),
db.attendee.findMany({
where: { id: { in: ids } },
select: { id: true, phone: true, guardianPhone: true },
select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
}),
]);
const coolingDown = new Set(recent.map((row) => row.attendeeId));
const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone]));
const phones = new Map(contacts.map((row) => [row.id, contactPhone(row.person)]));
for (const student of atRisk) {
if (coolingDown.has(student.attendeeId)) continue;

View File

@@ -0,0 +1,175 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
count: mock(),
create: mock(),
update: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const group = (overrides: Record<string, unknown> = {}) => ({
id: 'group-1',
name: 'Taller de Pintura',
createdById: teacherId,
capacity: 20,
...overrides,
});
const targetGroup = (overrides: Record<string, unknown> = {}) =>
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
const person = {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
};
const membership = (overrides: Record<string, unknown> = {}) => ({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
person,
notifyToken: 'notify-2',
status: 'ACTIVE',
createdAt: new Date('2026-11-02T10:00:00.000Z'),
updatedAt: new Date('2026-11-02T10:00:00.000Z'),
...overrides,
});
function addRequest(targetGroupId: string, userId = teacherId) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', { id: userId } as never);
await next();
});
app.route('/groups', groupsRoutes);
return app.request('/groups/group-1/attendees/att-1/add-to-group', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
}
describe('POST /groups/:groupId/attendees/:attendeeId/add-to-group', () => {
beforeEach(() => {
vi.clearAllMocks();
prisma.group.findUnique.mockReset();
prisma.attendee.findFirst.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.count.mockResolvedValue(3);
});
it('creates a membership of the same person in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
prisma.attendee.create.mockResolvedValue(membership() as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
fullName: 'Martín Gómez',
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
// The source membership is not touched.
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('reactivates a former (DROPPED) membership in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-old', status: 'DROPPED' } as never);
prisma.attendee.update.mockResolvedValue(membership({ id: 'att-old' }) as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-old' },
data: { status: 'ACTIVE' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the person is already in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-2', status: 'PAUSED' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ capacity: 3 }) as never);
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('group_capacity_reached');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects adding to the same group', async () => {
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-1');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_same_group');
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
});

View File

@@ -38,12 +38,21 @@ function makeGroup(overrides: Record<string, unknown> = {}) {
const attendee = {
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
// Every membership of the person: this one and another group.
attendees: [
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
{ id: 'a-2', groupId: 'group-2', status: 'PAUSED', group: { name: 'Yoga' } },
],
},
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -67,6 +76,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
expect(await res.json()).toEqual({
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
@@ -77,10 +87,12 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z',
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
});
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
where: { id: 'a-1', groupId: 'group-1' },
include: {
person: { select: expect.objectContaining({ fullName: true, attendees: expect.any(Object) }) },
payments: {
where: {
status: { not: 'CANCELLED' },

View File

@@ -0,0 +1,220 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
count: mock(),
update: mock(),
},
absenceNotice: {
updateMany: mock(),
},
attendance: {
deleteMany: mock(),
},
slotRelease: {
deleteMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const group = (overrides: Record<string, unknown> = {}) => ({
id: 'group-1',
name: 'Taller de Pintura',
description: null,
createdById: teacherId,
inviteToken: null,
createdAt: new Date('2026-09-01T10:00:00.000Z'),
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
days: ['MONDAY'],
time: '18:00',
capacity: 20,
price: 1500,
billingType: 'MONTHLY',
dueDay: 10,
...overrides,
});
const targetGroup = (overrides: Record<string, unknown> = {}) =>
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: 'notify-1',
status: 'ACTIVE',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
function moveRequest(targetGroupId: string, userId = teacherId, attendeeId = 'att-1') {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', { id: userId } as never);
await next();
});
app.route('/groups', groupsRoutes);
return app.request(`/groups/group-1/attendees/${attendeeId}/move`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
}
describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
beforeEach(() => {
vi.clearAllMocks();
prisma.group.findUnique.mockReset();
});
it('moves the member to the target group and undoes the old group future bookings', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.findFirst.mockResolvedValueOnce(attendee() as never).mockResolvedValueOnce(null);
prisma.attendee.count.mockResolvedValue(3);
prisma.attendee.update.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
const res = await moveRequest('group-2');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.groupId).toBe('group-2');
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-1' },
data: { groupId: 'group-2' },
include: { person: { select: expect.any(Object) } },
});
const futureOldClasses = {
classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } },
};
expect(prisma.absenceNotice.updateMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', cancelledAt: null, ...futureOldClasses },
data: { cancelledAt: expect.any(Date) },
});
expect(prisma.attendance.deleteMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', ...futureOldClasses },
});
expect(prisma.slotRelease.deleteMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', isClaimed: false, ...futureOldClasses },
});
});
it('rejects moving to the same group', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-1');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_same_group');
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 404 when the target group does not exist', async () => {
prisma.group.findUnique.mockResolvedValueOnce(group() as never).mockResolvedValueOnce(null);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-missing');
expect(res.status).toBe(404);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ capacity: 5 }) as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
prisma.attendee.count.mockResolvedValue(5);
const res = await moveRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('group_capacity_reached');
expect(prisma.attendee.update).not.toHaveBeenCalled();
expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled();
});
it('rejects with 409 when the person is already a member of the target group', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.findFirst
.mockResolvedValueOnce(attendee() as never)
.mockResolvedValueOnce({ id: 'att-existing' } as never);
prisma.attendee.count.mockResolvedValue(3);
const res = await moveRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.findFirst).toHaveBeenLastCalledWith({
where: { groupId: 'group-2', personId: 'person-1' },
select: { id: true },
});
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 404 when the member is not in the group', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
prisma.attendee.findFirst.mockResolvedValue(null);
const res = await moveRequest('group-2', teacherId, 'att-missing');
expect(res.status).toBe(404);
});
it('rejects a non-owner user', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
const res = await moveRequest('group-2', 'other-user');
expect(res.status).toBe(403);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 400 without a target group', async () => {
const res = await moveRequest('');
expect(res.status).toBe(400);
});
});

View File

@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
import { Prisma } from '@generated/prisma/client'
import { Hono } from 'hono'
const db = {
group: { findUnique: mock() },
attendee: { findFirst: mock(), update: mock() },
attendee: { findFirst: mock(), findUniqueOrThrow: mock() },
person: { update: mock() },
}
mock.module('@/lib/prisma', () => ({
@@ -15,15 +17,20 @@ mock.module('@/lib/prisma', () => ({
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
const userId = 'user-1'
const attendee = {
id: 'a-1',
groupId: 'group-1',
const person = {
id: 'person-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: 'Llega temprano',
}
const attendee = {
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
person,
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
@@ -51,11 +58,10 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
db.attendee.findFirst.mockResolvedValue(attendee)
})
it('actualiza contacto y conserva los campos vacíos como null', async () => {
db.attendee.update.mockResolvedValue({
it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue({
...attendee,
email: 'ana@example.com',
phone: null,
person: { ...person, email: 'ana@example.com' },
})
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
@@ -65,14 +71,49 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
})
expect(response.status).toBe(200)
expect(db.attendee.update).toHaveBeenCalledWith({
where: { id: 'a-1' },
expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' })
// The person's row: the change shows in every group they are in.
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { email: 'ana@example.com', phone: null },
})
})
it('normaliza el teléfono como el alta', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue(attendee)
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '11 2345-6789' }),
})
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { phone: '1123456789' },
})
})
it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => {
db.person.update.mockRejectedValueOnce(
new Prisma.PrismaClientKnownRequestError('Unique constraint failed', {
code: 'P2002',
clientVersion: 'test',
}),
)
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '1123456789' }),
})
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: 'person_phone_taken' })
})
it('actualiza una única nota', async () => {
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' })
db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } })
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
@@ -80,8 +121,8 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
body: JSON.stringify({ notes: 'Traer colchoneta' }),
})
expect(db.attendee.update).toHaveBeenCalledWith({
where: { id: 'a-1' },
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { notes: 'Traer colchoneta' },
})
})
@@ -94,6 +135,6 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
})
expect(response.status).toBe(400)
expect(db.attendee.update).not.toHaveBeenCalled()
expect(db.person.update).not.toHaveBeenCalled()
})
})

View File

@@ -15,6 +15,10 @@ const db = {
create: mock(),
count: mock(),
},
person: {
findFirst: mock(),
findMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -60,9 +64,34 @@ function makeApp(userValue: unknown) {
return app;
}
const personRow = (overrides: Record<string, unknown> = {}) => ({
id: 'person-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
...overrides,
});
const attendeeRow = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: personRow(),
notifyToken: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
describe('attendee incorporation & invite-token in groups', () => {
beforeEach(() => {
vi.clearAllMocks();
// Nobody with that phone among the teacher's people, unless a test says so.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.findMany.mockResolvedValue([]);
});
describe('GET /groups/:groupId/invite-token', () => {
@@ -109,18 +138,7 @@ describe('attendee incorporation & invite-token in groups', () => {
it('creates an attendee for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
@@ -140,20 +158,95 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(data.outcome).toBe('created');
expect(data.attendee.fullName).toBe('Martín Gómez');
expect(data.attendee.phone).toBe('+5491133445566');
expect(data.attendee.personId).toBe('person-1');
// A new person of the group owner, created with the membership.
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
group: { connect: { id: 'group-1' } },
person: {
create: {
createdById: teacherId,
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
},
},
},
include: { person: { select: expect.any(Object) } },
});
});
it('answers person_exists when the phone is already a person of another group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-9', groupId: 'group-9', status: 'ACTIVE', group: { name: 'Yoga' } }],
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'Martín', lastName: 'Gómez', phone: '+54 9 11 3344-5566' }),
});
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('person_exists');
expect(prisma.person.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { createdById: teacherId, phone: { in: ['+5491133445566', '+54 9 11 3344-5566'] } },
}),
);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('adds an existing person (personId) to the group without a new plan slot', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({ id: 'person-1', fullName: 'Martín Gómez' } as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(1);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-1' }),
});
expect(res.status).toBe(201);
expect(prisma.person.findFirst).toHaveBeenCalledWith({
where: { id: 'person-1', createdById: teacherId },
select: { id: true, fullName: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
include: { person: { select: expect.any(Object) } },
});
});
it('returns 404 for a personId of another teacher', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue(null);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-other' }),
});
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects duplicate phone number in individual add', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
@@ -197,18 +290,7 @@ describe('attendee incorporation & invite-token in groups', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20);
prisma.attendee.create.mockResolvedValue({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
@@ -412,16 +494,19 @@ describe('attendee incorporation & invite-token in groups', () => {
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
// Simulate that an attendee with phone '11111111' already exists
prisma.attendee.findMany.mockResolvedValue([
{ phone: '11111111' },
// The teacher's people: '11111111' is already in this group, '44444444'
// is in another group only (and active there).
prisma.person.findMany.mockResolvedValue([
{ id: 'person-in-group', phone: '11111111', attendees: [{ groupId: 'group-1', status: 'ACTIVE' }] },
{ id: 'person-elsewhere', phone: '44444444', attendees: [{ groupId: 'group-9', status: 'ACTIVE' }] },
] as never);
prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({
id: `att-${Math.random()}`,
...data,
guardianName: null,
guardianPhone: null,
groupId: 'group-1',
personId: data.personId ?? 'person-new',
notifyToken: null,
person: personRow({ fullName: data.person?.create?.fullName ?? 'Existente' }),
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
}));
@@ -434,19 +519,27 @@ describe('attendee incorporation & invite-token in groups', () => {
attendees: [
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the group
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
{ firstName: 'Otra', lastName: 'Persona', phone: '44444444' }, // In another group: linked
],
}),
});
expect(res.status).toBe(201);
const data = await res.json();
expect(data.totalProcessed).toBe(4);
expect(data.createdCount).toBe(2);
expect(data.totalProcessed).toBe(5);
expect(data.createdCount).toBe(3);
expect(data.linkedCount).toBe(1);
expect(data.duplicatesCount).toBe(2);
expect(data.message).toBe('2 alumnos agregados con éxito, 2 duplicados omitidos.');
expect(prisma.attendee.create).toHaveBeenCalledTimes(2);
expect(data.message).toBe(
'3 alumnos agregados con éxito (1 ya estaban en otros de tus grupos), 2 duplicados omitidos.',
);
expect(prisma.attendee.create).toHaveBeenCalledTimes(3);
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-elsewhere' },
include: { person: { select: expect.any(Object) } },
});
});
});
@@ -456,12 +549,8 @@ describe('attendee incorporation & invite-token in groups', () => {
{
id: 'att-1',
groupId: 'group-1',
fullName: 'Ana García',
email: null,
phone: '22222222',
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: personRow({ fullName: 'Ana García', phone: '22222222', email: null, notes: null }),
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
attendances: [],
@@ -487,6 +576,7 @@ describe('attendee incorporation & invite-token in groups', () => {
// The row summary is requested in the same query: one request per
// member would be N+1 over a listing of up to 100.
include: {
person: { select: expect.any(Object) },
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -11,12 +11,16 @@ function record(
return {
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -89,10 +93,12 @@ describe('toAttendeeListItemDto', () => {
});
it('conserva los campos del DTO plano', () => {
const dto = toAttendeeListItemDto(record({ phone: '22222222' }));
const base = record();
const dto = toAttendeeListItemDto(record({ person: { ...base.person, phone: '22222222' } }));
expect(dto.fullName).toBe('Ana Pérez');
expect(dto.phone).toBe('22222222');
expect(dto.personId).toBe('person-1');
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
});
});

View File

@@ -19,15 +19,30 @@ import { attendeesRoutes } from '@/modules/attendees';
const app = new Hono();
app.route('/attendees', attendeesRoutes);
const attendeeRow = {
id: 'attendee-1',
groupId: 'group-1',
const personSelect = {
id: true,
fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
};
const person = {
id: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: null,
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
};
const attendeeRow = {
id: 'attendee-1',
groupId: 'group-1',
personId: 'person-1',
notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -36,6 +51,7 @@ const attendeeRow = {
// What the Prisma mock returns: the row plus the summary relations.
const attendee = {
...attendeeRow,
person,
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
};
@@ -56,6 +72,12 @@ describe('attendees routes', () => {
data: [
{
...attendeeRow,
fullName: person.fullName,
email: person.email,
phone: person.phone,
guardianName: person.guardianName,
guardianPhone: person.guardianPhone,
notes: person.notes,
createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(),
// The query comes most recent first; the row shows them
@@ -71,6 +93,7 @@ describe('attendees routes', () => {
take: 10,
orderBy: { createdAt: 'desc' },
include: {
person: { select: personSelect },
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -12,7 +12,8 @@ function makeDb(params: {
return {
billingSubscription: { findUnique: mock(async () => params.subscription ?? null) },
group: { count: mock(async () => params.groups ?? 0) },
attendee: { count: mock(async () => params.attendees ?? 0) },
// People with an active membership: someone in two groups counts once.
person: { count: mock(async () => params.attendees ?? 0) },
};
}

View File

@@ -29,7 +29,14 @@ describe('plan guards in the use cases', () => {
it('checks a bulk import against the group owner, with the number of new attendees', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() },
attendee: { create: mock() },
// '1111' is already in this group; '4444' is active in another group.
person: {
findMany: mock(async () => [
{ id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] },
{ id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] },
]),
},
};
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
@@ -38,9 +45,11 @@ describe('plan guards in the use cases', () => {
{ fullName: 'Ana', phone: '2222' },
{ fullName: 'Beto', phone: '3333' },
{ fullName: 'Repetido', phone: '1111' },
{ fullName: 'De otro grupo', phone: '4444' },
],
} as never);
// Only the two new people: the one already active elsewhere takes no slot.
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
expect(result.ok).toBe(false);
expect(db.attendee.create).not.toHaveBeenCalled();

View File

@@ -159,8 +159,8 @@ describe('classes routes', () => {
it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => {
prisma.classSession.findUnique.mockResolvedValue(makeSession());
prisma.attendee.findMany.mockResolvedValue([
{ id: 'attendee-1', fullName: 'Ana Pérez' },
{ id: 'attendee-2', fullName: 'Bruno Díaz' },
{ id: 'attendee-1', person: { fullName: 'Ana Pérez' } },
{ id: 'attendee-2', person: { fullName: 'Bruno Díaz' } },
]);
prisma.payment.findMany.mockResolvedValue([
{ attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') },
@@ -443,7 +443,7 @@ describe('classes routes', () => {
prisma.attendee.findUnique.mockResolvedValue({
id: 'attendee-1',
fullName: 'Ana Pérez',
person: { fullName: 'Ana Pérez' },
group: {
id: 'group-1',
name: 'Funcional',

View File

@@ -63,7 +63,10 @@ describe.skipIf(!url)('payment review (real database)', () => {
],
});
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.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } });
await db.attendee.create({
data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, createdAt: new Date('2026-01-01T00:00:00Z') },
});
await db.studentAccount.create({
data: {
id: ids.account,
@@ -71,7 +74,7 @@ describe.skipIf(!url)('payment review (real database)', () => {
createdById: ids.teacher,
recoveryEmail: 'ana@test.local',
recoveryEmailVerifiedAt: NOW,
attendees: { create: { attendeeId: ids.ana } },
people: { create: { personId: `${ids.ana}-person` } },
},
});
await db.payment.create({

View File

@@ -19,7 +19,14 @@ describe.skipIf(!url)('student access (real database)', () => {
// 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}` };
const ids = {
user: `test-user-${suffix}`,
group: `test-group-${suffix}`,
group2: `test-group2-${suffix}`,
person: `test-person-${suffix}`,
attendee: `test-att-${suffix}`,
attendee2: `test-att2-${suffix}`,
};
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
@@ -42,7 +49,11 @@ describe.skipIf(!url)('student access (real database)', () => {
};
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' } });
await db.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } });
// One person in two groups of the teacher.
await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } });
await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } });
});
afterAll(async () => {
@@ -96,7 +107,7 @@ describe.skipIf(!url)('student access (real database)', () => {
if (!loser.ok) expect(loser.error.status).toBe(410);
}
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
expect(sessions).toHaveLength(1);
expect(sessions[0]?.device).toBe('iPhone · Safari');
@@ -122,7 +133,7 @@ describe.skipIf(!url)('student access (real database)', () => {
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 } });
const linked = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
await db.studentPasskey.create({
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
});
@@ -141,9 +152,25 @@ describe.skipIf(!url)('student access (real database)', () => {
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 } });
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
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' } });
});
it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => {
const fromFirst = await invite();
if (!fromFirst.ok) throw new Error('invite failed');
const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(
ids.group2,
ids.attendee2,
ids.user,
);
if (!fromSecond.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1);
// Same state from both groups: it is the person's access.
const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user);
expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } });
});
});

View File

@@ -8,6 +8,7 @@ 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 { GetStudentMe } from '@/modules/student-portal/features/me/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;
@@ -30,7 +31,12 @@ describe.skipIf(!url)('student portal (real database)', () => {
const ids = {
user: `t-user-${suffix}`,
group: `t-group-${suffix}`,
yoga: `t-yoga-${suffix}`,
personAna: `t-p-ana-${suffix}`,
personBeto: `t-p-beto-${suffix}`,
ana: `t-ana-${suffix}`,
anaYoga: `t-ana-yoga-${suffix}`,
betoYoga: `t-beto-yoga-${suffix}`,
beto: `t-beto-${suffix}`,
accountAna: `t-acc-ana-${suffix}`,
accountBeto: `t-acc-beto-${suffix}`,
@@ -50,17 +56,29 @@ describe.skipIf(!url)('student portal (real database)', () => {
await db.group.create({
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
});
await db.group.create({
data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' },
});
await db.person.createMany({
data: [
{ id: ids.personAna, createdById: ids.user, fullName: 'Ana' },
{ id: ids.personBeto, createdById: ids.user, fullName: 'Beto' },
],
});
// Ana and Beto are in both groups.
await db.attendee.createMany({
data: [
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
{ id: ids.ana, groupId: ids.group, personId: ids.personAna },
{ id: ids.beto, groupId: ids.group, personId: ids.personBeto },
{ id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna },
{ id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto },
],
});
await db.studentAccount.create({
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } },
});
await db.studentAccount.create({
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } },
});
await db.payment.createMany({
data: [
@@ -117,6 +135,21 @@ describe.skipIf(!url)('student portal (real database)', () => {
expect(!invented.ok && invented.error.status).toBe(400);
});
it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => {
const me = await new GetStudentMe({ db }).execute(ids.accountAna);
if (!me.ok) throw new Error('me failed');
expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([
[ids.ana, 'Natación'],
[ids.anaYoga, 'Yoga'],
]);
// Her membership in the second group is reachable; Beto's in that group is not.
expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true);
const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga);
expect(foreign.ok).toBe(false);
if (!foreign.ok) expect(foreign.error.status).toBe(404);
});
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);

View File

@@ -61,7 +61,7 @@ describe('groups routes', () => {
it('lists groups scoped to the current user', async () => {
prisma.group.findMany.mockResolvedValue([
{ ...group, _count: { attendees: 4, waitlist: 1 } },
{ ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } },
]);
prisma.group.count.mockResolvedValue(1);
@@ -76,6 +76,7 @@ describe('groups routes', () => {
updatedAt: group.updatedAt.toISOString(),
attendeesCount: 4,
waitlistCount: 1,
unpaidPaymentsCount: 3,
},
],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
@@ -89,7 +90,11 @@ describe('groups routes', () => {
where,
include: {
_count: {
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
select: {
attendees: true,
waitlist: { where: { status: 'PENDING' } },
payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } },
},
},
},
});

View File

@@ -82,7 +82,7 @@ describe('GetHomeSummary', () => {
dueDate: new Date('2026-09-25T12:00:00.000Z'),
status: 'PENDING',
group: { name: 'Cuadrilla A' },
attendee: { fullName: 'Ana García' },
attendee: { person: { fullName: 'Ana García' } },
},
]);
@@ -130,7 +130,7 @@ describe('GetHomeSummary', () => {
where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: [{ dueDate: 'asc' }],
take: 5,
include: { group: { select: { name: true } }, attendee: { select: { fullName: true } } },
include: { group: { select: { name: true } }, attendee: { select: { person: { select: { fullName: true } } } } },
});
});

View File

@@ -81,8 +81,8 @@ describe('create payments batch', () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([
{ id: 'att-1', fullName: 'Juana' },
{ id: 'att-2', fullName: 'Pedro' },
{ id: 'att-1', person: { fullName: 'Juana' } },
{ id: 'att-2', person: { fullName: 'Pedro' } },
]);
prisma.payment.create
.mockResolvedValueOnce({ id: 'pay-1' })
@@ -142,14 +142,14 @@ describe('create payments batch', () => {
unitPrice: 120,
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`,
backUrl: `${webOrigin}/student/payments`,
});
});
it('derives the currency from the owner country and defaults when there is none', async () => {
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]);
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
const useCase = batchUseCase();
createPreference.mockResolvedValueOnce({
@@ -169,13 +169,14 @@ describe('create payments batch', () => {
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
include: { person: { select: { fullName: true } } },
});
});
it('propagates the not-connected problem and creates no rows', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
getToken = mock(async () => ({
ok: false,
error: {
@@ -203,7 +204,7 @@ describe('create payments batch', () => {
it('answers 409 over HTTP when the owner has no linked account', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {

View File

@@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
paidAt: null,
createdAt: new Date('2026-10-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
attendee: { fullName: 'Juana Pérez' },
attendee: { person: { fullName: 'Juana Pérez' } },
group: {
name: 'Vinyasa',
price: { toString: () => '120.00' },
@@ -101,13 +101,13 @@ describe('renew payment link', () => {
unitPrice: 120,
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`,
backUrl: `${webOrigin}/student/payments`,
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
include: {
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } },
},
});

View File

@@ -36,7 +36,7 @@ const payment = {
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
group: { name: 'Cuadrilla Alfa', price: 150.5 },
attendee: { fullName: 'Juana Pérez' },
attendee: { person: { fullName: 'Juana Pérez' } },
};
function makeApp(userValue: unknown) {
@@ -93,7 +93,7 @@ describe('payments routes', () => {
where: { groupId: { in: ['group-1'] } },
include: {
group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
skip: 0,
take: 10,

View File

@@ -10,6 +10,11 @@ const db = {
count: mock(),
create: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findFirst: mock(),
create: mock(),
@@ -69,12 +74,16 @@ const preRegistration = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: 'notify-1',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
@@ -107,6 +116,9 @@ function makeApp(userValue: unknown) {
describe('group pre-registrations', () => {
beforeEach(() => {
vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
});
describe('GET /groups/:groupId/preregistrations', () => {
@@ -183,14 +195,19 @@ describe('group pre-registrations', () => {
expect(body.outcome).toBe('added');
expect(body.attendee.fullName).toBe('Martín Gómez');
expect(body.waitlistEntry).toBeNull();
expect(prisma.attendee.create).toHaveBeenCalledWith({
expect(prisma.person.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
createdById: teacherId,
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
notes: null,
},
select: { id: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
where: { id: 'pre-1' },
@@ -255,6 +272,13 @@ describe('group pre-registrations', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await makeApp({ id: teacherId }).request(

View File

@@ -74,7 +74,7 @@ describe('link del alumno', () => {
expiresAt: new Date(NOW.getTime() + 1000),
account: {
name: 'Ana',
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
people: [{ person: { attendees: [{ group: { name: 'Natación', owner: { name: 'Caro' } } }] } }],
},
})),
updateMany: mock(),

View File

@@ -1,4 +1,5 @@
import { describe, expect, it } from 'bun:test';
import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
import type { FileStorage } from '@/lib/storage';
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
@@ -45,6 +46,15 @@ describe('tipo real del comprobante (magic bytes)', () => {
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);
const longNote = await useCase.execute('acc', {
attendeeId: 'a1',
paymentIds: ['p1'],
note: 'x'.repeat(REPORTED_PAYMENT_NOTE_MAX + 1),
file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) },
});
expect(!longNote.ok && longNote.error.errors).toEqual({ note: ['too_long'] });
expect(puts).toEqual([]);
});
});

View File

@@ -12,6 +12,11 @@ const db = {
create: mock(),
delete: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -70,12 +75,16 @@ const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
@@ -94,6 +103,9 @@ function makeApp(userValue: unknown) {
describe('group waitlist management', () => {
beforeEach(() => {
vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
});
describe('GET /groups/:groupId/waitlist', () => {
@@ -146,7 +158,12 @@ describe('group waitlist management', () => {
const data = await res.json();
expect(data.attendee.fullName).toBe('Martín Gómez');
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-1', fullName: 'Martín Gómez', phone: '+5491133445566' }),
data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ createdById: teacherId, fullName: 'Martín Gómez', phone: '+5491133445566' }),
select: { id: true },
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
@@ -167,10 +184,17 @@ describe('group waitlist management', () => {
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
it('rejects with 409 when the phone already belongs to an attendee', async () => {
it('rejects with 409 when the person is already a member of the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
@@ -204,6 +228,72 @@ describe('group waitlist management', () => {
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
const promoteTo = (targetGroupId: string) =>
makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
it('places the entry in another group of the teacher and removes it from the origin waitlist', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', name: 'Taller de Cerámica' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(200);
expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } });
expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', createdById: 'other-user' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
it('returns 404 when the target group does not exist', async () => {
prisma.group.findUnique.mockResolvedValueOnce(mockGroup as never).mockResolvedValueOnce(null);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-missing');
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', capacity: 5 } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
const res = await promoteTo('group-2');
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('group_capacity_reached');
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
});
describe('DELETE /groups/:groupId/waitlist/:entryId', () => {
@@ -260,6 +350,10 @@ describe('group waitlist management', () => {
expect(body.removedAttendeeId).toBe('att-1');
expect(body.promoted).toBeNull();
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
// Their last group: the person goes too (no-op if they are in others).
expect(prisma.person.deleteMany).toHaveBeenCalledWith({
where: { id: 'person-1', attendees: { none: {} } },
});
});
it('removes an attendee and promotes the first pending waitlist entry atomically', async () => {
@@ -288,8 +382,9 @@ describe('group waitlist management', () => {
expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' });
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }),
select: { id: true },
});
});

View File

@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`,
attendee: { phone: null, guardianPhone: null, ...attendee },
attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
...overrides,
};
}
@@ -282,11 +282,11 @@ describe('re-engagement messages', () => {
]);
db.attendee.findMany
.mockResolvedValueOnce([
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled },
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled },
{ id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled },
{ id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled },
])
.mockResolvedValueOnce([
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
{ id: 'att-1', person: { phone: '1123456789', guardianPhone: null } },
]);
db.attendance.findMany.mockResolvedValue([
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },

View File

@@ -12,7 +12,8 @@ export type SheetProps = {
}
/* Bottom sheet on mobile (anchored to the bottom edge, above the home
indicator) and a centered dialog from `sm` up. Escape and the backdrop close
indicator, sliding up unless reduced motion is on) and a centered dialog
from `sm` up. Escape and the backdrop close
it; focus moves into the panel on open and goes back where it was on close. */
export function Sheet({ isOpen, onClose, title, description, children, className }: SheetProps) {
const titleId = useId()
@@ -50,7 +51,7 @@ export function Sheet({ isOpen, onClose, title, description, children, className
ref={panelRef}
tabIndex={-1}
className={cn(
'relative max-h-[90dvh] w-full overflow-y-auto rounded-t-2xl border border-border bg-surface p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] shadow-2xl outline-none animate-fade-in sm:max-w-md sm:rounded-2xl sm:pb-5',
'relative max-h-[90dvh] w-full overflow-y-auto rounded-t-2xl border border-border bg-surface p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] shadow-2xl outline-none animate-sheet-up motion-reduce:animate-fade-in sm:animate-fade-in sm:max-w-md sm:rounded-2xl sm:pb-5',
className,
)}
>

View File

@@ -1,6 +1,6 @@
import { useEffect, useId, useRef, useState } from 'react'
import type { KeyboardEvent, RefObject } from 'react'
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus } from 'lucide-react'
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
import { useToast } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
@@ -15,7 +15,7 @@ export function AttendeeActionsMenu({
* when it closes. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { beginContactEdit, openRemoveDialog } = useAttendeeDetail()
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
const toast = useToast()
const [isOpen, setIsOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
@@ -69,12 +69,6 @@ export function AttendeeActionsMenu({
items[next]?.focus()
}
const showPendingChangeGroup = () => {
close()
// TODO(miembros): navegar al selector cuando se confirmen las reglas y exista el endpoint.
toast.info('Cambiar de grupo estará disponible cuando se confirme el flujo de traspaso.')
}
const showPendingPause = () => {
close()
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
@@ -110,11 +104,26 @@ export function AttendeeActionsMenu({
type="button"
role="menuitem"
className={ITEM_CLASS}
onClick={showPendingChangeGroup}
onClick={() => {
close()
openChangeGroupDialog()
}}
>
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Cambiar de grupo
</button>
<button
type="button"
role="menuitem"
className={ITEM_CLASS}
onClick={() => {
close()
openAddToGroupDialog()
}}
>
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Agregar a otro grupo
</button>
<button
type="button"
role="menuitem"

View File

@@ -6,6 +6,8 @@ type AttendeeContactFormProps = {
phone: string
email: string
error: string | null
/** Aviso cuando la persona está en otros grupos: el cambio aplica en todos. */
sharedNote?: string | null
isSaving: boolean
onPhoneChange: (value: string) => void
onEmailChange: (value: string) => void
@@ -17,6 +19,7 @@ export function AttendeeContactForm({
phone,
email,
error,
sharedNote,
isSaving,
onPhoneChange,
onEmailChange,
@@ -46,6 +49,7 @@ export function AttendeeContactForm({
aria-describedby={error ? 'contact-error' : undefined}
/>
</ContactInput>
{sharedNote ? <p className="text-xs text-secondary">{sharedNote}</p> : null}
{error ? (
<p id="contact-error" role="alert" className="text-sm text-danger-fg">
{error}

View File

@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { Mail, Phone } from 'lucide-react'
import { ApiError } from '../../lib/api'
import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils'
import { AttendeeContactForm } from './AttendeeContactForm'
@@ -43,8 +44,12 @@ export function AttendeeContactSection() {
try {
await saveAttendee({ phone, email })
endContactEdit()
} catch {
setError('No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.')
} catch (err) {
setError(
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
? 'Ese teléfono ya es de otra persona que tenés registrada.'
: 'No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.',
)
}
}
@@ -69,6 +74,11 @@ export function AttendeeContactSection() {
phone={phone}
email={email}
error={error}
sharedNote={
attendee.otherGroups.length > 0
? 'El cambio se aplica en todos sus grupos.'
: null
}
isSaving={isUpdatingAttendee}
onPhoneChange={(value) => {
setPhone(value)

View File

@@ -5,14 +5,20 @@ import { useNavigate } from '@tanstack/react-router'
import type {
AttendeeDetailDto,
AttendeeHistory,
GroupListItem,
GroupWaitlistEntryDto,
UpdateAttendee,
} from '@gruperly/shared'
import { useToast } from '../../components/ui'
import {
addAttendeeToGroup,
ApiError,
getAttendeeHistory,
getGroup,
getGroupAttendee,
getGroups,
getGroupWaitlist,
moveGroupAttendee,
updateGroupAttendee,
} from '../../lib/api'
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
@@ -39,8 +45,22 @@ type AttendeeDetailContextValue = {
closeRemoveDialog: () => void
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
isSubmittingRemoval: boolean
/** Qué diálogo de grupo está abierto: "Cambiar de grupo" o "Agregar a otro grupo". */
groupDialogMode: GroupDialogMode | null
openChangeGroupDialog: () => void
openAddToGroupDialog: () => void
closeGroupDialog: () => void
/** Grupos del profe (incluye el actual); se piden al abrir el diálogo. */
groups: GroupListItem[]
groupsPending: boolean
moveToGroup: (targetGroupId: string) => void
isMovingAttendee: boolean
addToGroup: (targetGroupId: string) => void
isAddingToGroup: boolean
}
export type GroupDialogMode = 'move' | 'add'
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
export function AttendeeDetailProvider({
@@ -54,7 +74,9 @@ export function AttendeeDetailProvider({
}) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const toast = useToast()
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
const [groupDialogMode, setGroupDialogMode] = useState<GroupDialogMode | null>(null)
const [isEditingContact, setIsEditingContact] = useState(false)
const groupQuery = useQuery({
@@ -76,7 +98,9 @@ export function AttendeeDetailProvider({
['group-attendee', groupId, attendeeId],
(current) => (current ? { ...current, ...updated } : current),
)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
// Los datos son de la persona: cambian también en sus otros grupos.
void queryClient.invalidateQueries({ queryKey: ['group-attendees'] })
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
},
})
@@ -108,6 +132,71 @@ export function AttendeeDetailProvider({
},
})
// Misma key que Grupos y Cobros: el diálogo reusa el caché si ya está.
const groupsQuery = useQuery({
queryKey: ['groups'],
queryFn: getGroups,
enabled: groupDialogMode !== null,
})
const groups = groupsQuery.data?.data ?? []
const moveMutation = useMutation({
mutationFn: (targetGroupId: string) => moveGroupAttendee(groupId, attendeeId, targetGroupId),
onSuccess: (moved, targetGroupId) => {
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${moved.fullName} pasó a ${targetName}.`)
for (const id of [groupId, targetGroupId]) {
void queryClient.invalidateQueries({ queryKey: ['group-attendees', id] })
void queryClient.invalidateQueries({ queryKey: ['group', id] })
}
void queryClient.invalidateQueries({ queryKey: ['groups'] })
void queryClient.invalidateQueries({ queryKey: ['attention'] })
setGroupDialogMode(null)
// La ficha vive bajo el grupo: pasa a la URL del grupo nuevo sin dejar la
// vieja en el historial (ya no existe).
void navigate({
to: '/groups/$groupId/attendees/$attendeeId',
params: { groupId: targetGroupId, attendeeId },
replace: true,
})
},
onError: (err: Error) => {
const code = err instanceof ApiError ? err.problem?.code : undefined
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
} else if (code === 'attendee_already_registered') {
toast.error('Esta persona ya es miembro de ese grupo.')
} else {
toast.error(err.message || 'No se pudo cambiar de grupo.')
}
},
})
const addToGroupMutation = useMutation({
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
onSuccess: (added, targetGroupId) => {
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${added.fullName} ahora también está en ${targetName}.`)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
// "También está en" de esta ficha (y la de sus otros grupos).
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
void queryClient.invalidateQueries({ queryKey: ['groups'] })
void queryClient.invalidateQueries({ queryKey: ['attention'] })
setGroupDialogMode(null)
},
onError: (err: Error) => {
const code = err instanceof ApiError ? err.problem?.code : undefined
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
} else if (code === 'attendee_already_registered') {
toast.error('Esta persona ya es miembro de ese grupo.')
} else {
toast.error(err.message || 'No se pudo agregar al grupo.')
}
},
})
const value: AttendeeDetailContextValue = {
groupId,
groupName: groupQuery.data?.name,
@@ -135,6 +224,16 @@ export function AttendeeDetailProvider({
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
},
isSubmittingRemoval: isRemovingAttendee,
groupDialogMode,
openChangeGroupDialog: () => setGroupDialogMode('move'),
openAddToGroupDialog: () => setGroupDialogMode('add'),
closeGroupDialog: () => setGroupDialogMode(null),
groups,
groupsPending: groupsQuery.isPending,
moveToGroup: (targetGroupId) => moveMutation.mutate(targetGroupId),
isMovingAttendee: moveMutation.isPending,
addToGroup: (targetGroupId) => addToGroupMutation.mutate(targetGroupId),
isAddingToGroup: addToGroupMutation.isPending,
}
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>

View File

@@ -10,7 +10,9 @@ import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection'
import { AttendeeNotesSection } from './AttendeeNotesSection'
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
import { OtherGroupsSection } from './OtherGroupsSection'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ChangeGroupDialog } from './ChangeGroupDialog'
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
import { formatMemberSince } from './attendance'
import { paymentPresentation } from './detail'
@@ -87,6 +89,7 @@ export function AttendeeDetailView() {
<div className="mt-6">
<AttendeeContactSection />
<OtherGroupsSection />
<StudentAccessSection />
<AttendeePaymentsSection />
<AttendeeAttendanceSection />
@@ -97,6 +100,7 @@ export function AttendeeDetailView() {
) : null}
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
<ChangeGroupDialog returnFocusRef={menuTriggerRef} />
</section>
)
}

View File

@@ -0,0 +1,182 @@
import { useEffect, useRef, useState } from 'react'
import type { RefObject } from 'react'
import type { GroupListItem } from '@gruperly/shared'
import type { LucideIcon } from 'lucide-react'
import { CalendarCheck, CalendarX, History, Loader2, MoveRight, UserPlus, Wallet } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
type Consequence = { key: string; icon: LucideIcon; text: string }
function isFull(group: GroupListItem): boolean {
return group.capacity != null && group.attendeesCount >= group.capacity
}
/* "Cambiar de grupo" (sale de este y entra al otro) y "Agregar a otro grupo"
(queda en los dos) comparten el selector de destino; cambian el texto, las
consecuencias y la acción. */
export function ChangeGroupDialog({
returnFocusRef,
}: {
/** The element focus returns to when it closes (the "⋯" button). */
returnFocusRef: RefObject<HTMLButtonElement | null>
}) {
const {
groupId,
attendee,
groupName,
groups,
groupsPending,
groupDialogMode,
closeGroupDialog,
moveToGroup,
isMovingAttendee,
addToGroup,
isAddingToGroup,
} = useAttendeeDetail()
const isOpen = groupDialogMode !== null
const isAdd = groupDialogMode === 'add'
const [targetGroupId, setTargetGroupId] = useState('')
const wasOpen = useRef(false)
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
useEffect(() => {
if (isOpen) {
wasOpen.current = true
setTargetGroupId('')
return
}
if (!wasOpen.current) return
wasOpen.current = false
returnFocusRef.current?.focus()
}, [isOpen, returnFocusRef])
if (!attendee) return null
// Fuera el grupo actual y los grupos donde ya está. Al agregar, una baja
// anterior (DROPPED) se puede reactivar; al mover, no (sería otra membresía).
const blocked = new Set(
attendee.otherGroups
.filter((membership) => !isAdd || membership.status !== 'DROPPED')
.map((membership) => membership.groupId),
)
const otherGroups = groups.filter((group) => group.id !== groupId && !blocked.has(group.id))
const currentName = groupName ?? 'el grupo actual'
const isSubmitting = isAdd ? isAddingToGroup : isMovingAttendee
const consequences: Consequence[] = isAdd
? [
{
key: 'sigue',
icon: CalendarCheck,
text: `Sigue en ${currentName}: va a estar en los dos grupos.`,
},
{
key: 'datos',
icon: History,
text: 'Comparte el contacto, las notas y el acceso a la app de alumnos.',
},
{
key: 'cuotas',
icon: Wallet,
text: 'La asistencia y las cuotas se llevan por separado en cada grupo.',
},
]
: [
{
key: 'historial',
icon: History,
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
},
{
key: 'cuotas',
icon: Wallet,
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
},
{
key: 'faltas',
icon: CalendarX,
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
},
]
return (
<Modal
isOpen={isOpen}
onClose={closeGroupDialog}
title={isAdd ? 'Agregar a otro grupo' : 'Cambiar de grupo'}
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
maxWidth="sm"
>
<div className="space-y-4">
{groupsPending ? (
<div className="flex justify-center py-4">
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label="Cargando grupos" />
</div>
) : otherGroups.length === 0 ? (
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
{groups.length > 1
? 'Ya es miembro de todos tus otros grupos.'
: `No tenés otros grupos. Creá uno para poder ${isAdd ? 'agregar' : 'mover'} a este miembro.`}
</p>
) : (
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">
{isAdd ? 'Agregar a' : 'Mover a'}
</span>
<select
autoFocus
value={targetGroupId}
onChange={(event) => setTargetGroupId(event.target.value)}
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
<option value="" disabled>
Elegí un grupo
</option>
{otherGroups.map((group) => {
const full = isFull(group)
return (
<option key={group.id} value={group.id} disabled={full}>
{group.name}
{full ? ' (sin cupo)' : ''}
</option>
)
})}
</select>
</label>
)}
<ul className="space-y-2.5">
{consequences.map(({ icon: Icon, key, text }) => (
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
<span>{text}</span>
</li>
))}
</ul>
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
<Button variant="ghost" onClick={closeGroupDialog}>
Cancelar
</Button>
<Button
variant="primary"
onClick={() => (isAdd ? addToGroup(targetGroupId) : moveToGroup(targetGroupId))}
disabled={!targetGroupId || isSubmitting}
className="gap-2"
>
{isSubmitting ? (
<Loader2 className="size-4 animate-spin" />
) : isAdd ? (
<UserPlus className="size-4" />
) : (
<MoveRight className="size-4" />
)}
<span>{isAdd ? 'Agregar' : 'Cambiar de grupo'}</span>
</Button>
</div>
</div>
</Modal>
)
}

View File

@@ -103,7 +103,7 @@ export function InviteToAppSheet({
}
>
<div className="space-y-4">
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary" aria-label="Vista previa del mensaje">
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary break-words" aria-label="Vista previa del mensaje">
{preview}
</div>

View File

@@ -0,0 +1,49 @@
import { Link } from '@tanstack/react-router'
import { ChevronRight, Users } from 'lucide-react'
import type { PersonMembership } from '@gruperly/shared'
import { Badge, type BadgeVariant } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
type StatusBadge = { label: string; variant: BadgeVariant }
const STATUS_BADGE: Record<PersonMembership['status'], StatusBadge | null> = {
ACTIVE: null,
PAUSED: { label: 'En pausa', variant: 'warning' },
DROPPED: { label: 'Dado de baja', variant: 'neutral' },
}
/* La misma persona en otros grupos del profe: cada fila abre su ficha en ese
grupo (asistencia y cuotas son de cada grupo; el contacto es compartido). */
export function OtherGroupsSection() {
const { attendee } = useAttendeeDetail()
if (!attendee || attendee.otherGroups.length === 0) return null
return (
<Section title="También está en">
<ul className="divide-y divide-border/60">
{attendee.otherGroups.map((membership) => {
const badge = STATUS_BADGE[membership.status]
return (
<li key={membership.attendeeId}>
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId: membership.groupId, attendeeId: membership.attendeeId }}
className="flex min-h-14 items-center gap-3 rounded-lg px-3 py-2 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Users className="size-4 shrink-0 text-secondary" aria-hidden="true" />
<span className="min-w-0 flex-1 truncate text-sm text-primary">{membership.groupName}</span>
{badge ? (
<Badge variant={badge.variant} className="text-[11px]">
{badge.label}
</Badge>
) : null}
<ChevronRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
</Link>
</li>
)
})}
</ul>
</Section>
)
}

View File

@@ -123,6 +123,9 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
toast.info(result.message)
}
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
// Si era alguien de otro grupo, su ficha allá ahora lo muestra también acá.
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
void queryClient.invalidateQueries({ queryKey: ['person-lookup'] })
goBackToGroup()
}
@@ -135,6 +138,13 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
setIsCapacityModalOpen(true)
return
}
// El aviso del formulario no llegó a mostrarse (o alguien la cargó recién):
// refresca la búsqueda para que aparezca la opción de agregar a esa persona.
if (err instanceof ApiError && err.problem?.code === 'person_exists') {
void queryClient.invalidateQueries({ queryKey: ['person-lookup', groupId] })
toast.info('Ya tenés registrada a una persona con este teléfono. Podés agregarla a este grupo.')
return
}
toast.error(err.message || 'Error al agregar miembro.')
},
})

View File

@@ -0,0 +1,71 @@
import { UserCheck } from 'lucide-react'
import type { PersonSummary } from '@gruperly/shared'
import { Button } from '../../../components/ui'
type ExistingPersonNoticeProps = {
person: PersonSummary
/** La persona ya es miembro (no dado de baja) del grupo al que se está agregando. */
alreadyInGroup: boolean
isLinked: boolean
onLink: () => void
onUnlink: () => void
onChangePhone: () => void
}
/* El teléfono ya es de alguien que el profe tiene en otro grupo: en vez de
crear un duplicado, ofrece sumar a esa misma persona. */
export function ExistingPersonNotice({
person,
alreadyInGroup,
isLinked,
onLink,
onUnlink,
onChangePhone,
}: ExistingPersonNoticeProps) {
const groupNames = person.groups.map((group) => group.groupName).join(', ')
if (alreadyInGroup) {
return (
<div role="alert" className="mt-2 rounded-xl bg-danger-soft px-3 py-2.5 text-sm text-danger-fg">
{person.fullName} ya es miembro de este grupo.
</div>
)
}
return (
<div role="status" className="mt-2 rounded-xl border border-border bg-accent-soft/40 px-3 py-3 text-sm text-primary">
<div className="flex items-start gap-2.5">
<UserCheck className="mt-0.5 size-4 shrink-0 text-accent-fg" aria-hidden="true" />
<p className="min-w-0">
{isLinked ? (
<>
Vas a agregar a <strong>{person.fullName}</strong> a este grupo. Sus datos de contacto
y notas son los mismos que en sus otros grupos.
</>
) : (
<>
Ya tenés a <strong>{person.fullName}</strong> con este teléfono
{groupNames ? ` (en ${groupNames})` : ''}. ¿Es la misma persona?
</>
)}
</p>
</div>
<div className="mt-2.5 flex flex-wrap justify-end gap-2">
{isLinked ? (
<Button variant="ghost" onClick={onUnlink} size="sm">
No es esta persona
</Button>
) : (
<>
<Button variant="ghost" onClick={onChangePhone} size="sm">
Usar otro teléfono
</Button>
<Button variant="primary" onClick={onLink} size="sm">
Sí, agregarla
</Button>
</>
)}
</div>
</div>
)
}

View File

@@ -1,19 +1,47 @@
import { useState } from 'react'
import { useRef, useState } from 'react'
import { Check, Loader2 } from 'lucide-react'
import { Button, Input, Label, useToast } from '../../../components/ui'
import { useAddAttendee } from './AddAttendeeProvider'
import { ExistingPersonNotice } from './ExistingPersonNotice'
import { usePersonLookup } from './usePersonLookup'
export function QuickAddForm() {
const { submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
const { groupId, submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
const toast = useToast()
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const [phone, setPhone] = useState('')
const [email, setEmail] = useState('')
const [notes, setNotes] = useState('')
const phoneRef = useRef<HTMLInputElement>(null)
// El teléfono identifica a la persona: si ya la tenés en otro grupo, se suma
// esa misma persona (con sus datos) en vez de crear un duplicado.
const { person: existingPerson } = usePersonLookup(groupId, phone)
const [linkedPersonId, setLinkedPersonId] = useState<string | null>(null)
const linkedPerson = existingPerson && existingPerson.id === linkedPersonId ? existingPerson : null
const alreadyInGroup = Boolean(
existingPerson?.groups.some((group) => group.groupId === groupId && group.status !== 'DROPPED'),
)
// Con el teléfono de alguien que ya existe solo se puede vincular.
const mustLink = Boolean(existingPerson) && !linkedPerson
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (alreadyInGroup) return
if (linkedPerson) {
submitQuickAttendee({
firstName: linkedPerson.fullName,
lastName: '',
phone: phone.trim(),
personId: linkedPerson.id,
})
return
}
if (mustLink) {
toast.info('Ese teléfono ya es de una persona registrada: agregala o usá otro teléfono.')
return
}
if (!firstName.trim() || !phone.trim()) {
toast.error('Nombre y teléfono son obligatorios.')
return
@@ -33,7 +61,9 @@ export function QuickAddForm() {
setPhone('')
setEmail('')
setNotes('')
setLinkedPersonId(null)
}
const isLinked = Boolean(linkedPerson)
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
@@ -44,8 +74,9 @@ export function QuickAddForm() {
<Input
id="quick-first-name"
placeholder="Ej. Lucas"
value={firstName}
value={linkedPerson ? linkedPerson.fullName : firstName}
onChange={(e) => setFirstName(e.target.value)}
disabled={isLinked}
required
/>
</div>
@@ -56,8 +87,9 @@ export function QuickAddForm() {
<Input
id="quick-last-name"
placeholder="Ej. González"
value={lastName}
value={isLinked ? '' : lastName}
onChange={(e) => setLastName(e.target.value)}
disabled={isLinked}
/>
</div>
</div>
@@ -69,13 +101,31 @@ export function QuickAddForm() {
<Input
id="quick-phone"
placeholder="Ej. +54 9 11 2345-6789"
ref={phoneRef}
value={phone}
onChange={(e) => setPhone(e.target.value)}
onChange={(e) => {
setPhone(e.target.value)
setLinkedPersonId(null)
}}
required
/>
{existingPerson ? (
<ExistingPersonNotice
person={existingPerson}
alreadyInGroup={alreadyInGroup}
isLinked={isLinked}
onLink={() => setLinkedPersonId(existingPerson.id)}
onUnlink={() => setLinkedPersonId(null)}
onChangePhone={() => {
phoneRef.current?.focus()
phoneRef.current?.select()
}}
/>
) : (
<p className="mt-1 text-[11px] text-foreground/50">
Usado para contacto y validación de duplicados.
</p>
)}
</div>
<div>
@@ -86,8 +136,9 @@ export function QuickAddForm() {
id="quick-email"
type="email"
placeholder="alumno@ejemplo.com"
value={email}
value={linkedPerson ? (linkedPerson.email ?? '') : email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLinked}
/>
</div>
@@ -100,6 +151,7 @@ export function QuickAddForm() {
placeholder="Ej. Nivel intermedio, trae materiales propios"
value={notes}
onChange={(e) => setNotes(e.target.value)}
disabled={isLinked}
/>
</div>
@@ -117,7 +169,7 @@ export function QuickAddForm() {
<Button
variant="primary"
type="submit"
disabled={isSubmittingAttendee}
disabled={isSubmittingAttendee || alreadyInGroup}
className="w-full sm:w-auto"
>
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}

View File

@@ -0,0 +1,29 @@
import { useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { lookupPerson } from '../../../lib/api'
const DEBOUNCE_MS = 400
const MIN_DIGITS = 6
/* Mientras el profe escribe el teléfono: ¿ya es de una persona que tiene en
otro grupo? Espera a que deje de tipear para no pedir en cada tecla. */
export function usePersonLookup(groupId: string, phone: string) {
const [debouncedPhone, setDebouncedPhone] = useState(phone.trim())
useEffect(() => {
const timer = setTimeout(() => setDebouncedPhone(phone.trim()), DEBOUNCE_MS)
return () => clearTimeout(timer)
}, [phone])
const enabled = Boolean(groupId) && debouncedPhone.replace(/\D/g, '').length >= MIN_DIGITS
const query = useQuery({
queryKey: ['person-lookup', groupId, debouncedPhone],
queryFn: () => lookupPerson(groupId, debouncedPhone),
enabled,
staleTime: 30_000,
})
// Mientras el valor tipeado no coincide con el consultado, no hay veredicto.
const settled = enabled && debouncedPhone === phone.trim()
return { person: settled ? (query.data ?? null) : null }
}

View File

@@ -6,6 +6,7 @@ import type {
UpdateGroupAutomations,
AttendeeListItem,
GroupDto,
GroupListItem,
GroupPreRegistrationDto,
GroupWaitlistEntryDto,
GroupRiskLevel,
@@ -17,6 +18,7 @@ import {
approveGroupPreRegistration,
getGroup,
getGroupAttendees,
getGroups,
getGroupPreRegistrations,
getGroupsRiskOverview,
getGroupWaitlist,
@@ -75,7 +77,10 @@ type GroupDetailContextValue = {
isSubmittingApproval: boolean
isSubmittingRejection: boolean
isRegeneratingInvite: boolean
promoteEntry: (entry: GroupWaitlistEntryDto) => void
/** Grupos del profe: destino posible al pasar a alguien de la lista de espera. */
groups: GroupListItem[]
/** `targetGroupId` es este grupo por defecto, u otro grupo del profe. */
promoteEntry: (entry: GroupWaitlistEntryDto, targetGroupId: string) => void
removeEntry: (entry: GroupWaitlistEntryDto) => void
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
@@ -157,6 +162,8 @@ export function GroupDetailProvider({
enabled: Boolean(groupId),
})
const groupsQuery = useQuery({ queryKey: ['groups'], queryFn: getGroups })
const group = groupQuery.data
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
@@ -208,10 +215,19 @@ export function GroupDetailProvider({
})
const promoteWaitlistMutation = useMutation({
mutationFn: (entryId: string) => promoteGroupWaitlistEntry(groupId, entryId),
onSuccess: (result) => {
mutationFn: ({ entryId, targetGroupId }: { entryId: string; targetGroupId: string }) =>
promoteGroupWaitlistEntry(groupId, entryId, targetGroupId),
onSuccess: (result, { targetGroupId }) => {
if (targetGroupId === groupId) {
toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`)
} else {
const targetName = groupsQuery.data?.data.find((g) => g.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${result.attendee.fullName} pasó a ${targetName}.`)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
}
invalidateGroupQueries()
void queryClient.invalidateQueries({ queryKey: ['groups'] })
},
onError: (err: Error) => {
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
@@ -377,9 +393,10 @@ export function GroupDetailProvider({
isSubmittingApproval: approvePreRegistrationMutation.isPending,
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
isRegeneratingInvite: regenerateTokenMutation.isPending,
promoteEntry: (entry) => {
groups: groupsQuery.data?.data ?? [],
promoteEntry: (entry, targetGroupId) => {
setSelectedWaitlistEntry(null)
promoteWaitlistMutation.mutate(entry.id)
promoteWaitlistMutation.mutate({ entryId: entry.id, targetGroupId })
},
removeEntry: (entry) => {
setSelectedWaitlistEntry(null)

View File

@@ -1,11 +1,19 @@
import type { GroupListItem } from '@gruperly/shared'
import { useEffect, useState } from 'react'
import { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react'
import { Button, Modal } from '../../../components/ui'
import { formatPhoneDisplay } from '../../../lib/format'
import { DetailRow } from './DetailRow'
import { useGroupDetail } from './GroupDetailProvider'
function isFull(group: GroupListItem): boolean {
return group.capacity != null && group.attendeesCount >= group.capacity
}
export function WaitlistEntryDetailModal() {
const {
groupId,
groups,
selectedWaitlistEntry,
setSelectedWaitlistEntry,
hasFreeCapacity,
@@ -15,6 +23,16 @@ export function WaitlistEntryDetailModal() {
isSubmittingWaitlistRemoval,
} = useGroupDetail()
// Por defecto pasa al grupo en el que se anotó; el profe puede elegir otro.
const [targetGroupId, setTargetGroupId] = useState(groupId)
useEffect(() => {
setTargetGroupId(groupId)
}, [groupId, selectedWaitlistEntry])
const isCurrentGroup = targetGroupId === groupId
const targetGroup = groups.find((group) => group.id === targetGroupId)
const targetHasFreeCapacity = isCurrentGroup ? hasFreeCapacity : !targetGroup || !isFull(targetGroup)
return (
<Modal
isOpen={selectedWaitlistEntry !== null}
@@ -81,18 +99,42 @@ export function WaitlistEntryDetailModal() {
</DetailRow>
</div>
{!hasFreeCapacity ? (
{groups.length > 1 ? (
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Asignar a</span>
<select
value={targetGroupId}
onChange={(event) => setTargetGroupId(event.target.value)}
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
{groups.map((group) => {
const isOwnGroup = group.id === groupId
// El grupo actual queda elegible siempre: su cupo lo explica el aviso de abajo.
const full = !isOwnGroup && isFull(group)
return (
<option key={group.id} value={group.id} disabled={full}>
{group.name}
{isOwnGroup ? ' (en el que se anotó)' : full ? ' (sin cupo)' : ''}
</option>
)
})}
</select>
</label>
) : null}
{!targetHasFreeCapacity ? (
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-xs text-foreground/70">
El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar a esta
persona al grupo.
{isCurrentGroup
? 'El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar a esta persona al grupo.'
: 'Ese grupo alcanzó su cupo de miembros. Elige otro grupo o libera un lugar primero.'}
</p>
) : null}
<div className="grid grid-cols-1 gap-2.5 border-t border-border pt-2">
<Button
variant="primary"
onClick={() => promoteEntry(selectedWaitlistEntry)}
disabled={isSubmittingPromotion || !hasFreeCapacity}
onClick={() => promoteEntry(selectedWaitlistEntry, targetGroupId)}
disabled={isSubmittingPromotion || !targetHasFreeCapacity}
className="gap-2"
>
{isSubmittingPromotion ? (
@@ -100,7 +142,9 @@ export function WaitlistEntryDetailModal() {
) : (
<UserCheck className="size-4" />
)}
<span>Pasar al grupo</span>
<span className="truncate">
{isCurrentGroup || !targetGroup ? 'Pasar al grupo' : `Pasar a ${targetGroup.name}`}
</span>
</Button>
<Button
variant="ghost"

View File

@@ -0,0 +1,19 @@
import { Link } from '@tanstack/react-router'
import { Plus } from 'lucide-react'
import { cn } from '../../lib/utils'
/* Pie del selector de grupos de Cobros: lleva al alta de grupo. */
export function CreateGroupLink({ compact = false }: { compact?: boolean }) {
return (
<Link
to="/groups/new"
className={cn(
'flex items-center gap-2 rounded-xl px-3 text-sm font-medium text-accent-fg hover:bg-primary-soft',
compact ? 'min-h-10' : 'min-h-11',
)}
>
<Plus className="size-4" aria-hidden="true" />
Crear un grupo nuevo
</Link>
)
}

View File

@@ -0,0 +1,116 @@
import { ChevronDown, Users } from 'lucide-react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Sheet } from '../../components/ui'
import { cn } from '../../lib/utils'
import { CreateGroupLink } from './CreateGroupLink'
import { GroupOptionList } from './GroupOptionList'
import { usePayments } from './PaymentsProvider'
/* Mismo corte que la fila de filtros: debajo de `lg` la fila scrollea en
horizontal y un popover absoluto quedaría recortado, así que ahí va el sheet. */
const DESKTOP_QUERY = '(min-width: 1024px)'
function useIsDesktop() {
const [isDesktop, setIsDesktop] = useState(() => window.matchMedia(DESKTOP_QUERY).matches)
useEffect(() => {
const media = window.matchMedia(DESKTOP_QUERY)
const handleChange = () => setIsDesktop(media.matches)
media.addEventListener('change', handleChange)
return () => media.removeEventListener('change', handleChange)
}, [])
return isDesktop
}
/* Chip de grupo de la fila de filtros de Cobros: bottom sheet en mobile y
dropdown anclado al chip en desktop. */
export function GroupFilter() {
const { groups, groupId, setGroupId } = usePayments()
const [isOpen, setIsOpen] = useState(false)
const isDesktop = useIsDesktop()
const rootRef = useRef<HTMLDivElement>(null)
const chipRef = useRef<HTMLButtonElement>(null)
const selected = groups.find((group) => group.id === groupId)
// Estable: el `Sheet` vuelve a correr su efecto (y mueve el foco) si cambia `onClose`.
const close = useCallback(() => setIsOpen(false), [])
// El dropdown cierra con clic afuera y con Escape; el sheet resuelve ambos solo.
useEffect(() => {
if (!isOpen || !isDesktop) return
const handlePointerDown = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setIsOpen(false)
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return
setIsOpen(false)
chipRef.current?.focus()
}
document.addEventListener('pointerdown', handlePointerDown)
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('pointerdown', handlePointerDown)
document.removeEventListener('keydown', handleKeyDown)
}
}, [isOpen, isDesktop])
const handleSelect = (next: string | null) => {
setIsOpen(false)
// En mobile el `Sheet` devuelve el foco al chip al cerrarse.
if (isDesktop) chipRef.current?.focus()
if (next !== groupId) setGroupId(next)
}
const list = (
<GroupOptionList groups={groups} selectedId={groupId} onSelect={handleSelect} compact={isDesktop} />
)
return (
<div ref={rootRef} className="relative shrink-0">
<button
ref={chipRef}
type="button"
aria-haspopup="listbox"
aria-expanded={isOpen}
aria-label={`Grupo: ${selected?.name ?? 'Todos los grupos'}`}
onClick={() => setIsOpen((open) => !open)}
className={cn(
'flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
isOpen
? 'border-accent bg-accent-soft text-accent-fg'
: 'border-border bg-surface text-primary hover:border-accent/50',
selected && 'font-semibold',
)}
>
<Users className="size-4 shrink-0" aria-hidden="true" />
<span className="max-w-[12rem] truncate">{selected?.name ?? 'Todos los grupos'}</span>
<ChevronDown
className={cn(
'size-4 shrink-0 transition-transform motion-reduce:transition-none',
isOpen && 'rotate-180',
)}
aria-hidden="true"
/>
</button>
{isDesktop ? (
isOpen ? (
<div className="absolute left-0 top-full z-40 mt-1.5 w-80 animate-fade-in rounded-xl border border-border bg-surface p-1.5 shadow-lg">
<p className="px-2.5 py-1.5 text-xs font-medium text-foreground/50">Grupos</p>
<div className="max-h-80 overflow-y-auto">{list}</div>
<div className="mt-1.5 border-t border-border pt-1.5">
<CreateGroupLink compact />
</div>
</div>
) : null
) : (
<Sheet isOpen={isOpen} onClose={close} title="Elegir grupo">
{list}
<div className="mt-3 border-t border-border pt-2">
<CreateGroupLink />
</div>
</Sheet>
)}
</div>
)
}

Some files were not shown because too many files have changed in this diff Show More