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:
@@ -0,0 +1,148 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
CreateAbsenceNotices,
|
||||
CreateAbsenceNoticesResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { validationProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { absenceReleaseHours, registerAbsence } from '@/modules/classes/lib';
|
||||
import { occurrencesBetween } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
classAlreadyStartedProblem,
|
||||
findLinkedAttendee,
|
||||
studentAttendeeNotFoundProblem,
|
||||
teacherTimeZone,
|
||||
} from '../../lib';
|
||||
import { ABSENCE_REASON_TO_DB, horizonEnd } from '../classes/use-case';
|
||||
|
||||
type AbsenceDb = Pick<
|
||||
PrismaClient,
|
||||
'attendee' | 'classSession' | 'absenceNotice' | 'attendance' | 'slotRelease'
|
||||
>;
|
||||
|
||||
type AbsenceDeps = {
|
||||
db?: AbsenceDb;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: Date;
|
||||
releaseHours?: number;
|
||||
};
|
||||
|
||||
/* "No voy a ir": only before the class starts, only for real classes of the
|
||||
attendee's group. Each class goes through the same `registerAbsence` the
|
||||
teacher and the old absence link use (EXCUSED + spot release), so an excused
|
||||
absence doesn't count for the attendance risk rules. Classes already
|
||||
notified are skipped (idempotent). */
|
||||
export class NotifyStudentAbsences {
|
||||
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
accountId: string,
|
||||
input: CreateAbsenceNotices,
|
||||
): Promise<Result<CreateAbsenceNoticesResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
|
||||
const timeZone = teacherTimeZone(attendee.group.owner.country);
|
||||
const valid = new Set(
|
||||
occurrencesBetween({
|
||||
days: attendee.group.days,
|
||||
time: attendee.group.time,
|
||||
from: now,
|
||||
to: horizonEnd(now),
|
||||
timeZone,
|
||||
}).map((date) => date.getTime()),
|
||||
);
|
||||
|
||||
const requested = [...new Set(input.startsAt.map((value) => new Date(value).getTime()))];
|
||||
for (const time of requested) {
|
||||
if (time <= now.getTime()) return err(classAlreadyStartedProblem());
|
||||
if (!valid.has(time)) {
|
||||
return err(validationProblem({ detail: 'Una de las clases elegidas no es del grupo.' }));
|
||||
}
|
||||
}
|
||||
|
||||
const notified: CreateAbsenceNoticesResult['notified'] = [];
|
||||
for (const time of requested.sort((a, b) => a - b)) {
|
||||
const startsAt = new Date(time);
|
||||
const session = await db.classSession.upsert({
|
||||
where: { groupId_startsAt: { groupId: attendee.groupId, startsAt } },
|
||||
create: { groupId: attendee.groupId, startsAt },
|
||||
update: {},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const existing = await db.absenceNotice.findFirst({
|
||||
where: { attendeeId: attendee.id, classSessionId: session.id, cancelledAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) continue;
|
||||
|
||||
const registered = await registerAbsence(
|
||||
{ db, unitOfWork },
|
||||
{
|
||||
attendeeId: attendee.id,
|
||||
classSessionId: session.id,
|
||||
now,
|
||||
releaseHours: this.deps.releaseHours ?? absenceReleaseHours(),
|
||||
},
|
||||
);
|
||||
if (!registered.ok) return registered;
|
||||
|
||||
const notice = await db.absenceNotice.create({
|
||||
data: {
|
||||
attendeeId: attendee.id,
|
||||
classSessionId: session.id,
|
||||
accountId,
|
||||
reason: input.reason ? ABSENCE_REASON_TO_DB[input.reason] : null,
|
||||
message: input.message || null,
|
||||
createdAt: now,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
notified.push({ id: notice.id, startsAt: startsAt.toISOString() });
|
||||
}
|
||||
|
||||
return ok({ notified });
|
||||
}
|
||||
}
|
||||
|
||||
/* "Deshacer": while the class hasn't started. Undoes what the notice did: the
|
||||
EXCUSED mark and the released spot, if nobody claimed it. */
|
||||
export class CancelStudentAbsence {
|
||||
constructor(private readonly deps: AbsenceDeps = {}) {}
|
||||
|
||||
async execute(accountId: string, noticeId: string): Promise<Result<{ id: string }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const notice = await db.absenceNotice.findFirst({
|
||||
where: {
|
||||
id: noticeId,
|
||||
cancelledAt: null,
|
||||
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||
});
|
||||
if (!notice) return err(studentAttendeeNotFoundProblem());
|
||||
if (notice.classSession.startsAt <= now) return err(classAlreadyStartedProblem());
|
||||
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
await tx.absenceNotice.update({ where: { id: notice.id }, data: { cancelledAt: now } });
|
||||
await tx.attendance.deleteMany({
|
||||
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, status: 'EXCUSED' },
|
||||
});
|
||||
await tx.slotRelease.deleteMany({
|
||||
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, isClaimed: false },
|
||||
});
|
||||
return ok({ id: notice.id });
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user