Files
gruperly/apps/backend/src/modules/student-portal/features/absences/use-case.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

149 lines
5.3 KiB
TypeScript

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' }, person: { 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 });
});
}
}