development #14

Merged
jselesan merged 102 commits from development into main 2026-11-07 13:21:43 +00:00
808 changed files with 68746 additions and 1203 deletions
Showing only changes of commit d21e1c3730 - Show all commits

View File

@@ -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

View File

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

View File

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

View File

@@ -72,31 +72,55 @@ enum AttendeeStatus {
DROPPED
}
model Attendee {
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")
}

View File

@@ -24,7 +24,7 @@ model StudentAccount {
updatedAt DateTime @updatedAt @map("updated_at")
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
attendees StudentAccountAttendee[]
people StudentAccountPerson[]
tokens StudentAccessToken[]
sessions StudentSession[]
passkeys StudentPasskey[]
@@ -37,17 +37,20 @@ model StudentAccount {
@@map("student_accounts")
}
model StudentAccountAttendee {
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 {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
import {
alreadyWaitlistedProblem,
capacityReachedProblem,
conflictProblem,
noGroupAccessProblem,
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
import {
alreadyInGroupProblem,
findPersonByPhone,
isUniqueViolation,
personExistsProblem,
} from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
}
const phone = normalizePhone(payload.phone);
const existing = await db.attendee.findFirst({
where: {
groupId,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
},
});
if (existing) {
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;
}
}
}

View File

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

View File

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

View File

@@ -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<PrismaClient, 'group' | 'attendee'>;
@@ -54,7 +54,7 @@ export class MoveAttendee {
return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
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));
},
);
}

View File

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

View File

@@ -4,10 +4,11 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { toAttendeeDto } from '../../lib/helpers';
import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type UpdateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
};
type UpdateAttendeeCommand = {
@@ -26,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];
}),
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { countsAsNewStudent } from '@/modules/people/lib/people';
import {
findGroupOwnedByUser,
type GroupWaitlistEntryRecord,
@@ -11,7 +12,7 @@ import {
import { promoteWaitlistEntryRecord } from '../../lib/promote';
type PromoteGroupWaitlistEntryDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -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;
}

View File

@@ -1,15 +1,17 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders';
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers';
import { capacityReachedProblem } from '@/http/problem-builders';
import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers';
import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people';
import { type GroupWaitlistEntryRecord } from './helpers';
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>;
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry' | 'person'>;
type PromoteGroup = {
id: string;
capacity: number | null;
createdById: string;
};
export async function findFirstPendingWaitlistEntry(
@@ -23,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<PrismaClient, 'attendee'>,
group: PromoteGroup,
phone: string | null,
group: Pick<PromoteGroup, 'id' | 'capacity'>,
personId: string | null,
): Promise<Result<void, ProblemDetails>> {
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<Result<AttendeeDto, ProblemDetails>> {
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 = {

View File

@@ -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;

View File

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

View File

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

View File

@@ -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,

View File

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

View File

@@ -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 } },
},
});

View File

@@ -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(),

View File

@@ -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,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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',

View File

@@ -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,
})),
),
});
}
}

View File

