- 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>
143 lines
4.6 KiB
TypeScript
143 lines
4.6 KiB
TypeScript
import type { PrismaClient } from '@generated/prisma/client';
|
|
import type {
|
|
AttendanceStatus,
|
|
ProblemDetails,
|
|
Result,
|
|
StudentAtRisk,
|
|
StudentsAtRisk,
|
|
} 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';
|
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
|
|
|
type GetStudentsAtRiskDeps = {
|
|
db?: AnalyticsAccessDb & StudentsAtRiskDb;
|
|
now?: Date;
|
|
};
|
|
|
|
type AttendanceStreamRow = {
|
|
attendeeId: string;
|
|
classSessionId: string;
|
|
status: AttendanceStatus;
|
|
classSession: { startsAt: Date };
|
|
};
|
|
|
|
export class GetStudentsAtRisk {
|
|
constructor(private readonly deps: GetStudentsAtRiskDeps = {}) {}
|
|
|
|
async execute(
|
|
groupId: string,
|
|
userId: string,
|
|
): Promise<Result<StudentsAtRisk, 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 atRisk = await findStudentsAtRisk(db, groupId, now);
|
|
|
|
return ok({
|
|
groupName: access.value.name,
|
|
data: atRisk,
|
|
});
|
|
}
|
|
}
|
|
|
|
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
|
|
|
/**
|
|
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
|
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
|
|
* with the same domain rule as the group listing and Home
|
|
* (`summarizeMemberAttendance`), so every screen agrees on who is at risk.
|
|
* Does not check access: callers do.
|
|
*/
|
|
export async function findStudentsAtRisk(
|
|
db: StudentsAtRiskDb,
|
|
groupId: string,
|
|
now: Date,
|
|
): Promise<StudentAtRisk[]> {
|
|
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
|
|
|
const [windowSessions, attendees, attendances] = await Promise.all([
|
|
db.classSession.findMany({
|
|
where: { groupId, startsAt: { gte: since } },
|
|
select: { id: true, startsAt: true },
|
|
orderBy: { startsAt: 'desc' },
|
|
}),
|
|
db.attendee.findMany({
|
|
where: { groupId, status: 'ACTIVE' },
|
|
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
|
}).then((rows) => rows.map(flattenPerson)),
|
|
db.attendance.findMany({
|
|
where: { attendee: { groupId } },
|
|
select: {
|
|
attendeeId: true,
|
|
classSessionId: true,
|
|
status: true,
|
|
classSession: { select: { startsAt: true } },
|
|
},
|
|
orderBy: { classSession: { startsAt: 'desc' } },
|
|
}),
|
|
]);
|
|
|
|
const totalWindowSessions = windowSessions.length;
|
|
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
|
|
|
const atRisk: StudentAtRisk[] = [];
|
|
for (const attendee of attendees) {
|
|
const rows = streamByAttendee.get(attendee.id) ?? [];
|
|
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
|
|
const riskLevel = toRiskLevel(signals.level);
|
|
if (!riskLevel) {
|
|
continue;
|
|
}
|
|
// Display only: the verdict is the domain's. The rate keeps counting
|
|
// unrecorded classes as missed, which is what "asistencia mensual" says.
|
|
const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
|
|
const consecutiveAbsences = signals.consecutiveAbsences;
|
|
const attendedAt = lastAttendedAt(stream);
|
|
const monthlyRate = monthlyAttendanceRate(
|
|
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
|
totalWindowSessions,
|
|
);
|
|
atRisk.push({
|
|
attendeeId: attendee.id,
|
|
fullName: attendee.fullName,
|
|
phone: attendee.phone,
|
|
riskLevel,
|
|
consecutiveAbsences,
|
|
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
|
monthlyAttendanceRate: monthlyRate,
|
|
});
|
|
}
|
|
|
|
atRisk.sort((a, b) => {
|
|
if (a.riskLevel !== b.riskLevel) {
|
|
return a.riskLevel === 'HIGH' ? -1 : 1;
|
|
}
|
|
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
|
|
return b.consecutiveAbsences - a.consecutiveAbsences;
|
|
}
|
|
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
|
|
});
|
|
|
|
return atRisk;
|
|
}
|
|
|
|
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
|
|
const byAttendee = new Map<string, AttendanceStreamRow[]>();
|
|
for (const row of rows) {
|
|
const list = byAttendee.get(row.attendeeId) ?? [];
|
|
list.push(row);
|
|
byAttendee.set(row.attendeeId, list);
|
|
}
|
|
return byAttendee;
|
|
} |