feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)

- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo
  atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys
  opcionales (SimpleWebAuthn) y mail de recuperación con rate limit.
- Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta,
  pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil.
- Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar),
  "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de
  grupo y datos para transferir en Ajustes.
- "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas.
- Zona horaria por defecto: Buenos Aires.
- Migración add_student_access, tests contra Postgres real (test:db) y docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-28 15:39:09 -03:00
parent b99bc4d519
commit 060a4f09e4
146 changed files with 7994 additions and 32 deletions

View File

@@ -0,0 +1,101 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
import { computeStudentAccess } from '../../lib/status';
type InviteStudentDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
now?: Date;
};
/* "Invitar" / "Reinvitar": reinviting restarts the access. It revokes every
pending link and every session and removes the passkeys (a lost phone must not
keep a way in), then issues a fresh 72 h single-use link. The welcome screen
shows again on the next sign-in so the student can add a passkey back. The
raw token only leaves here, inside the URL: the database keeps its hash. */
export class InviteStudent {
constructor(private readonly deps: InviteStudentDeps = {}) {}
async execute(
groupId: string,
attendeeId: string,
userId: string,
): Promise<Result<StudentInvitationDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: {
id: true,
fullName: true,
phone: true,
guardianPhone: true,
group: { select: { owner: { select: { country: true } } } },
},
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
const token = generateAccessToken();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const issued = await unitOfWork.executeResult(async (tx) => {
const link = await tx.studentAccountAttendee.findFirst({
where: { attendeeId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
const accountId =
link?.accountId
?? (
await tx.studentAccount.create({
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
select: { id: true },
})
).id;
await tx.studentAccessToken.updateMany({
where: { accountId, usedAt: null, revokedAt: null },
data: { revokedAt: now },
});
await tx.studentSession.updateMany({
where: { accountId, revokedAt: null },
data: { revokedAt: now },
});
await tx.studentPasskey.deleteMany({ where: { accountId } });
await tx.studentAccount.update({ where: { id: accountId }, data: { welcomedAt: null } });
await tx.studentAccessToken.create({
data: {
accountId,
kind: 'INVITATION',
tokenHash: hashToken(token),
expiresAt,
createdById: userId,
createdAt: now,
},
});
return ok(accountId);
});
if (!issued.ok) return issued;
return ok({
url: studentLinkUrl(token),
expiresAt: expiresAt.toISOString(),
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
access: await computeStudentAccess(db, attendeeId, now),
});
}
}
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
}