@@ -1,36 +1,21 @@
import type { Prisma } from '@generated/prisma/client';
export type StudentAccessDb = {
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
};
/* The authorization rule of every student endpoint: only the attendees linked
to the session's account. Anything else is a 404 (we don't confirm ids). */
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
const links = await db.studentAccountAttendee.findMany({
// A DROPPED attendee loses access; a PAUSED one keeps it.
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
select: { attendeeId: true },
orderBy: { createdAt: 'asc' },
});
return links.map((link) => link.attendeeId);
}
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
/* One attendee of the session, with what the student screens need from the
group. null for an attendee not linked to the account (or DROPPED): routes
answer 404, the same as for an id that doesn't exist. */
/* The authorization rule of every student endpoint: an attendee (membership)
of a person linked to the session's account, with what the student screens
need from the group. The account is linked to the person, so every group
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
access): routes answer 404, the same as for an id that doesn't exist. */
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
return db.attendee.findFirst({
where: {
id: attendeeId,
status: { not: 'DROPPED' },
studentAccounts: { some: { accountId } },
person: { studentAccounts: { some: { accountId } } },
},
select: {
id: true,
fullName: true,
groupId: true,
group: {
select: {

View File

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

View File

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

View File

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

View File

@@ -38,12 +38,21 @@ function makeGroup(overrides: Record<string, unknown> = {}) {
const attendee = {
id: 'a-1',
groupId: 'group-1',
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' },

View File

@@ -56,12 +56,16 @@ const targetGroup = (overrides: Record<string, unknown> = {}) =>
const attendee = (overrides: Record<string, unknown> = {}) => ({
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();
});

View File

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

View File

@@ -15,6 +15,10 @@ const db = {
create: mock(),
count: mock(),
},
person: {
findFirst: mock(),
findMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -60,9 +64,34 @@ function makeApp(userValue: unknown) {
return app;
}
const personRow = (overrides: Record<string, unknown> = {}) => ({
id: 'person-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
...overrides,
});
const attendeeRow = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: personRow(),
notifyToken: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
describe('attendee incorporation & invite-token in groups', () => {
beforeEach(() => {
vi.clearAllMocks();
// Nobody with that phone among the teacher's people, unless a test says so.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.findMany.mockResolvedValue([]);
});
describe('GET /groups/:groupId/invite-token', () => {
@@ -109,18 +138,7 @@ describe('attendee incorporation & invite-token in groups', () => {
it('creates an attendee for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
@@ -140,20 +158,95 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(data.outcome).toBe('created');
expect(data.attendee.fullName).toBe('Martín Gómez');
expect(data.attendee.phone).toBe('+5491133445566');
expect(data.attendee.personId).toBe('person-1');
// A new person of the group owner, created with the membership.
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
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,

View File

@@ -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');
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,6 +8,7 @@ import type { FileStorage } from '@/lib/storage';
import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case';
import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case';
import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case';
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
@@ -30,7 +31,12 @@ describe.skipIf(!url)('student portal (real database)', () => {
const ids = {
user: `t-user-${suffix}`,
group: `t-group-${suffix}`,
yoga: `t-yoga-${suffix}`,
personAna: `t-p-ana-${suffix}`,
personBeto: `t-p-beto-${suffix}`,
ana: `t-ana-${suffix}`,
anaYoga: `t-ana-yoga-${suffix}`,
betoYoga: `t-beto-yoga-${suffix}`,
beto: `t-beto-${suffix}`,
accountAna: `t-acc-ana-${suffix}`,
accountBeto: `t-acc-beto-${suffix}`,
@@ -50,17 +56,29 @@ describe.skipIf(!url)('student portal (real database)', () => {
await db.group.create({
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
});
await db.group.create({
data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' },
});
await db.person.createMany({
data: [
{ id: ids.personAna, createdById: ids.user, fullName: 'Ana' },
{ id: ids.personBeto, createdById: ids.user, fullName: 'Beto' },
],
});
// Ana and Beto are in both groups.
await db.attendee.createMany({
data: [
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
{ id: ids.ana, groupId: ids.group, personId: ids.personAna },
{ id: ids.beto, groupId: ids.group, personId: ids.personBeto },
{ id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna },
{ id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto },
],
});
await db.studentAccount.create({
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } },
});
await db.studentAccount.create({
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } },
});
await db.payment.createMany({
data: [
@@ -117,6 +135,21 @@ describe.skipIf(!url)('student portal (real database)', () => {
expect(!invented.ok && invented.error.status).toBe(400);
});
it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => {
const me = await new GetStudentMe({ db }).execute(ids.accountAna);
if (!me.ok) throw new Error('me failed');
expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([
[ids.ana, 'Natación'],
[ids.anaYoga, 'Yoga'],
]);
// Her membership in the second group is reachable; Beto's in that group is not.
expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true);
const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga);
expect(foreign.ok).toBe(false);
if (!foreign.ok) expect(foreign.error.status).toBe(404);
});
it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => {
expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);

View File

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

View File

@@ -81,8 +81,8 @@ describe('create payments batch', () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([
{ id: 'att-1', fullName: 'Juana' },
{ id: 'att-2', fullName: 'Pedro' },
{ id: 'att-1', person: { fullName: 'Juana' } },
{ id: 'att-2', person: { fullName: 'Pedro' } },
]);
prisma.payment.create
.mockResolvedValueOnce({ id: 'pay-1' })
@@ -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', {

View File

@@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
paidAt: null,
createdAt: new Date('2026-10-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
attendee: { fullName: 'Juana Pérez' },
attendee: { person: { fullName: 'Juana Pérez' } },
group: {
name: 'Vinyasa',
price: { toString: () => '120.00' },
@@ -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 } },
},
});

View File

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

View File

@@ -10,6 +10,11 @@ const db = {
count: mock(),
create: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findFirst: mock(),
create: mock(),
@@ -69,12 +74,16 @@ const preRegistration = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
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',

View File

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

View File

@@ -12,6 +12,11 @@ const db = {
create: mock(),
delete: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -70,12 +75,16 @@ const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
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 },
});
});

View File

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

View File

@@ -1,6 +1,6 @@
import { useEffect, useId, useRef, useState } from 'react'
import type { KeyboardEvent, RefObject } from 'react'
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus } from 'lucide-react'
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
import { useToast } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
@@ -15,7 +15,7 @@ export function AttendeeActionsMenu({
* when it closes. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog } = useAttendeeDetail()
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
const toast = useToast()
const [isOpen, setIsOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
@@ -112,6 +112,18 @@ export function AttendeeActionsMenu({
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Cambiar de grupo
</button>
<button
type="button"
role="menuitem"
className={ITEM_CLASS}
onClick={() => {
close()
openAddToGroupDialog()
}}
>
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Agregar a otro grupo
</button>
<button
type="button"
role="menuitem"

View File

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

View File

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

View File

@@ -11,6 +11,7 @@ import type {
} from '@gruperly/shared'
import { useToast } from '../../components/ui'
import {
addAttendeeToGroup,
ApiError,
getAttendeeHistory,
getGroup,
@@ -44,16 +45,22 @@ type AttendeeDetailContextValue = {
closeRemoveDialog: () => void
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
isSubmittingRemoval: boolean
isChangeGroupDialogOpen: boolean
/** Qué diálogo de grupo está abierto: "Cambiar de grupo" o "Agregar a otro grupo". */
groupDialogMode: GroupDialogMode | null
openChangeGroupDialog: () => void
closeChangeGroupDialog: () => void
openAddToGroupDialog: () => void
closeGroupDialog: () => void
/** Grupos del profe (incluye el actual); se piden al abrir el diálogo. */
groups: GroupListItem[]
groupsPending: boolean
moveToGroup: (targetGroupId: string) => void
isMovingAttendee: boolean
addToGroup: (targetGroupId: string) => void
isAddingToGroup: boolean
}
export type GroupDialogMode = 'move' | 'add'
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
export function AttendeeDetailProvider({
@@ -69,7 +76,7 @@ export function AttendeeDetailProvider({
const queryClient = useQueryClient()
const toast = useToast()
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
const [isChangeGroupDialogOpen, setIsChangeGroupDialogOpen] = useState(false)
const [groupDialogMode, setGroupDialogMode] = useState<GroupDialogMode | null>(null)
const [isEditingContact, setIsEditingContact] = useState(false)
const groupQuery = useQuery({
@@ -91,7 +98,9 @@ export function AttendeeDetailProvider({
['group-attendee', groupId, attendeeId],
(current) => (current ? { ...current, ...updated } : current),
)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
// Los datos son de la persona: cambian también en sus otros grupos.
void queryClient.invalidateQueries({ queryKey: ['group-attendees'] })
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
},
})
@@ -127,7 +136,7 @@ export function AttendeeDetailProvider({
const groupsQuery = useQuery({
queryKey: ['groups'],
queryFn: getGroups,
enabled: isChangeGroupDialogOpen,
enabled: groupDialogMode !== null,
})
const groups = groupsQuery.data?.data ?? []
@@ -142,7 +151,7 @@ export function AttendeeDetailProvider({
}
void queryClient.invalidateQueries({ queryKey: ['groups'] })
void queryClient.invalidateQueries({ queryKey: ['attention'] })
setIsChangeGroupDialogOpen(false)
setGroupDialogMode(null)
// La ficha vive bajo el grupo: pasa a la URL del grupo nuevo sin dejar la
// vieja en el historial (ya no existe).
void navigate({
@@ -156,13 +165,38 @@ export function AttendeeDetailProvider({
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
} else if (code === 'attendee_already_registered') {
toast.error('En ese grupo ya hay un miembro con el mismo teléfono.')
toast.error('Esta persona ya es miembro de ese grupo.')
} else {
toast.error(err.message || 'No se pudo cambiar de grupo.')
}
},
})
const addToGroupMutation = useMutation({
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
onSuccess: (added, targetGroupId) => {
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${added.fullName} ahora también está en ${targetName}.`)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
// "También está en" de esta ficha (y la de sus otros grupos).
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
void queryClient.invalidateQueries({ queryKey: ['groups'] })
void queryClient.invalidateQueries({ queryKey: ['attention'] })
setGroupDialogMode(null)
},
onError: (err: Error) => {
const code = err instanceof ApiError ? err.problem?.code : undefined
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
} else if (code === 'attendee_already_registered') {
toast.error('Esta persona ya es miembro de ese grupo.')
} else {
toast.error(err.message || 'No se pudo agregar al grupo.')
}
},
})
const value: AttendeeDetailContextValue = {
groupId,
groupName: groupQuery.data?.name,
@@ -190,13 +224,16 @@ export function AttendeeDetailProvider({
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
},
isSubmittingRemoval: isRemovingAttendee,
isChangeGroupDialogOpen,
openChangeGroupDialog: () => setIsChangeGroupDialogOpen(true),
closeChangeGroupDialog: () => setIsChangeGroupDialogOpen(false),
groupDialogMode,
openChangeGroupDialog: () => setGroupDialogMode('move'),
openAddToGroupDialog: () => setGroupDialogMode('add'),
closeGroupDialog: () => setGroupDialogMode(null),
groups,
groupsPending: groupsQuery.isPending,
moveToGroup: (targetGroupId) => moveMutation.mutate(targetGroupId),
isMovingAttendee: moveMutation.isPending,
addToGroup: (targetGroupId) => addToGroupMutation.mutate(targetGroupId),
isAddingToGroup: addToGroupMutation.isPending,
}
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>

View File

@@ -10,6 +10,7 @@ import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection'
import { AttendeeNotesSection } from './AttendeeNotesSection'
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
import { OtherGroupsSection } from './OtherGroupsSection'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ChangeGroupDialog } from './ChangeGroupDialog'
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
@@ -88,6 +89,7 @@ export function AttendeeDetailView() {
<div className="mt-6">
<AttendeeContactSection />
<OtherGroupsSection />
<StudentAccessSection />
<AttendeePaymentsSection />
<AttendeeAttendanceSection />

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -69,6 +69,7 @@ import type {
TransferDetailsDto,
UpdateTransferDetails,
TeacherAbsenceNoticeList,
PersonSummary,
PromoteGroupWaitlistEntryResult,
PublicNotifyAbsence,
RejectGroupPreRegistrationResult,
@@ -323,6 +324,20 @@ export const moveGroupAttendee = (groupId: string, attendeeId: string, targetGro
body: JSON.stringify({ targetGroupId }),
})
// Suma a la misma persona a otro grupo del profe (sigue en este); devuelve la
// membresía nueva.
export const addAttendeeToGroup = (groupId: string, attendeeId: string, targetGroupId: string) =>
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/add-to-group`, {
method: 'POST',
body: JSON.stringify({ targetGroupId }),
})
// ¿Ese teléfono ya es de una persona del profe (dueño del grupo)? `null` si no.
export const lookupPerson = (groupId: string, phone: string) =>
apiFetch<PersonSummary | null>(
`/api/v1/people/lookup?groupId=${encodeURIComponent(groupId)}&phone=${encodeURIComponent(phone)}`,
)
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)

View File

@@ -1,4 +1,5 @@
import { z } from 'zod';
import { attendeeStatusSchema } from './analytics.js';
import { attendanceStatusSchema } from './attendance.js';
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
import { paymentStatusSchema } from './payments.js';
@@ -14,9 +15,12 @@ const paginationSchema = createPaginationSchema();
HISTORY_SESSIONS_LIMIT classes separately. */
export const RECENT_ATTENDANCE_LIMIT = 5;
/* An attendee is the membership of a person in one group. Contact data belongs
to the person (shared by all their groups) and travels flattened here. */
export const AttendeeDtoSchema = z.object({
id: z.string(),
groupId: z.string(),
personId: z.string(),
fullName: z.string(),
email: z.string().nullable(),
phone: z.string().nullable(),
@@ -59,8 +63,19 @@ export const AttendeePaymentSummarySchema = z.object({
});
export type AttendeePaymentSummary = z.output<typeof AttendeePaymentSummarySchema>;
/** Another group of the teacher the same person is in. */
export const PersonMembershipSchema = z.object({
attendeeId: z.string(),
groupId: z.string(),
groupName: z.string(),
status: attendeeStatusSchema,
});
export type PersonMembership = z.output<typeof PersonMembershipSchema>;
export const AttendeeDetailDtoSchema = AttendeeDtoSchema.extend({
payment: AttendeePaymentSummarySchema.nullable(),
/** The person's memberships in the teacher's other groups. */
otherGroups: z.array(PersonMembershipSchema),
});
export type AttendeeDetailDto = z.output<typeof AttendeeDetailDtoSchema>;
@@ -106,6 +121,9 @@ export const CreateAttendeeSchema = z.object({
phone: z.string().trim().min(6, 'Ingresa un número de teléfono válido'),
email: z.string().trim().email('Email inválido').optional().or(z.literal('')),
notes: z.string().trim().optional(),
/* Adds an existing person of the teacher (found by phone) instead of creating
a new one: the name/email fields are ignored then. */
personId: z.string().min(1).optional(),
});
export type CreateAttendee = z.output<typeof CreateAttendeeSchema>;
@@ -154,6 +172,8 @@ export type BulkCreateAttendees = z.output<typeof BulkCreateAttendeesSchema>;
export const BulkCreateAttendeesResultSchema = z.object({
totalProcessed: z.number().int(),
createdCount: z.number().int(),
/** Rows whose phone was already a person of the teacher: added to this group as that person. */
linkedCount: z.number().int(),
duplicatesCount: z.number().int(),
invalidCount: z.number().int(),
message: z.string(),
@@ -175,6 +195,30 @@ export const MoveAttendeeSchema = z.object({
});
export type MoveAttendee = z.output<typeof MoveAttendeeSchema>;
// Adds the same person to another group of the teacher, keeping this one.
export const AddAttendeeToGroupSchema = z.object({
targetGroupId: z.string().min(1),
});
export type AddAttendeeToGroup = z.output<typeof AddAttendeeToGroupSchema>;
/* "Ya existe esta persona": what the add form shows when the phone is already
one of the teacher's people (`GET /people/lookup?groupId=&phone=`). The
group says whose people: its owner's. */
export const PersonLookupQuerySchema = z.object({
groupId: z.string().min(1),
phone: z.string().trim().min(6),
});
export type PersonLookupQuery = z.output<typeof PersonLookupQuerySchema>;
export const PersonSummarySchema = z.object({
id: z.string(),
fullName: z.string(),
email: z.string().nullable(),
phone: z.string().nullable(),
groups: z.array(PersonMembershipSchema),
});
export type PersonSummary = z.output<typeof PersonSummarySchema>;
export const PromoteGroupWaitlistEntryResultSchema = z.object({
attendee: AttendeeDtoSchema,
});