From d21e1c37302d8d3f2ff8b0af05f4df21284bffe3 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 3 Nov 2026 09:46:37 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20un=20miembro=20puede=20pertenecer=20a?= =?UTF-8?q?=20m=C3=A1s=20de=20un=20grupo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- AGENTS.md | 10 +- .../20261102180000_add_people/migration.sql | 182 +++++++++++++++++ apps/backend/prisma/models/auth.prisma | 1 + apps/backend/prisma/models/domain.prisma | 46 +++-- .../prisma/models/student-access.prisma | 23 ++- apps/backend/src/app.ts | 2 + .../features/get-attendee-history/use-case.ts | 5 +- .../get-groups-risk-overview/use-case.ts | 5 +- .../features/get-students-at-risk/use-case.ts | 5 +- .../attendees/features/add-to-group/route.ts | 24 +++ .../features/add-to-group/use-case.ts | 88 +++++++++ .../features/add-to-waitlist/use-case.ts | 6 +- .../features/bulk-create/use-case.ts | 79 +++++--- .../attendees/features/create/use-case.ts | 115 +++++++---- .../attendees/features/get-all/use-case.ts | 3 +- .../attendees/features/get-by-id/use-case.ts | 14 +- .../attendees/features/move/use-case.ts | 7 +- .../attendees/features/remove/use-case.ts | 9 +- .../attendees/features/update/use-case.ts | 32 ++- .../src/modules/attendees/lib/helpers.ts | 49 ++++- .../features/get-overview/use-case.ts | 13 +- .../src/modules/billing/lib/entitlements.ts | 7 +- .../features/public-details/use-case.ts | 5 +- .../features/session-students/use-case.ts | 6 +- .../features/approve/use-case.ts | 6 +- .../features/promote/use-case.ts | 6 +- .../src/modules/group-waitlist/lib/promote.ts | 52 ++--- apps/backend/src/modules/groups/routes.ts | 2 + .../home/features/get-summary/use-case.ts | 4 +- .../features/join-via-invite/use-case.ts | 11 +- .../features/create-batch/use-case.ts | 3 +- .../payments/features/get-all/use-case.ts | 2 +- .../payments/features/renew/use-case.ts | 4 +- .../payments/features/reported/use-case.ts | 4 +- .../src/modules/payments/lib/helpers.ts | 4 +- .../modules/people/features/lookup/route.ts | 18 ++ .../people/features/lookup/use-case.ts | 24 +++ apps/backend/src/modules/people/index.ts | 1 + apps/backend/src/modules/people/lib/people.ts | 142 ++++++++++++++ apps/backend/src/modules/people/routes.ts | 8 + .../features/get-status/use-case.ts | 6 +- .../features/invite/use-case.ts | 23 ++- .../features/list-absence-notices/use-case.ts | 4 +- .../src/modules/student-access/lib/status.ts | 11 +- .../features/absences/use-case.ts | 2 +- .../features/link-info/use-case.ts | 16 +- .../student-portal/features/me/use-case.ts | 32 +-- .../src/modules/student-portal/lib/access.ts | 27 +-- .../whatsapp/jobs/send-payment-reminders.ts | 9 +- .../jobs/send-reengagement-messages.ts | 5 +- .../test/attendee-add-to-group.test.ts | 175 +++++++++++++++++ apps/backend/test/attendee-get-by-id.test.ts | 24 ++- apps/backend/test/attendee-move.test.ts | 23 ++- apps/backend/test/attendee-update.test.ts | 69 +++++-- .../test/attendees-incorporation.test.ts | 184 +++++++++++++----- apps/backend/test/attendees-list-item.test.ts | 20 +- apps/backend/test/attendees.test.ts | 29 ++- .../backend/test/billing-entitlements.test.ts | 3 +- apps/backend/test/billing-plan-guards.test.ts | 11 +- apps/backend/test/classes.test.ts | 6 +- .../backend/test/db/payment-review.db.test.ts | 7 +- .../backend/test/db/student-access.db.test.ts | 37 +++- .../backend/test/db/student-portal.db.test.ts | 41 +++- apps/backend/test/home.test.ts | 4 +- apps/backend/test/payments-batch.test.ts | 11 +- apps/backend/test/payments-renew.test.ts | 4 +- apps/backend/test/payments.test.ts | 4 +- apps/backend/test/preregistrations.test.ts | 42 +++- apps/backend/test/student-portal-auth.test.ts | 2 +- apps/backend/test/waitlist-management.test.ts | 50 ++++- apps/backend/test/whatsapp-jobs.test.ts | 8 +- .../attendee-detail/AttendeeActionsMenu.tsx | 16 +- .../attendee-detail/AttendeeContactForm.tsx | 4 + .../AttendeeContactSection.tsx | 14 +- .../AttendeeDetailProvider.tsx | 57 +++++- .../attendee-detail/AttendeeDetailView.tsx | 2 + .../attendee-detail/ChangeGroupDialog.tsx | 105 ++++++---- .../attendee-detail/OtherGroupsSection.tsx | 49 +++++ .../groups/add/AddAttendeeProvider.tsx | 10 + .../groups/add/ExistingPersonNotice.tsx | 71 +++++++ .../src/features/groups/add/QuickAddForm.tsx | 72 ++++++- .../features/groups/add/usePersonLookup.ts | 29 +++ apps/web/src/lib/api.ts | 15 ++ packages/shared/src/schemas/attendees.ts | 44 +++++ 84 files changed, 1981 insertions(+), 423 deletions(-) create mode 100644 apps/backend/prisma/migrations/20261102180000_add_people/migration.sql create mode 100644 apps/backend/src/modules/attendees/features/add-to-group/route.ts create mode 100644 apps/backend/src/modules/attendees/features/add-to-group/use-case.ts create mode 100644 apps/backend/src/modules/people/features/lookup/route.ts create mode 100644 apps/backend/src/modules/people/features/lookup/use-case.ts create mode 100644 apps/backend/src/modules/people/index.ts create mode 100644 apps/backend/src/modules/people/lib/people.ts create mode 100644 apps/backend/src/modules/people/routes.ts create mode 100644 apps/backend/test/attendee-add-to-group.test.ts create mode 100644 apps/web/src/features/attendee-detail/OtherGroupsSection.tsx create mode 100644 apps/web/src/features/groups/add/ExistingPersonNotice.tsx create mode 100644 apps/web/src/features/groups/add/usePersonLookup.ts diff --git a/AGENTS.md b/AGENTS.md index 528c777..5e94eff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,12 +70,20 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web 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 diff --git a/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql new file mode 100644 index 0000000..a67892f --- /dev/null +++ b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql @@ -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; diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma index 97fd6a8..f701f92 100644 --- a/apps/backend/prisma/models/auth.prisma +++ b/apps/backend/prisma/models/auth.prisma @@ -28,6 +28,7 @@ model User { whatsappAccount WhatsappAccount? subscription BillingSubscription? studentAccounts StudentAccount[] @relation("StudentAccountsCreated") + people Person[] @relation("OwnerPeople") @@map("users") } diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index cb48448..3dacdf2 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -72,31 +72,55 @@ enum AttendeeStatus { DROPPED } -model Attendee { - id String @id @default(cuid()) - groupId String @map("group_id") - fullName String @map("full_name") +// 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()) + 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") + guardianName String? @map("guardian_name") + guardianPhone String? @map("guardian_phone") notes String? - 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") + 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") } diff --git a/apps/backend/prisma/models/student-access.prisma b/apps/backend/prisma/models/student-access.prisma index 3c9d16b..0dd705b 100644 --- a/apps/backend/prisma/models/student-access.prisma +++ b/apps/backend/prisma/models/student-access.prisma @@ -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 { - accountId String @map("account_id") - attendeeId String @map("attendee_id") - createdAt DateTime @default(now()) @map("created_at") +// 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") + 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) + account StudentAccount @relation(fields: [accountId], 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 { diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index f2995d3..3a064d7 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -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) => { diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts index 827c85d..67733fa 100644 --- a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts @@ -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)); } diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts index 9339743..4521b38 100644 --- a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts @@ -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, + 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 }, diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts index 7bbd064..d3ea984 100644 --- a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts @@ -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: { diff --git a/apps/backend/src/modules/attendees/features/add-to-group/route.ts b/apps/backend/src/modules/attendees/features/add-to-group/route.ts new file mode 100644 index 0000000..9e17479 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-group/route.ts @@ -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; diff --git a/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts new file mode 100644 index 0000000..af24c3b --- /dev/null +++ b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts @@ -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; + unitOfWork?: Pick; +}; + +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> { + 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> => { + 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; + } + } +} diff --git a/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts index 764b629..c4e186c 100644 --- a/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts +++ b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts @@ -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) } }, }, }); diff --git a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts index 2a5f1f8..0edc689 100644 --- a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts @@ -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; + db?: Pick; planGuard?: Pick; }; @@ -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(); - for (const a of existingAttendees) { - if (a.phone) { - existingPhones.add(normalizePhone(a.phone)); - } + const peopleByPhone = new Map(); + 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(); + 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, diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts index 9ee24bd..814600d 100644 --- a/apps/backend/src/modules/attendees/features/create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/create/use-case.ts @@ -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; + db?: Pick; planGuard?: Pick; }; @@ -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) { - return err( - conflictProblem({ - detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', - code: 'attendee_already_registered', - }), - ); + /* 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( + 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({ - data: { - groupId, - fullName, - phone, - email: payload.email?.trim() || null, - notes: payload.notes?.trim() || null, - }, - }); + try { + const attendee = membership + ? await db.attendee.update({ + where: { id: membership.id }, + data: { status: 'ACTIVE' }, + include: attendeeWithPerson, + }) + : await db.attendee.create({ + data: { + 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; + } } -} \ No newline at end of file +} diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts index e9438df..e9e4726 100644 --- a/apps/backend/src/modules/attendees/features/get-all/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts @@ -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; @@ -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: { diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts index 0f9e987..60b220e 100644 --- a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts @@ -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; @@ -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)), + }), + ); } } diff --git a/apps/backend/src/modules/attendees/features/move/use-case.ts b/apps/backend/src/modules/attendees/features/move/use-case.ts index 54a625b..5fd2394 100644 --- a/apps/backend/src/modules/attendees/features/move/use-case.ts +++ b/apps/backend/src/modules/attendees/features/move/use-case.ts @@ -5,7 +5,7 @@ import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builder 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 { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; +import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers'; type MoveAttendeeDeps = { db?: Pick; @@ -54,7 +54,7 @@ export class MoveAttendee { return unitOfWork.executeResult( async (tx: Prisma.TransactionClient): Promise> => { - const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.phone); + const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId); if (!canJoin.ok) return canJoin; const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } }; @@ -68,8 +68,9 @@ export class MoveAttendee { const moved = await tx.attendee.update({ where: { id: attendeeId }, data: { groupId: targetGroupId }, + include: attendeeWithPerson, }); - return ok(toAttendeeDto(moved as unknown as AttendeeRecord)); + return ok(toAttendeeDto(moved)); }, ); } diff --git a/apps/backend/src/modules/attendees/features/remove/use-case.ts b/apps/backend/src/modules/attendees/features/remove/use-case.ts index 584956b..9201822 100644 --- a/apps/backend/src/modules/attendees/features/remove/use-case.ts +++ b/apps/backend/src/modules/attendees/features/remove/use-case.ts @@ -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> => { 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 }); diff --git a/apps/backend/src/modules/attendees/features/update/use-case.ts b/apps/backend/src/modules/attendees/features/update/use-case.ts index e288e80..1af86d7 100644 --- a/apps/backend/src/modules/attendees/features/update/use-case.ts +++ b/apps/backend/src/modules/attendees/features/update/use-case.ts @@ -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; + db?: Pick; }; type UpdateAttendeeCommand = { @@ -26,12 +27,26 @@ 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({ + // 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 }, - data: normalizeEditableFields(input), + include: attendeeWithPerson, }); return ok(toAttendeeDto(updated)); } @@ -39,6 +54,11 @@ export class UpdateAttendeeDetails { 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]; + }), ); } diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 06ac783..066bd00 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -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( + row: TRow, +): Omit & TRow['person'] { + const { person, ...rest } = row; + return { ...rest, ...person }; +} diff --git a/apps/backend/src/modules/attention/features/get-overview/use-case.ts b/apps/backend/src/modules/attention/features/get-overview/use-case.ts index e68fdd6..aeec72e 100644 --- a/apps/backend/src/modules/attention/features/get-overview/use-case.ts +++ b/apps/backend/src/modules/attention/features/get-overview/use-case.ts @@ -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, + }).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, diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts index 1193ff2..ab8746d 100644 --- a/apps/backend/src/modules/billing/lib/entitlements.ts +++ b/apps/backend/src/modules/billing/lib/entitlements.ts @@ -86,7 +86,7 @@ export type Entitlements = PlanResolution & { }; type PlanGuardDeps = { - db?: Pick; + db?: Pick; 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()); diff --git a/apps/backend/src/modules/classes/features/public-details/use-case.ts b/apps/backend/src/modules/classes/features/public-details/use-case.ts index db40339..0f31993 100644 --- a/apps/backend/src/modules/classes/features/public-details/use-case.ts +++ b/apps/backend/src/modules/classes/features/public-details/use-case.ts @@ -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; diff --git a/apps/backend/src/modules/classes/features/session-students/use-case.ts b/apps/backend/src/modules/classes/features/session-students/use-case.ts index e7c30a1..037b7a3 100644 --- a/apps/backend/src/modules/classes/features/session-students/use-case.ts +++ b/apps/backend/src/modules/classes/features/session-students/use-case.ts @@ -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 }, diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts index e4166b6..02762aa 100644 --- a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts +++ b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts @@ -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; + db?: Pick; unitOfWork?: UnitOfWork; planGuard?: Pick; }; @@ -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; } diff --git a/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts index 412b383..a0291f6 100644 --- a/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts +++ b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts @@ -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; + db?: Pick; unitOfWork?: UnitOfWork; planGuard?: Pick; }; @@ -51,7 +52,8 @@ export class PromoteGroupWaitlistEntry { targetGroup = targetResult.value; } - 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; } diff --git a/apps/backend/src/modules/group-waitlist/lib/promote.ts b/apps/backend/src/modules/group-waitlist/lib/promote.ts index fb72812..de10bb5 100644 --- a/apps/backend/src/modules/group-waitlist/lib/promote.ts +++ b/apps/backend/src/modules/group-waitlist/lib/promote.ts @@ -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; +export type PromoteDb = Pick; type PromoteGroup = { id: string; capacity: number | null; + createdById: string; }; export async function findFirstPendingWaitlistEntry( @@ -23,13 +25,13 @@ export async function findFirstPendingWaitlistEntry( return record as GroupWaitlistEntryRecord | null; } -/* Whether someone can join `group`: free capacity (ACTIVE members) and no - member there with the same phone. Shared by the waitlist promotion and the - member move between groups. */ +/* 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, - group: PromoteGroup, - phone: string | null, + group: Pick, + personId: string | null, ): Promise> { if (group.capacity !== null) { const currentCount = await db.attendee.count({ @@ -40,44 +42,44 @@ export async function checkCanJoinGroup( } } - if (phone) { + if (personId) { const existing = await db.attendee.findFirst({ - where: { groupId: group.id, 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()); } } 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> { - const canJoin = await checkCanJoinGroup(db, group, entry.phone); + const person = await findOrCreatePerson(db, group.createdById, { + fullName: entry.fullName, + phone: entry.phone, + email: entry.email, + notes: entry.notes, + }); + + 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, - fullName: entry.fullName, - phone: entry.phone, - email: entry.email, - notes: entry.notes, - }, + data: { groupId: group.id, personId: person.id }, + include: attendeeWithPerson, }); - return ok(toAttendeeDto(attendee as unknown as AttendeeRecord)); + return ok(toAttendeeDto(attendee)); } export type PromoteFirstResult = { diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index cee0eeb..b1848bf 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -1,5 +1,6 @@ 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'; @@ -39,6 +40,7 @@ routes.route('/', updateAttendeeRoute); routes.route('/', getAttendeeStatsRoute); routes.route('/', removeAttendeeRoute); routes.route('/', moveAttendeeRoute); +routes.route('/', addAttendeeToGroupRoute); routes.route('/', studentAccessRoutes); export default routes; diff --git a/apps/backend/src/modules/home/features/get-summary/use-case.ts b/apps/backend/src/modules/home/features/get-summary/use-case.ts index d7e5af6..bcf74ba 100644 --- a/apps/backend/src/modules/home/features/get-summary/use-case.ts +++ b/apps/backend/src/modules/home/features/get-summary/use-case.ts @@ -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) diff --git a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts index 8bbe0a5..8e98107 100644 --- a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts +++ b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts @@ -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; @@ -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) }, }, }); diff --git a/apps/backend/src/modules/payments/features/create-batch/use-case.ts b/apps/backend/src/modules/payments/features/create-batch/use-case.ts index f6029b4..9a57861 100644 --- a/apps/backend/src/modules/payments/features/create-batch/use-case.ts +++ b/apps/backend/src/modules/payments/features/create-batch/use-case.ts @@ -81,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()); @@ -150,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, diff --git a/apps/backend/src/modules/payments/features/get-all/use-case.ts b/apps/backend/src/modules/payments/features/get-all/use-case.ts index 88fa89d..8552e41 100644 --- a/apps/backend/src/modules/payments/features/get-all/use-case.ts +++ b/apps/backend/src/modules/payments/features/get-all/use-case.ts @@ -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, diff --git a/apps/backend/src/modules/payments/features/renew/use-case.ts b/apps/backend/src/modules/payments/features/renew/use-case.ts index 3ed3c80..1766487 100644 --- a/apps/backend/src/modules/payments/features/renew/use-case.ts +++ b/apps/backend/src/modules/payments/features/renew/use-case.ts @@ -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, @@ -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 } }, }, }); diff --git a/apps/backend/src/modules/payments/features/reported/use-case.ts b/apps/backend/src/modules/payments/features/reported/use-case.ts index b50fee0..10da111 100644 --- a/apps/backend/src/modules/payments/features/reported/use-case.ts +++ b/apps/backend/src/modules/payments/features/reported/use-case.ts @@ -31,7 +31,7 @@ const reportSelect = { 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; @@ -202,7 +202,7 @@ 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(), diff --git a/apps/backend/src/modules/payments/lib/helpers.ts b/apps/backend/src/modules/payments/lib/helpers.ts index a3b5eda..3da80bd 100644 --- a/apps/backend/src/modules/payments/lib/helpers.ts +++ b/apps/backend/src/modules/payments/lib/helpers.ts @@ -18,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 { @@ -27,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, diff --git a/apps/backend/src/modules/people/features/lookup/route.ts b/apps/backend/src/modules/people/features/lookup/route.ts new file mode 100644 index 0000000..cc2e17a --- /dev/null +++ b/apps/backend/src/modules/people/features/lookup/route.ts @@ -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; diff --git a/apps/backend/src/modules/people/features/lookup/use-case.ts b/apps/backend/src/modules/people/features/lookup/use-case.ts new file mode 100644 index 0000000..3d381c8 --- /dev/null +++ b/apps/backend/src/modules/people/features/lookup/use-case.ts @@ -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; +}; + +/* 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> { + 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)); + } +} diff --git a/apps/backend/src/modules/people/index.ts b/apps/backend/src/modules/people/index.ts new file mode 100644 index 0000000..73592d8 --- /dev/null +++ b/apps/backend/src/modules/people/index.ts @@ -0,0 +1 @@ +export { default as peopleRoutes } from './routes'; diff --git a/apps/backend/src/modules/people/lib/people.ts b/apps/backend/src/modules/people/lib/people.ts new file mode 100644 index 0000000..1baa790 --- /dev/null +++ b/apps/backend/src/modules/people/lib/people.ts @@ -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; + +/* 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 { + 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 { + 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', + }); +} diff --git a/apps/backend/src/modules/people/routes.ts b/apps/backend/src/modules/people/routes.ts new file mode 100644 index 0000000..a673c5e --- /dev/null +++ b/apps/backend/src/modules/people/routes.ts @@ -0,0 +1,8 @@ +import { Hono } from 'hono'; +import lookupRoute from './features/lookup/route'; + +const routes = new Hono(); + +routes.route('/', lookupRoute); + +export default routes; diff --git a/apps/backend/src/modules/student-access/features/get-status/use-case.ts b/apps/backend/src/modules/student-access/features/get-status/use-case.ts index b461fd4..1a0f8ee 100644 --- a/apps/backend/src/modules/student-access/features/get-status/use-case.ts +++ b/apps/backend/src/modules/student-access/features/get-status/use-case.ts @@ -7,7 +7,7 @@ import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { computeStudentAccess } from '../../lib/status'; type GetStudentAccessDeps = { - db?: Pick; + db?: Pick; 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())); } } diff --git a/apps/backend/src/modules/student-access/features/invite/use-case.ts b/apps/backend/src/modules/student-access/features/invite/use-case.ts index 11c44d8..b85b99d 100644 --- a/apps/backend/src/modules/student-access/features/invite/use-case.ts +++ b/apps/backend/src/modules/student-access/features/invite/use-case.ts @@ -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; + db?: Pick; unitOfWork?: Pick; 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), }); } } diff --git a/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts b/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts index 7da29a0..dc1be9d 100644 --- a/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts +++ b/apps/backend/src/modules/student-access/features/list-absence-notices/use-case.ts @@ -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, diff --git a/apps/backend/src/modules/student-access/lib/status.ts b/apps/backend/src/modules/student-access/lib/status.ts index f3388a8..1392343 100644 --- a/apps/backend/src/modules/student-access/lib/status.ts +++ b/apps/backend/src/modules/student-access/lib/status.ts @@ -1,17 +1,18 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { StudentAccessDto } from '@gruperly/shared'; -export type StudentAccessStatusDb = Pick; +export type StudentAccessStatusDb = Pick; /* 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 { - const link = await db.studentAccountAttendee.findFirst({ - where: { attendeeId }, + const link = await db.studentAccountPerson.findFirst({ + where: { personId }, orderBy: { createdAt: 'asc' }, select: { account: { diff --git a/apps/backend/src/modules/student-portal/features/absences/use-case.ts b/apps/backend/src/modules/student-portal/features/absences/use-case.ts index 3748887..d74391d 100644 --- a/apps/backend/src/modules/student-portal/features/absences/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/absences/use-case.ts @@ -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 } } }, }); diff --git a/apps/backend/src/modules/student-portal/features/link-info/use-case.ts b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts index a863651..62563a4 100644 --- a/apps/backend/src/modules/student-portal/features/link-info/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts @@ -32,10 +32,20 @@ export class GetStudentLinkInfo { account: { select: { name: true, - attendees: { + people: { orderBy: { createdAt: 'asc' }, take: 1, - select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } }, + select: { + person: { + select: { + attendees: { + orderBy: { createdAt: 'asc' }, + take: 1, + 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', diff --git a/apps/backend/src/modules/student-portal/features/me/use-case.ts b/apps/backend/src/modules/student-portal/features/me/use-case.ts index 264c17e..f2d1a27 100644 --- a/apps/backend/src/modules/student-portal/features/me/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/me/use-case.ts @@ -20,15 +20,21 @@ 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: { - id: true, fullName: true, - group: { select: { id: true, name: true, owner: { select: { name: true } } } }, + attendees: { + where: { status: { not: 'DROPPED' } }, + orderBy: { createdAt: 'asc' }, + select: { + id: true, + group: { select: { id: true, name: true, owner: { select: { name: true } } } }, + }, + }, }, }, }, @@ -46,13 +52,15 @@ export class GetStudentMe { hasPasskey: account._count.passkeys > 0, welcomed: account.welcomedAt !== null, }, - students: account.attendees.map(({ attendee }) => ({ - attendeeId: attendee.id, - fullName: attendee.fullName, - groupId: attendee.group.id, - groupName: attendee.group.name, - teacherName: attendee.group.owner.name, - })), + students: account.people.flatMap(({ person }) => + person.attendees.map((attendee) => ({ + attendeeId: attendee.id, + fullName: person.fullName, + groupId: attendee.group.id, + groupName: attendee.group.name, + teacherName: attendee.group.owner.name, + })), + ), }); } } diff --git a/apps/backend/src/modules/student-portal/lib/access.ts b/apps/backend/src/modules/student-portal/lib/access.ts index e54668c..436f2ef 100644 --- a/apps/backend/src/modules/student-portal/lib/access.ts +++ b/apps/backend/src/modules/student-portal/lib/access.ts @@ -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 { - 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: { diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts index 7292875..bcb61c5 100644 --- a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts +++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts @@ -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), diff --git a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts index 0e452d2..a02d7a1 100644 --- a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts +++ b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts @@ -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; diff --git a/apps/backend/test/attendee-add-to-group.test.ts b/apps/backend/test/attendee-add-to-group.test.ts new file mode 100644 index 0000000..aceea7c --- /dev/null +++ b/apps/backend/test/attendee-add-to-group.test.ts @@ -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) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const group = (overrides: Record = {}) => ({ + id: 'group-1', + name: 'Taller de Pintura', + createdById: teacherId, + capacity: 20, + ...overrides, +}); +const targetGroup = (overrides: Record = {}) => + 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 = {}) => ({ + 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(); + }); +}); diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts index aed0da3..0dd69af 100644 --- a/apps/backend/test/attendee-get-by-id.test.ts +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -38,12 +38,21 @@ function makeGroup(overrides: Record = {}) { const attendee = { id: 'a-1', groupId: 'group-1', - fullName: 'Ana Pérez', - email: 'ana@example.com', - phone: '5512345678', - guardianName: 'Luis Pérez', - guardianPhone: null, - notes: null, + 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' }, diff --git a/apps/backend/test/attendee-move.test.ts b/apps/backend/test/attendee-move.test.ts index 220d9e7..2ed4247 100644 --- a/apps/backend/test/attendee-move.test.ts +++ b/apps/backend/test/attendee-move.test.ts @@ -56,12 +56,16 @@ const targetGroup = (overrides: Record = {}) => const attendee = (overrides: Record = {}) => ({ id: 'att-1', groupId: 'group-1', - fullName: 'Martín Gómez', - phone: '+5491133445566', - email: null, - guardianName: null, - guardianPhone: null, - notes: null, + 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'), @@ -105,6 +109,7 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => { 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) } }, @@ -169,7 +174,7 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => { expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled(); }); - it('rejects with 409 when the phone already belongs to a member of the target group', async () => { + 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); @@ -182,6 +187,10 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => { 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(); }); diff --git a/apps/backend/test/attendee-update.test.ts b/apps/backend/test/attendee-update.test.ts index ad2f63e..41867b0 100644 --- a/apps/backend/test/attendee-update.test.ts +++ b/apps/backend/test/attendee-update.test.ts @@ -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() }) }) diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts index 4ffbb54..daf6052 100644 --- a/apps/backend/test/attendees-incorporation.test.ts +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -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 = {}) => ({ + 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 = {}) => ({ + 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', - fullName: 'Martín Gómez', - phone: '+5491133445566', - email: 'martin@example.com', - notes: 'Viene con su hermano', + 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, diff --git a/apps/backend/test/attendees-list-item.test.ts b/apps/backend/test/attendees-list-item.test.ts index 5a77cf1..13eefa9 100644 --- a/apps/backend/test/attendees-list-item.test.ts +++ b/apps/backend/test/attendees-list-item.test.ts @@ -11,12 +11,16 @@ function record( return { id: 'att-1', groupId: 'group-1', - fullName: 'Ana Pérez', - email: null, - phone: null, - guardianName: null, - guardianPhone: null, - notes: null, + 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'); }); }); diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index 4cf4098..428229b 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -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, diff --git a/apps/backend/test/billing-entitlements.test.ts b/apps/backend/test/billing-entitlements.test.ts index e81366b..5dc8687 100644 --- a/apps/backend/test/billing-entitlements.test.ts +++ b/apps/backend/test/billing-entitlements.test.ts @@ -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) }, }; } diff --git a/apps/backend/test/billing-plan-guards.test.ts b/apps/backend/test/billing-plan-guards.test.ts index ba118ce..77cc2bd 100644 --- a/apps/backend/test/billing-plan-guards.test.ts +++ b/apps/backend/test/billing-plan-guards.test.ts @@ -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(); diff --git a/apps/backend/test/classes.test.ts b/apps/backend/test/classes.test.ts index bd0012e..4533a58 100644 --- a/apps/backend/test/classes.test.ts +++ b/apps/backend/test/classes.test.ts @@ -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', diff --git a/apps/backend/test/db/payment-review.db.test.ts b/apps/backend/test/db/payment-review.db.test.ts index cfcd384..912a87a 100644 --- a/apps/backend/test/db/payment-review.db.test.ts +++ b/apps/backend/test/db/payment-review.db.test.ts @@ -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({ diff --git a/apps/backend/test/db/student-access.db.test.ts b/apps/backend/test/db/student-access.db.test.ts index 8a8b6f7..870bb58 100644 --- a/apps/backend/test/db/student-access.db.test.ts +++ b/apps/backend/test/db/student-access.db.test.ts @@ -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' } }); + }); }); diff --git a/apps/backend/test/db/student-portal.db.test.ts b/apps/backend/test/db/student-portal.db.test.ts index b2a9e51..d3b375b 100644 --- a/apps/backend/test/db/student-portal.db.test.ts +++ b/apps/backend/test/db/student-portal.db.test.ts @@ -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); diff --git a/apps/backend/test/home.test.ts b/apps/backend/test/home.test.ts index 7df2cec..af66ce1 100644 --- a/apps/backend/test/home.test.ts +++ b/apps/backend/test/home.test.ts @@ -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 } } } } }, }); }); diff --git a/apps/backend/test/payments-batch.test.ts b/apps/backend/test/payments-batch.test.ts index b581cfa..455746c 100644 --- a/apps/backend/test/payments-batch.test.ts +++ b/apps/backend/test/payments-batch.test.ts @@ -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' }) @@ -149,7 +149,7 @@ describe('create payments batch', () => { 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', { diff --git a/apps/backend/test/payments-renew.test.ts b/apps/backend/test/payments-renew.test.ts index 2bf16ed..9c5f16e 100644 --- a/apps/backend/test/payments-renew.test.ts +++ b/apps/backend/test/payments-renew.test.ts @@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record = {}) { 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' }, @@ -107,7 +107,7 @@ describe('renew payment link', () => { 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 } }, }, }); diff --git a/apps/backend/test/payments.test.ts b/apps/backend/test/payments.test.ts index 2728c36..255f7db 100644 --- a/apps/backend/test/payments.test.ts +++ b/apps/backend/test/payments.test.ts @@ -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, diff --git a/apps/backend/test/preregistrations.test.ts b/apps/backend/test/preregistrations.test.ts index c4627a5..036bfd8 100644 --- a/apps/backend/test/preregistrations.test.ts +++ b/apps/backend/test/preregistrations.test.ts @@ -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 = {}) => ({ const attendee = (overrides: Record = {}) => ({ id: 'att-1', groupId: 'group-1', - fullName: 'Martín Gómez', - phone: '+5491133445566', - email: null, - guardianName: null, - guardianPhone: null, - notes: null, + 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,7 +272,14 @@ describe('group pre-registrations', () => { prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); prisma.attendee.count.mockResolvedValue(5); - prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + 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( '/groups/group-1/preregistrations/pre-1/approve', diff --git a/apps/backend/test/student-portal-auth.test.ts b/apps/backend/test/student-portal-auth.test.ts index 57572fa..6bd53b6 100644 --- a/apps/backend/test/student-portal-auth.test.ts +++ b/apps/backend/test/student-portal-auth.test.ts @@ -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(), diff --git a/apps/backend/test/waitlist-management.test.ts b/apps/backend/test/waitlist-management.test.ts index 412e001..edca032 100644 --- a/apps/backend/test/waitlist-management.test.ts +++ b/apps/backend/test/waitlist-management.test.ts @@ -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 = {}) => ({ const attendee = (overrides: Record = {}) => ({ id: 'att-1', groupId: 'group-1', - fullName: 'Martín Gómez', - phone: '+5491133445566', - email: null, - guardianName: null, - guardianPhone: null, - notes: null, + 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', { @@ -227,7 +251,8 @@ describe('group waitlist management', () => { 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: expect.objectContaining({ groupId: 'group-2', fullName: 'Martín Gómez' }), + data: { groupId: 'group-2', personId: 'person-1' }, + include: { person: { select: expect.any(Object) } }, }); expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); }); @@ -325,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 () => { @@ -353,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 }, }); }); diff --git a/apps/backend/test/whatsapp-jobs.test.ts b/apps/backend/test/whatsapp-jobs.test.ts index 7316bb7..9b43f2e 100644 --- a/apps/backend/test/whatsapp-jobs.test.ts +++ b/apps/backend/test/whatsapp-jobs.test.ts @@ -37,7 +37,7 @@ function payment(id: string, attendee: Record, 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 } }, diff --git a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx index c3d7e6f..444e324 100644 --- a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx @@ -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 }) { - const { beginContactEdit, openRemoveDialog, openChangeGroupDialog } = useAttendeeDetail() + const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail() const toast = useToast() const [isOpen, setIsOpen] = useState(false) const menuRef = useRef(null) @@ -112,6 +112,18 @@ export function AttendeeActionsMenu({