From 5b3a035dcf1262844befb4ae77277056646cb2eb Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 11 Nov 2026 14:04:25 -0300 Subject: [PATCH] feat(student-portal): student account belongs to the adult in charge - Inviting a kid with an adult in charge links the account to the adult (a legacy account linked to the kid moves to the adult and is renamed). - `linkedPersonWhere` lets the account reach the kids of a linked adult, so the adult sees and manages all their kids, including ones added later. - /me, link info and access status follow the adult; siblings share state. - Web: greeting uses the account holder, profile lists each kid's group, and the invitation sheet/message address the adult. - DB tests for the adult account flow. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../features/get-status/use-case.ts | 10 +- .../features/invite/use-case.ts | 82 +++++++--- .../features/absences/use-case.ts | 3 +- .../features/link-info/use-case.ts | 19 ++- .../student-portal/features/me/use-case.ts | 61 +++++--- .../src/modules/student-portal/lib/access.ts | 18 ++- .../test/db/student-guardian.db.test.ts | 140 ++++++++++++++++++ .../attendee-detail/InviteToAppSheet.tsx | 19 ++- .../attendee-detail/StudentAccessSection.tsx | 1 + .../features/attendee-detail/studentAccess.ts | 17 ++- .../features/student-app/StudentHomeView.tsx | 5 +- .../student-app/StudentProfileView.tsx | 9 +- .../src/i18n/locales/en/attendeeDetail.json | 4 +- .../i18n/locales/es-419/attendeeDetail.json | 4 +- .../i18n/locales/es-AR/attendeeDetail.json | 4 +- .../i18n/locales/pt-BR/attendeeDetail.json | 4 +- 17 files changed, 336 insertions(+), 66 deletions(-) create mode 100644 apps/backend/test/db/student-guardian.db.test.ts diff --git a/AGENTS.md b/AGENTS.md index 555804a..2fc16e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,7 +70,7 @@ 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 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**. + 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). En grupos de chicos la cuenta es del **adulto a cargo** (`person_guardians`): invitar a un chico vincula al adulto (y pasa al adulto una cuenta vieja del chico), y `linkedPersonWhere` le da acceso a todos sus chicos, también a los que se sumen después, sin reinvitar. 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. diff --git a/apps/backend/src/modules/student-access/features/get-status/use-case.ts b/apps/backend/src/modules/student-access/features/get-status/use-case.ts index 1a0f8ee..c32055d 100644 --- a/apps/backend/src/modules/student-access/features/get-status/use-case.ts +++ b/apps/backend/src/modules/student-access/features/get-status/use-case.ts @@ -4,6 +4,7 @@ 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 { guardianSelect } from '@/modules/people/lib/guardians'; import { computeStudentAccess } from '../../lib/status'; type GetStudentAccessDeps = { @@ -23,9 +24,14 @@ 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: { personId: true } }); + const attendee = await db.attendee.findFirst({ + where: { id: attendeeId, groupId }, + select: { personId: true, person: { select: guardianSelect } }, + }); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); - return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date())); + // A kid with an adult in charge uses the adult's account (shared by siblings). + const ownerId = attendee.person.guardians[0]?.guardian.id ?? attendee.personId; + return ok(await computeStudentAccess(db, ownerId, this.deps.now ?? new Date())); } } diff --git a/apps/backend/src/modules/student-access/features/invite/use-case.ts b/apps/backend/src/modules/student-access/features/invite/use-case.ts index 285a8dc..36ed8ed 100644 --- a/apps/backend/src/modules/student-access/features/invite/use-case.ts +++ b/apps/backend/src/modules/student-access/features/invite/use-case.ts @@ -1,10 +1,10 @@ -import type { PrismaClient } from '@generated/prisma/client'; +import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared'; import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; import prisma, { UnitOfWork } from '@/lib/prisma'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; -import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; +import { contactPhone, guardianSelect, primaryGuardian } from '@/modules/people/lib/people'; import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; import { computeStudentAccess } from '../../lib/status'; @@ -44,30 +44,19 @@ export class InviteStudent { }); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + // The account belongs to the adult in charge when the kid has one: it + // reaches all of their kids. + const guardian = primaryGuardian(attendee.person); + const owner = guardian + ? { personId: guardian.id, fullName: guardian.fullName } + : { personId: attendee.personId, fullName: attendee.person.fullName }; + const token = generateAccessToken(); const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); const issued = await unitOfWork.executeResult(async (tx) => { - // 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 }, - }); - const accountId = - link?.accountId - ?? ( - await tx.studentAccount.create({ - data: { - name: attendee.person.fullName, - createdById: userId, - people: { create: { personId: attendee.personId } }, - }, - select: { id: true }, - }) - ).id; - + const accountId = await resolveAccount(tx, owner, userId); await tx.studentAccessToken.updateMany({ where: { accountId, usedAt: null, revokedAt: null }, data: { revokedAt: now }, @@ -96,7 +85,7 @@ export class InviteStudent { url: studentLinkUrl(token), expiresAt: expiresAt.toISOString(), whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country), - access: await computeStudentAccess(db, attendee.personId, now), + access: await computeStudentAccess(db, owner.personId, now), }); } } @@ -104,3 +93,52 @@ export class InviteStudent { function toWhatsappPhone(phone: string | null, country: string | null): string | null { return phone ? toWhatsappE164(phone, country as CountryCode | null) : null; } + +type AccountOwner = { personId: string; fullName: string }; + +/* One account per person: inviting from any of their groups (or, for an adult + in charge, from any of their kids) reuses it. Accounts made before kids + groups were linked to the kid: the oldest one of the adult's kids moves to + the adult, and the kids stop being linked one by one (they are reached + through `person_guardians`). */ +async function resolveAccount(tx: Prisma.TransactionClient, owner: AccountOwner, userId: string): Promise { + const kids = await tx.personGuardian.findMany({ where: { guardianId: owner.personId }, select: { childId: true } }); + const kidIds = kids.map((kid) => kid.childId); + + const own = await tx.studentAccountPerson.findFirst({ + where: { personId: owner.personId }, + orderBy: { createdAt: 'asc' }, + select: { accountId: true }, + }); + const legacy = + own || kidIds.length === 0 + ? null + : await tx.studentAccountPerson.findFirst({ + where: { personId: { in: kidIds } }, + orderBy: { createdAt: 'asc' }, + select: { accountId: true }, + }); + + let accountId: string; + if (own) { + accountId = own.accountId; + } else if (legacy) { + accountId = legacy.accountId; + await tx.studentAccount.update({ + where: { id: accountId }, + data: { name: owner.fullName, people: { create: { personId: owner.personId } } }, + }); + } else { + accountId = ( + await tx.studentAccount.create({ + data: { name: owner.fullName, createdById: userId, people: { create: { personId: owner.personId } } }, + select: { id: true }, + }) + ).id; + } + + if (kidIds.length > 0) { + await tx.studentAccountPerson.deleteMany({ where: { personId: { in: kidIds } } }); + } + return accountId; +} diff --git a/apps/backend/src/modules/student-portal/features/absences/use-case.ts b/apps/backend/src/modules/student-portal/features/absences/use-case.ts index d74391d..35e1a22 100644 --- a/apps/backend/src/modules/student-portal/features/absences/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/absences/use-case.ts @@ -13,6 +13,7 @@ import { occurrencesBetween } from '@/modules/home/lib/scheduler'; import { classAlreadyStartedProblem, findLinkedAttendee, + linkedPersonWhere, studentAttendeeNotFoundProblem, teacherTimeZone, } from '../../lib'; @@ -127,7 +128,7 @@ export class CancelStudentAbsence { where: { id: noticeId, cancelledAt: null, - attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } }, + attendee: { status: { not: 'DROPPED' }, person: linkedPersonWhere(accountId) }, }, select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } }, }); diff --git a/apps/backend/src/modules/student-portal/features/link-info/use-case.ts b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts index 62563a4..d1ba204 100644 --- a/apps/backend/src/modules/student-portal/features/link-info/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/link-info/use-case.ts @@ -1,4 +1,4 @@ -import type { PrismaClient } from '@generated/prisma/client'; +import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; import prisma from '@/lib/prisma'; @@ -9,6 +9,13 @@ type GetStudentLinkInfoDeps = { now?: Date; }; +const firstGroupSelect = { + where: { status: { not: 'DROPPED' } }, + orderBy: { createdAt: 'asc' }, + take: 1, + select: { group: { select: { name: true, owner: { select: { name: true } } } } }, +} satisfies Prisma.Person$attendeesArgs; + const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/; /* GET of the link: only reads, never consumes (WhatsApp previews and link @@ -38,10 +45,12 @@ export class GetStudentLinkInfo { select: { person: { select: { - attendees: { + attendees: firstGroupSelect, + // An adult in charge has no groups of their own: their kids' count. + children: { orderBy: { createdAt: 'asc' }, take: 1, - select: { group: { select: { name: true, owner: { select: { name: true } } } } }, + select: { child: { select: { attendees: firstGroupSelect } } }, }, }, }, @@ -62,7 +71,9 @@ export class GetStudentLinkInfo { return ok({ status: 'invalid' }); } - const group = row.account.people[0]?.person.attendees[0]?.group ?? null; + const person = row.account.people[0]?.person; + const group = + person?.attendees[0]?.group ?? person?.children[0]?.child.attendees[0]?.group ?? null; return ok({ status: 'valid', kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery', diff --git a/apps/backend/src/modules/student-portal/features/me/use-case.ts b/apps/backend/src/modules/student-portal/features/me/use-case.ts index f2d1a27..757ebad 100644 --- a/apps/backend/src/modules/student-portal/features/me/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/me/use-case.ts @@ -1,9 +1,44 @@ -import type { PrismaClient } from '@generated/prisma/client'; +import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { unauthorizedProblem } from '@/http/problem-details'; import prisma from '@/lib/prisma'; +const personGroupsSelect = { + fullName: true, + attendees: { + where: { status: { not: 'DROPPED' } }, + orderBy: { createdAt: 'asc' }, + select: { + id: true, + group: { select: { id: true, name: true, owner: { select: { name: true } } } }, + }, + }, +} satisfies Prisma.PersonSelect; + +type PersonGroups = Prisma.PersonGetPayload<{ select: typeof personGroupsSelect }>; + +/* One entry per membership; a kid reached twice (linked and through the adult) + shows up once. */ +function studentsOf(people: PersonGroups[]): StudentMe['students'] { + const seen = new Set(); + return people.flatMap((person) => + person.attendees.flatMap((attendee) => { + if (seen.has(attendee.id)) return []; + seen.add(attendee.id); + return [ + { + attendeeId: attendee.id, + fullName: person.fullName, + groupId: attendee.group.id, + groupName: attendee.group.name, + teacherName: attendee.group.owner.name, + }, + ]; + }), + ); +} + type StudentMeDeps = { db?: Pick; now?: Date }; export class GetStudentMe { @@ -20,21 +55,15 @@ export class GetStudentMe { pendingRecoveryEmail: true, welcomedAt: true, _count: { select: { passkeys: true } }, - // Linked people, and every group each of them is in. + // Linked people (and the kids of a linked adult in charge), and every + // group each of them is in. people: { orderBy: { createdAt: 'asc' }, select: { person: { select: { - fullName: true, - attendees: { - where: { status: { not: 'DROPPED' } }, - orderBy: { createdAt: 'asc' }, - select: { - id: true, - group: { select: { id: true, name: true, owner: { select: { name: true } } } }, - }, - }, + ...personGroupsSelect, + children: { orderBy: { createdAt: 'asc' }, select: { child: { select: personGroupsSelect } } }, }, }, }, @@ -52,15 +81,7 @@ export class GetStudentMe { hasPasskey: account._count.passkeys > 0, welcomed: account.welcomedAt !== null, }, - 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, - })), - ), + students: studentsOf(account.people.flatMap(({ person }) => [person, ...person.children.map(({ child }) => child)])), }); } } diff --git a/apps/backend/src/modules/student-portal/lib/access.ts b/apps/backend/src/modules/student-portal/lib/access.ts index 436f2ef..55e4333 100644 --- a/apps/backend/src/modules/student-portal/lib/access.ts +++ b/apps/backend/src/modules/student-portal/lib/access.ts @@ -2,17 +2,29 @@ import type { Prisma } from '@generated/prisma/client'; export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate }; +/* The people a student account reaches: the ones linked to it and the kids of + a linked adult in charge (kids groups). Kids are not linked one by one, so a + kid added later shows up without a new invitation. */ +export function linkedPersonWhere(accountId: string): Prisma.PersonWhereInput { + return { + OR: [ + { studentAccounts: { some: { accountId } } }, + { guardians: { some: { guardian: { studentAccounts: { some: { accountId } } } } } }, + ], + }; +} + /* 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 + need from the group. The account is linked to the person (or to their adult + in charge), 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' }, - person: { studentAccounts: { some: { accountId } } }, + person: linkedPersonWhere(accountId), }, select: { id: true, diff --git a/apps/backend/test/db/student-guardian.db.test.ts b/apps/backend/test/db/student-guardian.db.test.ts new file mode 100644 index 0000000..b7ffbd2 --- /dev/null +++ b/apps/backend/test/db/student-guardian.db.test.ts @@ -0,0 +1,140 @@ +/* Kids groups against a real Postgres: the student account belongs to the + adult in charge and reaches all of their kids. Skipped unless DB_TESTS=1 + (`bun run test:db`). Creates its own teacher/groups/people and deletes them. */ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; +import { PrismaClient } from '@generated/prisma/client'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case'; +import { InviteStudent } from '@/modules/student-access/features/invite/use-case'; +import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case'; +import { GetStudentMe } from '@/modules/student-portal/features/me/use-case'; +import { findLinkedAttendee } from '@/modules/student-portal/lib/access'; + +const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; +const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + +describe.skipIf(!url)('cuenta del adulto a cargo (real database)', () => { + let db: PrismaClient; + let unitOfWork: { executeResult: unknown }; + const ids = { + user: `test-user-${suffix}`, + swim: `test-swim-${suffix}`, + art: `test-art-${suffix}`, + ana: `test-ana-${suffix}`, + juan: `test-juan-${suffix}`, + sofi: `test-sofi-${suffix}`, + tomi: `test-tomi-${suffix}`, + other: `test-other-${suffix}`, + juanSwim: `test-juan-swim-${suffix}`, + sofiArt: `test-sofi-art-${suffix}`, + tomiArt: `test-tomi-art-${suffix}`, + otherSwim: `test-other-swim-${suffix}`, + }; + + beforeAll(async () => { + db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); + unitOfWork = { + executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => { + const rollback = Symbol('rollback'); + try { + return await db.$transaction(async (tx) => { + const result = await callback(tx); + if (!result.ok) throw { [rollback]: result }; + return result; + }); + } catch (error) { + if (error && typeof error === 'object' && rollback in error) { + return (error as Record)[rollback]; + } + throw error; + } + }) as never, + }; + await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } }); + await db.group.create({ data: { id: ids.swim, name: 'Natación', audience: 'KIDS', createdById: ids.user } }); + await db.group.create({ data: { id: ids.art, name: 'Plástica', audience: 'KIDS', createdById: ids.user } }); + await db.person.create({ data: { id: ids.ana, createdById: ids.user, fullName: 'Ana Pérez', phone: `11${suffix.slice(-8)}` } }); + for (const [id, fullName] of [ + [ids.juan, 'Juan Pérez'], + [ids.sofi, 'Sofi Pérez'], + ] as const) { + await db.person.create({ + data: { id, createdById: ids.user, fullName, guardians: { create: { guardianId: ids.ana } } }, + }); + } + await db.person.create({ data: { id: ids.other, createdById: ids.user, fullName: 'Otro Chico' } }); + await db.attendee.create({ data: { id: ids.juanSwim, groupId: ids.swim, personId: ids.juan } }); + await db.attendee.create({ data: { id: ids.sofiArt, groupId: ids.art, personId: ids.sofi } }); + await db.attendee.create({ data: { id: ids.otherSwim, groupId: ids.swim, personId: ids.other } }); + + // A legacy account linked to the kid (before kids groups). + await db.studentAccount.create({ + data: { name: 'Juan Pérez', createdById: ids.user, people: { create: { personId: ids.juan } } }, + }); + }); + + afterAll(async () => { + await db.studentAccount.deleteMany({ where: { createdById: ids.user } }); + await db.user.deleteMany({ where: { id: ids.user } }); + await db.$disconnect(); + }); + + const invite = (groupId: string, attendeeId: string) => + new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(groupId, attendeeId, ids.user); + const accountOf = async (personId: string) => + (await db.studentAccountPerson.findFirst({ where: { personId } }))?.accountId ?? null; + + it('invitar a un chico pasa su cuenta vieja al adulto', async () => { + const legacy = await accountOf(ids.juan); + const result = await invite(ids.swim, ids.juanSwim); + if (!result.ok) throw new Error('invite failed'); + + expect(await accountOf(ids.ana)).toBe(legacy); + expect(await accountOf(ids.juan)).toBeNull(); + const account = await db.studentAccount.findUniqueOrThrow({ where: { id: legacy as string } }); + expect(account.name).toBe('Ana Pérez'); + + const token = result.value.url.split('/i/')[1] as string; + expect(await new GetStudentLinkInfo({ db }).execute(token)).toMatchObject({ + ok: true, + value: { status: 'valid', name: 'Ana Pérez', groupName: 'Natación' }, + }); + }); + + it('invitar a un hermano reutiliza la cuenta del adulto', async () => { + const accountId = await accountOf(ids.ana); + const result = await invite(ids.art, ids.sofiArt); + if (!result.ok) throw new Error('invite failed'); + expect(await db.studentAccountPerson.count({ where: { personId: ids.ana } })).toBe(1); + expect(await accountOf(ids.ana)).toBe(accountId); + + const juan = await new GetStudentAccess({ db }).execute(ids.swim, ids.juanSwim, ids.user); + const sofi = await new GetStudentAccess({ db }).execute(ids.art, ids.sofiArt, ids.user); + expect(juan).toMatchObject({ ok: true, value: { status: 'invited' } }); + expect(sofi).toEqual(juan); + }); + + it('la cuenta del adulto ve a todos sus chicos, también uno nuevo, y a nadie más', async () => { + const accountId = (await accountOf(ids.ana)) as string; + + // A kid added after the invitation shows up without reinviting. + await db.person.create({ + data: { id: ids.tomi, createdById: ids.user, fullName: 'Tomi Pérez', guardians: { create: { guardianId: ids.ana } } }, + }); + await db.attendee.create({ data: { id: ids.tomiArt, groupId: ids.art, personId: ids.tomi } }); + + const me = await new GetStudentMe({ db }).execute(accountId); + if (!me.ok) throw new Error('me failed'); + expect(me.value.account.name).toBe('Ana Pérez'); + expect(me.value.students.map((s) => [s.fullName, s.groupName])).toEqual([ + ['Juan Pérez', 'Natación'], + ['Sofi Pérez', 'Plástica'], + ['Tomi Pérez', 'Plástica'], + ]); + + for (const attendeeId of [ids.juanSwim, ids.sofiArt, ids.tomiArt]) { + expect(await findLinkedAttendee(db, accountId, attendeeId)).not.toBeNull(); + } + expect(await findLinkedAttendee(db, accountId, ids.otherSwim)).toBeNull(); + }); +}); diff --git a/apps/web/src/features/attendee-detail/InviteToAppSheet.tsx b/apps/web/src/features/attendee-detail/InviteToAppSheet.tsx index e2b5989..55ef22d 100644 --- a/apps/web/src/features/attendee-detail/InviteToAppSheet.tsx +++ b/apps/web/src/features/attendee-detail/InviteToAppSheet.tsx @@ -16,6 +16,8 @@ type InviteToAppSheetProps = { groupName: string attendeeId: string fullName: string + /** Kids groups: the account (and the message) belong to the adult in charge. */ + guardianName?: string | null hasPhone: boolean /** Reinviting closes the current access: the copy says so. */ reinvite: boolean @@ -31,6 +33,7 @@ export function InviteToAppSheet({ groupName, attendeeId, fullName, + guardianName, hasPhone, reinvite, }: InviteToAppSheetProps) { @@ -39,6 +42,7 @@ export function InviteToAppSheet({ const [invitation, setInvitation] = useState(null) const [copied, setCopied] = useState(false) const firstName = fullName.split(' ')[0] ?? fullName + const guardianFirstName = guardianName ? (guardianName.split(' ')[0] ?? guardianName) : null const mutation = useMutation({ mutationFn: () => inviteStudent(groupId, attendeeId), @@ -63,7 +67,7 @@ export function InviteToAppSheet({ const popup = window.open('', '_blank') try { const result = await ensureInvitation() - const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url)) + const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url, guardianFirstName)) const target = result.whatsappPhone ? `https://wa.me/${result.whatsappPhone.replace(/\D/g, '')}?text=${text}` : `https://wa.me/?text=${text}` @@ -91,7 +95,12 @@ export function InviteToAppSheet({ } } - const preview = invitationMessage(firstName, groupName, invitation?.url ?? t('inviteSheet.linkPlaceholder')) + const preview = invitationMessage( + firstName, + groupName, + invitation?.url ?? t('inviteSheet.linkPlaceholder'), + guardianFirstName, + ) return (
diff --git a/apps/web/src/features/attendee-detail/StudentAccessSection.tsx b/apps/web/src/features/attendee-detail/StudentAccessSection.tsx index e389228..3109fe7 100644 --- a/apps/web/src/features/attendee-detail/StudentAccessSection.tsx +++ b/apps/web/src/features/attendee-detail/StudentAccessSection.tsx @@ -76,6 +76,7 @@ export function StudentAccessSection() { groupName={groupName ?? t('access.yourGroup')} attendeeId={attendee.id} fullName={attendee.fullName} + guardianName={attendee.guardianName} hasPhone={hasPhone} reinvite={invited} /> diff --git a/apps/web/src/features/attendee-detail/studentAccess.ts b/apps/web/src/features/attendee-detail/studentAccess.ts index 24e7bf6..6a1e64f 100644 --- a/apps/web/src/features/attendee-detail/studentAccess.ts +++ b/apps/web/src/features/attendee-detail/studentAccess.ts @@ -38,6 +38,19 @@ export function formatSince(iso: string): string { return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' }) } -export function invitationMessage(firstName: string, groupName: string, url: string): string { - return i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url }) +/* With an adult in charge the message goes to the adult, about the kid. */ +export function invitationMessage( + firstName: string, + groupName: string, + url: string, + guardianFirstName?: string | null, +): string { + return guardianFirstName + ? i18n.t('attendeeDetail:inviteSheet.messageGuardian', { + guardian: guardianFirstName, + name: firstName, + group: groupName, + url, + }) + : i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url }) } diff --git a/apps/web/src/features/student-app/StudentHomeView.tsx b/apps/web/src/features/student-app/StudentHomeView.tsx index 4d466a9..e4ed322 100644 --- a/apps/web/src/features/student-app/StudentHomeView.tsx +++ b/apps/web/src/features/student-app/StudentHomeView.tsx @@ -9,7 +9,7 @@ import { WeekClassesList } from './WeekClassesList' import { useTranslation } from 'react-i18next' export function StudentHomeView() { - const { student, classes, classesPending, fees } = useStudentApp() + const { me, student, classes, classesPending, fees } = useStudentApp() const { t } = useTranslation(['student', 'common']) if (!student) return null @@ -20,7 +20,8 @@ export function StudentHomeView() { return (
-

{t('home.greeting', { name: firstName(student.fullName) })}

+ {/* The account holder: the student, or the adult in charge of several kids. */} +

{t('home.greeting', { name: firstName(me?.account.name ?? student.fullName) })}

{fees ? : null} diff --git a/apps/web/src/features/student-app/StudentProfileView.tsx b/apps/web/src/features/student-app/StudentProfileView.tsx index 707d10f..535be3d 100644 --- a/apps/web/src/features/student-app/StudentProfileView.tsx +++ b/apps/web/src/features/student-app/StudentProfileView.tsx @@ -20,7 +20,14 @@ export function StudentProfileView() {

{me.account.name}

- {me.students.map((student) => `${student.groupName} · ${student.teacherName}`).join(' / ')} + {me.students + .map((student) => + // An adult in charge sees whose group each one is. + student.fullName === me.account.name + ? `${student.groupName} · ${student.teacherName}` + : `${student.fullName} · ${student.groupName}`, + ) + .join(' / ')}

diff --git a/apps/web/src/i18n/locales/en/attendeeDetail.json b/apps/web/src/i18n/locales/en/attendeeDetail.json index 6f66233..f38464f 100644 --- a/apps/web/src/i18n/locales/en/attendeeDetail.json +++ b/apps/web/src/i18n/locales/en/attendeeDetail.json @@ -58,6 +58,7 @@ "title": "Invite to the app", "descriptionReinvite": "Send {{name}} a new link. The previous access stops working.", "description": "{{name}} will be able to report absences, report payments and see their upcoming classes. No passwords or new details.", + "descriptionGuardian": "{{guardian}} will be able to report absences, report payments and see the classes of {{name}} and their other kids. No passwords or new details.", "preview": "Message preview", "linkPlaceholder": "🔗 personal link", "security": "The link is personal, works only once and expires in 72 hours. The first phone that opens it stays connected.", @@ -65,7 +66,8 @@ "sendWhatsapp": "Send on WhatsApp", "copied": "Link copied", "copy": "Copy link", - "message": "Hi {{name}}! I'm inviting you to gruperly to report absences and payments for {{group}}. {{url}}" + "message": "Hi {{name}}! I'm inviting you to gruperly to report absences and payments for {{group}}. {{url}}", + "messageGuardian": "Hi {{guardian}}! I'm inviting you to gruperly to report absences and payments for {{name}} in {{group}}. {{url}}" }, "payments": { "title": "Payments", diff --git a/apps/web/src/i18n/locales/es-419/attendeeDetail.json b/apps/web/src/i18n/locales/es-419/attendeeDetail.json index 7a0c42c..ac55432 100644 --- a/apps/web/src/i18n/locales/es-419/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-419/attendeeDetail.json @@ -58,6 +58,7 @@ "title": "Invitar a la app", "descriptionReinvite": "Envíale un link nuevo a {{name}}. El acceso anterior deja de funcionar.", "description": "{{name}} podrá avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.", + "descriptionGuardian": "{{guardian}} podrá avisar faltas, informar pagos y ver las clases de {{name}} y del resto de sus hijos. Sin contraseñas ni datos nuevos.", "preview": "Vista previa del mensaje", "linkPlaceholder": "🔗 link personal", "security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.", @@ -65,7 +66,8 @@ "sendWhatsapp": "Enviar por WhatsApp", "copied": "Link copiado", "copy": "Copiar link", - "message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}" + "message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}", + "messageGuardian": "¡Hola {{guardian}}! Te invito a gruperly para avisar faltas e informar pagos de {{name}} en {{group}}. {{url}}" }, "payments": { "title": "Cobros", diff --git a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json index 1007b39..67128f6 100644 --- a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json @@ -58,6 +58,7 @@ "title": "Invitar a la app", "descriptionReinvite": "Mandale un link nuevo a {{name}}. El acceso anterior deja de funcionar.", "description": "{{name}} va a poder avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.", + "descriptionGuardian": "{{guardian}} va a poder avisar faltas, informar pagos y ver las clases de {{name}} y del resto de sus chicos. Sin contraseñas ni datos nuevos.", "preview": "Vista previa del mensaje", "linkPlaceholder": "🔗 link personal", "security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.", @@ -65,7 +66,8 @@ "sendWhatsapp": "Enviar por WhatsApp", "copied": "Link copiado", "copy": "Copiar link", - "message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}" + "message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}", + "messageGuardian": "¡Hola {{guardian}}! Te invito a gruperly para avisar faltas e informar pagos de {{name}} en {{group}}. {{url}}" }, "payments": { "title": "Cobros", diff --git a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json index 0f7abbf..6808279 100644 --- a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json @@ -58,6 +58,7 @@ "title": "Convidar para o app", "descriptionReinvite": "Envie um novo link para {{name}}. O acesso anterior deixa de funcionar.", "description": "{{name}} vai poder avisar faltas, informar pagamentos e ver as próximas aulas. Sem senhas nem dados novos.", + "descriptionGuardian": "{{guardian}} vai poder avisar faltas, informar pagamentos e ver as aulas de {{name}} e dos outros filhos. Sem senhas nem dados novos.", "preview": "Prévia da mensagem", "linkPlaceholder": "🔗 link pessoal", "security": "O link é pessoal, vale uma única vez e vence em 72 horas. Fica conectado o primeiro celular que abrir.", @@ -65,7 +66,8 @@ "sendWhatsapp": "Enviar pelo WhatsApp", "copied": "Link copiado", "copy": "Copiar link", - "message": "Olá, {{name}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{group}}. {{url}}" + "message": "Olá, {{name}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{group}}. {{url}}", + "messageGuardian": "Olá, {{guardian}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{name}} em {{group}}. {{url}}" }, "payments": { "title": "Cobranças",