feat: una sola regla de riesgo y preinscripciones pendientes en Inicio
- Estadísticas ("Alumnos en riesgo") y el job de reenganche usan la misma
regla de dominio que la lista de grupos e Inicio
(summarizeMemberAttendance). El armado del historial por alumno vive en
analytics/lib/member-attendance.ts y se borra el clasificador viejo
(racha o asistencia mensual < 50%).
- El badge de alumnos en riesgo muestra el motivo real (faltas seguidas,
días sin venir o asistencia en baja).
- GET /home devuelve pendingPreRegistrations por grupo (en la misma
consulta de grupos) y "Para atender" las lista con link a la ficha en
la pestaña Pendientes (?section=pending).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,30 +4,21 @@ import type {
|
|||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
GroupRiskSummary,
|
GroupRiskSummary,
|
||||||
GroupsRiskOverview,
|
GroupsRiskOverview,
|
||||||
MemberClassSession,
|
|
||||||
ProblemDetails,
|
ProblemDetails,
|
||||||
Result,
|
Result,
|
||||||
UrgentMemberSummary,
|
UrgentMemberSummary,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
|
import {
|
||||||
|
ATTENDANCE_RISK_RULES,
|
||||||
|
getGroupAttendanceSummary,
|
||||||
|
ok,
|
||||||
|
URGENT_MEMBERS_LIMIT,
|
||||||
|
} from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import {
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
classifyRisk,
|
|
||||||
MIN_RISK_ABSENCE_STREAK,
|
|
||||||
MIN_RISK_MONTHLY_RATE,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '../../lib/risk';
|
|
||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
/* How many classes we look back per attendee. That is the real ceiling of the
|
|
||||||
model: `class_sessions` are not created on their own, they get materialized
|
|
||||||
when someone opens "today's classes", so pulling years of rows makes no
|
|
||||||
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
|
|
||||||
the attendance rate the card shows. */
|
|
||||||
const MEMBER_HISTORY_LIMIT = 20;
|
|
||||||
|
|
||||||
type GetGroupsRiskOverviewDeps = {
|
type GetGroupsRiskOverviewDeps = {
|
||||||
db?: {
|
db?: {
|
||||||
group: Prisma.GroupDelegate;
|
group: Prisma.GroupDelegate;
|
||||||
@@ -54,10 +45,10 @@ type AttendanceRow = {
|
|||||||
classSession: { startsAt: Date };
|
classSession: { startsAt: Date };
|
||||||
};
|
};
|
||||||
|
|
||||||
// Risk status light summary per group for the group listing.
|
// Risk summary per group for the group listing and Home. Everything comes from
|
||||||
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
|
// the domain rule (`getGroupAttendanceSummary`): the status light is the worst
|
||||||
// any is at medium risk and NONE otherwise. The counters state the reason
|
// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
|
||||||
// (consecutive absences or low attendance) so the listing can name it.
|
// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
|
||||||
export class GetGroupsRiskOverview {
|
export class GetGroupsRiskOverview {
|
||||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||||
|
|
||||||
@@ -117,75 +108,31 @@ export class GetGroupsRiskOverview {
|
|||||||
|
|
||||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||||
|
|
||||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
const items: GroupRiskSummary[] = groups.map((group) =>
|
||||||
// Why there is risk, computed in the same pass: a member with an absence
|
buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
|
||||||
// streak counts in the first counter and only there; the second one
|
);
|
||||||
// groups the members that don't reach a streak and are still below the
|
|
||||||
// attendance minimum.
|
|
||||||
const absenceStreakCountByGroup = new Map<string, number>();
|
|
||||||
const lowAttendanceCountByGroup = new Map<string, number>();
|
|
||||||
|
|
||||||
for (const attendee of attendees) {
|
|
||||||
const groupId = attendee.groupId;
|
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
|
||||||
status: row.status,
|
|
||||||
occurredAt: row.classSession.startsAt,
|
|
||||||
}));
|
|
||||||
const streak = trailingAbsentStreak(stream);
|
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
|
||||||
sessionsByGroup.get(groupId)?.length ?? 0,
|
|
||||||
);
|
|
||||||
const riskLevel = classifyRisk(streak, monthlyRate);
|
|
||||||
if (!riskLevel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (streak >= MIN_RISK_ABSENCE_STREAK) {
|
|
||||||
bump(absenceStreakCountByGroup, groupId);
|
|
||||||
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
|
||||||
bump(lowAttendanceCountByGroup, groupId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
|
|
||||||
if (
|
|
||||||
riskLevel === 'HIGH' ||
|
|
||||||
(riskLevel === 'MEDIUM' && current === 'NONE')
|
|
||||||
) {
|
|
||||||
worstRiskByGroup.set(groupId, riskLevel);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const items: GroupRiskSummary[] = groups.map((group) => ({
|
|
||||||
groupId: group.id,
|
|
||||||
groupName: group.name,
|
|
||||||
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
|
|
||||||
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
|
|
||||||
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
|
|
||||||
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
|
|
||||||
}));
|
|
||||||
|
|
||||||
return ok({ items });
|
return ok({ items });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The per-level summary consumed by the listing card and the Home follow-up
|
* The per-level summary consumed by the listing card and Home. It comes from
|
||||||
* section. It comes from `getGroupAttendanceSummary`, the same domain function
|
* `getGroupAttendanceSummary`, the same domain function that
|
||||||
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
* `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||||
* copies: one here and another in the client.
|
* copies: one here and another in the client.
|
||||||
*
|
*
|
||||||
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
||||||
* summary counts the group members and the card needs the capacity slots to
|
* summary counts the group members and the card needs the capacity slots to
|
||||||
* paint the indicator.
|
* paint the indicator.
|
||||||
*/
|
*/
|
||||||
function buildSummaryFields(
|
function buildSummary(
|
||||||
group: GroupRow,
|
group: GroupRow,
|
||||||
attendees: AttendeeRow[],
|
attendees: AttendeeRow[],
|
||||||
sessionsByGroup: Map<string, SessionRow[]>,
|
sessionsByGroup: Map<string, SessionRow[]>,
|
||||||
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
||||||
now: Date,
|
now: Date,
|
||||||
) {
|
): GroupRiskSummary {
|
||||||
const resumen = getGroupAttendanceSummary({
|
const resumen = getGroupAttendanceSummary({
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
capacity: group.capacity,
|
capacity: group.capacity,
|
||||||
@@ -193,35 +140,23 @@ function buildSummaryFields(
|
|||||||
now,
|
now,
|
||||||
members: attendees
|
members: attendees
|
||||||
.filter((attendee) => attendee.groupId === group.id)
|
.filter((attendee) => attendee.groupId === group.id)
|
||||||
.map((attendee) => {
|
.map((attendee) =>
|
||||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
toMemberAttendance(
|
||||||
// If the attendee has attendances before their enrollment date in the
|
attendee,
|
||||||
// DB (e.g. created today but with past classes already recorded), their
|
sessionsByGroup.get(group.id) ?? [],
|
||||||
// effective join date is the first class they were marked for.
|
attendanceByAttendee.get(attendee.id) ?? [],
|
||||||
const earliestAttendance = attendeeAttendances.reduce<Date | null>(
|
),
|
||||||
(earliest, att) =>
|
),
|
||||||
!earliest || att.classSession.startsAt < earliest
|
|
||||||
? att.classSession.startsAt
|
|
||||||
: earliest,
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const enrolledAt =
|
|
||||||
earliestAttendance && earliestAttendance < attendee.createdAt
|
|
||||||
? earliestAttendance
|
|
||||||
: attendee.createdAt;
|
|
||||||
|
|
||||||
return {
|
|
||||||
attendeeId: attendee.id,
|
|
||||||
fullName: attendee.fullName,
|
|
||||||
enrolledAt: enrolledAt.toISOString(),
|
|
||||||
sessions: memberSessions(
|
|
||||||
sessionsByGroup.get(group.id) ?? [],
|
|
||||||
attendeeAttendances,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Why there is risk, over every member and not only the urgent ones sent to
|
||||||
|
// the client. Disjoint: an absence streak counts in the first and only
|
||||||
|
// there; the second groups the rest (inactivity or a declining trend).
|
||||||
|
const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok');
|
||||||
|
const absenceStreakCount = atRisk.filter(
|
||||||
|
(member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak,
|
||||||
|
).length;
|
||||||
|
|
||||||
const urgentes: UrgentMemberSummary[] = resumen.urgentes
|
const urgentes: UrgentMemberSummary[] = resumen.urgentes
|
||||||
.slice(0, URGENT_MEMBERS_LIMIT)
|
.slice(0, URGENT_MEMBERS_LIMIT)
|
||||||
.map((urgente) => ({
|
.map((urgente) => ({
|
||||||
@@ -233,7 +168,14 @@ function buildSummaryFields(
|
|||||||
attendanceRate: urgente.attendanceRate,
|
attendanceRate: urgente.attendanceRate,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
groupId: group.id,
|
||||||
|
groupName: group.name,
|
||||||
|
riskLevel,
|
||||||
|
absenceStreakCount,
|
||||||
|
lowAttendanceCount: atRisk.length - absenceStreakCount,
|
||||||
riesgoAlto: resumen.riesgoAlto,
|
riesgoAlto: resumen.riesgoAlto,
|
||||||
atencion: resumen.atencion,
|
atencion: resumen.atencion,
|
||||||
ok: resumen.ok,
|
ok: resumen.ok,
|
||||||
@@ -244,10 +186,6 @@ function buildSummaryFields(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function bump(counter: Map<string, number>, key: string) {
|
|
||||||
counter.set(key, (counter.get(key) ?? 0) + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
||||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
@@ -257,25 +195,3 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
|||||||
}
|
}
|
||||||
return byAttendee;
|
return byAttendee;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The universe of classes is the group's, not the `Attendance` rows'.
|
|
||||||
Attendance is recorded attendee by attendee and only when someone marks a
|
|
||||||
class, so "this class happened and this attendee has no record" is a real
|
|
||||||
and frequent state, not an absence. If the list were built from the
|
|
||||||
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
|
||||||
two absences separated by an unmarked class would count as three in a row.
|
|
||||||
The domain already treats them as neutral (`status: null`), so all that is
|
|
||||||
left here is to pick the right universe and keep the criterion on one side.
|
|
||||||
`sessions` comes from most recent to oldest, so keeping the first
|
|
||||||
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
|
||||||
and not global, so a group with a long history doesn't steal window from
|
|
||||||
the groups listed after it. */
|
|
||||||
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
|
|
||||||
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
|
||||||
|
|
||||||
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
|
|
||||||
sessionId: session.id,
|
|
||||||
startsAt: session.startsAt.toISOString(),
|
|
||||||
status: statusBySession.get(session.id) ?? null,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
@@ -6,15 +6,11 @@ import type {
|
|||||||
StudentAtRisk,
|
StudentAtRisk,
|
||||||
StudentsAtRisk,
|
StudentsAtRisk,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||||
import {
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
classifyRisk,
|
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||||
lastAttendedAt,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '../../lib/risk';
|
|
||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
type GetStudentsAtRiskDeps = {
|
type GetStudentsAtRiskDeps = {
|
||||||
@@ -24,6 +20,7 @@ type GetStudentsAtRiskDeps = {
|
|||||||
|
|
||||||
type AttendanceStreamRow = {
|
type AttendanceStreamRow = {
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
|
classSessionId: string;
|
||||||
status: AttendanceStatus;
|
status: AttendanceStatus;
|
||||||
classSession: { startsAt: Date };
|
classSession: { startsAt: Date };
|
||||||
};
|
};
|
||||||
@@ -56,8 +53,10 @@ export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' |
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
* 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, so both
|
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
|
||||||
* agree on who is at risk. Does not check access: callers do.
|
* 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(
|
export async function findStudentsAtRisk(
|
||||||
db: StudentsAtRiskDb,
|
db: StudentsAtRiskDb,
|
||||||
@@ -69,16 +68,18 @@ export async function findStudentsAtRisk(
|
|||||||
const [windowSessions, attendees, attendances] = await Promise.all([
|
const [windowSessions, attendees, attendances] = await Promise.all([
|
||||||
db.classSession.findMany({
|
db.classSession.findMany({
|
||||||
where: { groupId, startsAt: { gte: since } },
|
where: { groupId, startsAt: { gte: since } },
|
||||||
select: { id: true },
|
select: { id: true, startsAt: true },
|
||||||
|
orderBy: { startsAt: 'desc' },
|
||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { groupId, status: 'ACTIVE' },
|
where: { groupId, status: 'ACTIVE' },
|
||||||
select: { id: true, fullName: true, phone: true },
|
select: { id: true, fullName: true, phone: true, createdAt: true },
|
||||||
}),
|
}),
|
||||||
db.attendance.findMany({
|
db.attendance.findMany({
|
||||||
where: { attendee: { groupId } },
|
where: { attendee: { groupId } },
|
||||||
select: {
|
select: {
|
||||||
attendeeId: true,
|
attendeeId: true,
|
||||||
|
classSessionId: true,
|
||||||
status: true,
|
status: true,
|
||||||
classSession: { select: { startsAt: true } },
|
classSession: { select: { startsAt: true } },
|
||||||
},
|
},
|
||||||
@@ -91,20 +92,21 @@ export async function findStudentsAtRisk(
|
|||||||
|
|
||||||
const atRisk: StudentAtRisk[] = [];
|
const atRisk: StudentAtRisk[] = [];
|
||||||
for (const attendee of attendees) {
|
for (const attendee of attendees) {
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
const rows = streamByAttendee.get(attendee.id) ?? [];
|
||||||
status: row.status,
|
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
|
||||||
occurredAt: row.classSession.startsAt,
|
const riskLevel = toRiskLevel(signals.level);
|
||||||
}));
|
if (!riskLevel) {
|
||||||
const consecutiveAbsences = trailingAbsentStreak(stream);
|
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 attendedAt = lastAttendedAt(stream);
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
const monthlyRate = monthlyAttendanceRate(
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
||||||
totalWindowSessions,
|
totalWindowSessions,
|
||||||
);
|
);
|
||||||
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
|
|
||||||
if (!riskLevel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
atRisk.push({
|
atRisk.push({
|
||||||
attendeeId: attendee.id,
|
attendeeId: attendee.id,
|
||||||
fullName: attendee.fullName,
|
fullName: attendee.fullName,
|
||||||
|
|||||||
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared';
|
||||||
|
|
||||||
|
/* How many classes we look back per attendee. That is the real ceiling of the
|
||||||
|
model: `class_sessions` are not created on their own, they get materialized
|
||||||
|
when someone opens "today's classes", so pulling years of rows makes no
|
||||||
|
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
|
||||||
|
the attendance rate the card shows. */
|
||||||
|
export const MEMBER_HISTORY_LIMIT = 20;
|
||||||
|
|
||||||
|
export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date };
|
||||||
|
export type MemberSessionRow = { id: string; startsAt: Date };
|
||||||
|
export type MemberAttendanceRow = {
|
||||||
|
classSessionId: string;
|
||||||
|
status: AttendanceStatus;
|
||||||
|
classSession: { startsAt: Date };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The input of the domain risk rule (`summarizeMemberAttendance` in shared) for
|
||||||
|
* one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the
|
||||||
|
* re-engagement job all build it here, so they can't disagree on who is at risk.
|
||||||
|
*
|
||||||
|
* `groupSessions` must come most recent first (as the queries order them).
|
||||||
|
*/
|
||||||
|
export function toMemberAttendance(
|
||||||
|
attendee: MemberAttendeeRow,
|
||||||
|
groupSessions: MemberSessionRow[],
|
||||||
|
attendances: MemberAttendanceRow[],
|
||||||
|
): MemberAttendance {
|
||||||
|
// If the attendee has attendances before their enrollment date in the DB
|
||||||
|
// (e.g. created today but with past classes already recorded), their
|
||||||
|
// effective join date is the first class they were marked for.
|
||||||
|
const earliestAttendance = attendances.reduce<Date | null>(
|
||||||
|
(earliest, att) =>
|
||||||
|
!earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const enrolledAt =
|
||||||
|
earliestAttendance && earliestAttendance < attendee.createdAt
|
||||||
|
? earliestAttendance
|
||||||
|
: attendee.createdAt;
|
||||||
|
|
||||||
|
return {
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
fullName: attendee.fullName,
|
||||||
|
enrolledAt: enrolledAt.toISOString(),
|
||||||
|
sessions: memberSessions(groupSessions, attendances),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */
|
||||||
|
export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null {
|
||||||
|
if (level === 'riesgo_alto') return 'HIGH';
|
||||||
|
if (level === 'atencion') return 'MEDIUM';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The universe of classes is the group's, not the `Attendance` rows'.
|
||||||
|
Attendance is recorded attendee by attendee and only when someone marks a
|
||||||
|
class, so "this class happened and this attendee has no record" is a real
|
||||||
|
and frequent state, not an absence. If the list were built from the
|
||||||
|
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
||||||
|
two absences separated by an unmarked class would count as three in a row.
|
||||||
|
The domain already treats them as neutral (`status: null`), so all that is
|
||||||
|
left here is to pick the right universe and keep the criterion on one side.
|
||||||
|
`sessions` comes from most recent to oldest, so keeping the first
|
||||||
|
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
||||||
|
and not global, so a group with a long history doesn't steal window from
|
||||||
|
the groups listed after it. */
|
||||||
|
function memberSessions(
|
||||||
|
sessions: MemberSessionRow[],
|
||||||
|
attendances: MemberAttendanceRow[],
|
||||||
|
): MemberClassSession[] {
|
||||||
|
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
||||||
|
|
||||||
|
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
|
||||||
|
sessionId: session.id,
|
||||||
|
startsAt: session.startsAt.toISOString(),
|
||||||
|
status: statusBySession.get(session.id) ?? null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -3,27 +3,6 @@ export type AttendanceStreamEntry = {
|
|||||||
occurredAt: Date;
|
occurredAt: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
|
||||||
|
|
||||||
/** Minimum streak of unexcused absences that already triggers risk. */
|
|
||||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
|
||||||
|
|
||||||
/** Monthly attendance (30-day window) below which there is risk. */
|
|
||||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
|
||||||
|
|
||||||
// Counts the consecutive unexcused absences from the most recent class.
|
|
||||||
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
|
|
||||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
|
||||||
let streak = 0;
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (entry.status !== 'ABSENT') {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
streak += 1;
|
|
||||||
}
|
|
||||||
return streak;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
@@ -46,17 +25,3 @@ export function monthlyAttendanceRate(
|
|||||||
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
||||||
return Math.round((present / totalSessions) * 100);
|
return Math.round((present / totalSessions) * 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
|
|
||||||
export function classifyRisk(
|
|
||||||
consecutiveAbsences: number,
|
|
||||||
monthlyRate: number,
|
|
||||||
): RiskLevel | null {
|
|
||||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
|
|
||||||
return 'HIGH';
|
|
||||||
}
|
|
||||||
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
|
|
||||||
return 'MEDIUM';
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -24,7 +24,7 @@ type GroupSummaryRecord = {
|
|||||||
name: string;
|
name: string;
|
||||||
days: NextClass['days'];
|
days: NextClass['days'];
|
||||||
time: string | null;
|
time: string | null;
|
||||||
_count: { attendees: number };
|
_count: { attendees: number; preRegistrations: number };
|
||||||
};
|
};
|
||||||
|
|
||||||
export class GetHomeSummary {
|
export class GetHomeSummary {
|
||||||
@@ -42,7 +42,11 @@ export class GetHomeSummary {
|
|||||||
name: true,
|
name: true,
|
||||||
days: true,
|
days: true,
|
||||||
time: true,
|
time: true,
|
||||||
_count: { select: { attendees: true } },
|
// The pending pre-registrations ride on the same query: Home lists
|
||||||
|
// them under "Para atender" without one request per group.
|
||||||
|
_count: {
|
||||||
|
select: { attendees: true, preRegistrations: { where: { status: 'PENDING' } } },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -51,6 +55,7 @@ export class GetHomeSummary {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +98,13 @@ export class GetHomeSummary {
|
|||||||
groupName: payment.group.name,
|
groupName: payment.group.name,
|
||||||
attendeeName: payment.attendee.fullName,
|
attendeeName: payment.attendee.fullName,
|
||||||
})),
|
})),
|
||||||
|
pendingPreRegistrations: groups
|
||||||
|
.filter((group) => group._count.preRegistrations > 0)
|
||||||
|
.map((group) => ({
|
||||||
|
groupId: group.id,
|
||||||
|
groupName: group.name,
|
||||||
|
count: group._count.preRegistrations,
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cuenta el motivo: faltas seguidas y asistencia baja, sin repetir alumnos', async () => {
|
it('cuenta el motivo: faltas seguidas o inactividad, sin repetir alumnos', async () => {
|
||||||
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
|
||||||
prismaFetchAttendeeFindMany([
|
prismaFetchAttendeeFindMany([
|
||||||
attendee('a-1', 'group-1'),
|
attendee('a-1', 'group-1'),
|
||||||
@@ -113,6 +113,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||||
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
|
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
|
||||||
|
{ id: 's7', groupId: 'group-1', startsAt: at(15) },
|
||||||
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
|
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
|
||||||
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
||||||
]);
|
]);
|
||||||
@@ -121,11 +122,10 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||||
attendance('a-1', 's3', 'PRESENT', at(3)),
|
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||||
// No streak, but attends less than half of the month's classes.
|
// A single absence, but 14 days between their last presence and the
|
||||||
attendance('a-2', 's1', 'PRESENT', at(1)),
|
// class they missed (the ones in between have no record): inactivity.
|
||||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
attendance('a-2', 's1', 'ABSENT', at(1)),
|
||||||
attendance('a-2', 's3', 'ABSENT', at(3)),
|
attendance('a-2', 's7', 'PRESENT', at(15)),
|
||||||
attendance('a-2', 's4', 'ABSENT', at(4)),
|
|
||||||
// Ok.
|
// Ok.
|
||||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||||
attendance('a-3', 's2', 'PRESENT', at(2)),
|
attendance('a-3', 's2', 'PRESENT', at(2)),
|
||||||
@@ -144,7 +144,7 @@ describe('GET /groups-risk/overview', () => {
|
|||||||
{
|
{
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
groupName: 'Funcional',
|
groupName: 'Funcional',
|
||||||
riskLevel: 'MEDIUM',
|
riskLevel: 'HIGH',
|
||||||
absenceStreakCount: 1,
|
absenceStreakCount: 1,
|
||||||
lowAttendanceCount: 1,
|
lowAttendanceCount: 1,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
import { describe, expect, it } from 'bun:test';
|
import { describe, expect, it } from 'bun:test';
|
||||||
import {
|
import { lastAttendedAt, monthlyAttendanceRate } from '@/modules/analytics/lib/risk';
|
||||||
classifyRisk,
|
|
||||||
lastAttendedAt,
|
|
||||||
monthlyAttendanceRate,
|
|
||||||
trailingAbsentStreak,
|
|
||||||
} from '@/modules/analytics/lib/risk';
|
|
||||||
|
|
||||||
const day = 24 * 60 * 60 * 1000;
|
const day = 24 * 60 * 60 * 1000;
|
||||||
const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
||||||
@@ -12,25 +7,6 @@ const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
|||||||
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
||||||
return { status, occurredAt: at(offsetDays) };
|
return { status, occurredAt: at(offsetDays) };
|
||||||
}
|
}
|
||||||
describe('trailingAbsentStreak', () => {
|
|
||||||
it('devuelve 0 sin registros', () => {
|
|
||||||
expect(trailingAbsentStreak([])).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('cuenta ausencias consecutivas sin justificar desde la más reciente', () => {
|
|
||||||
expect(trailingAbsentStreak([entry('ABSENT', 0)])).toBe(1);
|
|
||||||
expect(trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('ABSENT', 14)])).toBe(3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rompe la cadena con PRESENT o EXCUSED', () => {
|
|
||||||
expect(
|
|
||||||
trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('PRESENT', 14)]),
|
|
||||||
).toBe(2);
|
|
||||||
expect(trailingAbsentStreak([entry('EXCUSED', 0), entry('ABSENT', 7)])).toBe(0);
|
|
||||||
expect(trailingAbsentStreak([entry('PRESENT', 0)])).toBe(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('lastAttendedAt', () => {
|
describe('lastAttendedAt', () => {
|
||||||
it('devuelve la clase PRESENT más reciente', () => {
|
it('devuelve la clase PRESENT más reciente', () => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -59,21 +35,3 @@ describe('monthlyAttendanceRate', () => {
|
|||||||
expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0);
|
expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('classifyRisk', () => {
|
|
||||||
it('HIGH con 3 o más ausencias consecutivas', () => {
|
|
||||||
expect(classifyRisk(3, 80)).toBe('HIGH');
|
|
||||||
expect(classifyRisk(5, 20)).toBe('HIGH');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('MEDIUM con 2 ausencias consecutivas o asistencia menor al 50%', () => {
|
|
||||||
expect(classifyRisk(2, 90)).toBe('MEDIUM');
|
|
||||||
expect(classifyRisk(1, 40)).toBe('MEDIUM');
|
|
||||||
expect(classifyRisk(2, 40)).toBe('MEDIUM');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sin riesgo si no cumple ningún umbral', () => {
|
|
||||||
expect(classifyRisk(1, 60)).toBeNull();
|
|
||||||
expect(classifyRisk(0, 60)).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -133,24 +133,35 @@ describe('analytics routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('GET /groups/:groupId/students-at-risk', () => {
|
describe('GET /groups/:groupId/students-at-risk', () => {
|
||||||
const sessions = [at(0), at(7), at(14), at(21)];
|
// Every 3 days: with weekly classes two absences already add up to 14 days
|
||||||
|
// without coming, and the inactivity rule would turn the MEDIUM case HIGH.
|
||||||
|
const sessions = [at(0), at(3), at(6), at(9)];
|
||||||
|
const sessionRows = sessions.map((startsAt, index) => ({ id: `s${index}`, startsAt: new Date(startsAt) }));
|
||||||
|
const enrolled = new Date(at(60));
|
||||||
|
// `offset` is the index in `sessions`: 0 is the most recent class.
|
||||||
|
const row = (attendeeId: string, status: string, offset: number) => ({
|
||||||
|
attendeeId,
|
||||||
|
classSessionId: `s${offset}`,
|
||||||
|
status,
|
||||||
|
classSession: { startsAt: new Date(sessions[offset]) },
|
||||||
|
});
|
||||||
|
|
||||||
it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => {
|
it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt })));
|
prisma.classSession.findMany.mockResolvedValue(sessionRows);
|
||||||
prisma.attendee.findMany.mockResolvedValue([
|
prisma.attendee.findMany.mockResolvedValue([
|
||||||
{ id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111' },
|
{ id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111', createdAt: enrolled },
|
||||||
{ id: 'a-2', fullName: 'Bruno Díaz', phone: null },
|
{ id: 'a-2', fullName: 'Bruno Díaz', phone: null, createdAt: enrolled },
|
||||||
]);
|
]);
|
||||||
prisma.attendance.findMany.mockResolvedValue([
|
prisma.attendance.findMany.mockResolvedValue([
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } },
|
row('a-1', 'ABSENT', 0),
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } },
|
row('a-1', 'ABSENT', 1),
|
||||||
{ attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(14)) } },
|
row('a-1', 'ABSENT', 2),
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } },
|
row('a-1', 'PRESENT', 3),
|
||||||
{ attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } },
|
row('a-2', 'ABSENT', 0),
|
||||||
{ attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } },
|
row('a-2', 'ABSENT', 1),
|
||||||
{ attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(14)) } },
|
row('a-2', 'PRESENT', 2),
|
||||||
{ attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } },
|
row('a-2', 'PRESENT', 3),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
||||||
@@ -165,7 +176,7 @@ describe('analytics routes', () => {
|
|||||||
phone: '+521111111111',
|
phone: '+521111111111',
|
||||||
riskLevel: 'HIGH',
|
riskLevel: 'HIGH',
|
||||||
consecutiveAbsences: 3,
|
consecutiveAbsences: 3,
|
||||||
lastAttendedAt: at(21),
|
lastAttendedAt: sessions[3],
|
||||||
monthlyAttendanceRate: 25,
|
monthlyAttendanceRate: 25,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -174,7 +185,7 @@ describe('analytics routes', () => {
|
|||||||
phone: null,
|
phone: null,
|
||||||
riskLevel: 'MEDIUM',
|
riskLevel: 'MEDIUM',
|
||||||
consecutiveAbsences: 2,
|
consecutiveAbsences: 2,
|
||||||
lastAttendedAt: at(14),
|
lastAttendedAt: sessions[2],
|
||||||
monthlyAttendanceRate: 50,
|
monthlyAttendanceRate: 50,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -183,14 +194,11 @@ describe('analytics routes', () => {
|
|||||||
|
|
||||||
it('devuelve lista vacía cuando nadie está en riesgo', async () => {
|
it('devuelve lista vacía cuando nadie está en riesgo', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt })));
|
prisma.classSession.findMany.mockResolvedValue(sessionRows);
|
||||||
prisma.attendee.findMany.mockResolvedValue([
|
prisma.attendee.findMany.mockResolvedValue([
|
||||||
{ id: 'a-1', fullName: 'Ana Pérez', phone: null },
|
{ id: 'a-1', fullName: 'Ana Pérez', phone: null, createdAt: enrolled },
|
||||||
]);
|
|
||||||
prisma.attendance.findMany.mockResolvedValue([
|
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(0)) } },
|
|
||||||
{ attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(7)) } },
|
|
||||||
]);
|
]);
|
||||||
|
prisma.attendance.findMany.mockResolvedValue([row('a-1', 'PRESENT', 0), row('a-1', 'PRESENT', 1)]);
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk');
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ const groupA = {
|
|||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
capacity: 8,
|
capacity: 8,
|
||||||
_count: { attendees: 3 },
|
_count: { attendees: 3, preRegistrations: 2 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const groupB = {
|
const groupB = {
|
||||||
@@ -48,7 +48,7 @@ const groupB = {
|
|||||||
billingType: null,
|
billingType: null,
|
||||||
dueDay: null,
|
dueDay: null,
|
||||||
capacity: null,
|
capacity: null,
|
||||||
_count: { attendees: 2 },
|
_count: { attendees: 2, preRegistrations: 0 },
|
||||||
};
|
};
|
||||||
|
|
||||||
const madeUpAmount = (value: string) => ({ toString: () => value });
|
const madeUpAmount = (value: string) => ({ toString: () => value });
|
||||||
@@ -113,6 +113,8 @@ describe('GetHomeSummary', () => {
|
|||||||
attendeeName: 'Ana García',
|
attendeeName: 'Ana García',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
// Only the groups with something waiting: Cuadrilla B has none.
|
||||||
|
pendingPreRegistrations: [{ groupId: 'g1', groupName: 'Cuadrilla A', count: 2 }],
|
||||||
});
|
});
|
||||||
|
|
||||||
const where = {
|
const where = {
|
||||||
@@ -160,7 +162,7 @@ describe('GetHomeSummary', () => {
|
|||||||
billingType: null,
|
billingType: null,
|
||||||
dueDay: null,
|
dueDay: null,
|
||||||
capacity: null,
|
capacity: null,
|
||||||
_count: { attendees: 0 },
|
_count: { attendees: 0, preRegistrations: 0 },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -238,6 +240,7 @@ describe('GetHomeSummary', () => {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
expect(prisma.payment.aggregate).not.toHaveBeenCalled();
|
expect(prisma.payment.aggregate).not.toHaveBeenCalled();
|
||||||
expect(prisma.payment.findMany).not.toHaveBeenCalled();
|
expect(prisma.payment.findMany).not.toHaveBeenCalled();
|
||||||
@@ -259,6 +262,7 @@ describe('home routes', () => {
|
|||||||
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
|
||||||
nextClass: null,
|
nextClass: null,
|
||||||
upcomingPayments: [],
|
upcomingPayments: [],
|
||||||
|
pendingPreRegistrations: [],
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -273,20 +273,26 @@ describe('payment reminders', () => {
|
|||||||
describe('re-engagement messages', () => {
|
describe('re-engagement messages', () => {
|
||||||
function atRiskGroup() {
|
function atRiskGroup() {
|
||||||
// Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
|
// Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
|
||||||
db.classSession.findMany.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
|
const s1 = new Date('2026-10-16T10:00:00Z');
|
||||||
|
const s2 = new Date('2026-10-14T10:00:00Z');
|
||||||
|
const enrolled = new Date('2026-09-01T10:00:00Z');
|
||||||
|
db.classSession.findMany.mockResolvedValue([
|
||||||
|
{ id: 's1', startsAt: s1 },
|
||||||
|
{ id: 's2', startsAt: s2 },
|
||||||
|
]);
|
||||||
db.attendee.findMany
|
db.attendee.findMany
|
||||||
.mockResolvedValueOnce([
|
.mockResolvedValueOnce([
|
||||||
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789' },
|
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled },
|
||||||
{ id: 'att-2', fullName: 'Beto', phone: '1198765432' },
|
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled },
|
||||||
])
|
])
|
||||||
.mockResolvedValueOnce([
|
.mockResolvedValueOnce([
|
||||||
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
|
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
|
||||||
]);
|
]);
|
||||||
db.attendance.findMany.mockResolvedValue([
|
db.attendance.findMany.mockResolvedValue([
|
||||||
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
|
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },
|
||||||
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
|
{ attendeeId: 'att-1', classSessionId: 's2', status: 'ABSENT', classSession: { startsAt: s2 } },
|
||||||
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
|
{ attendeeId: 'att-2', classSessionId: 's1', status: 'PRESENT', classSession: { startsAt: s1 } },
|
||||||
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
|
{ attendeeId: 'att-2', classSessionId: 's2', status: 'PRESENT', classSession: { startsAt: s2 } },
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ export function AnalyticsView() {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
Alumnos con faltas seguidas, que dejaron de venir o cuya asistencia viene en baja.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{atRisk.length === 0 ? (
|
{atRisk.length === 0 ? (
|
||||||
|
|||||||
@@ -39,11 +39,9 @@ export function AtRiskStudentCard({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
{student.riskLevel === 'HIGH' ? (
|
<Badge variant={student.riskLevel === 'HIGH' ? 'danger' : 'warning'}>
|
||||||
<Badge variant="danger">{student.consecutiveAbsences} faltas seguidas</Badge>
|
{riskReason(student)}
|
||||||
) : (
|
</Badge>
|
||||||
<Badge variant="warning">Baja asistencia</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-3 flex items-center gap-2 border-t border-border pt-3">
|
<div className="mt-3 flex items-center gap-2 border-t border-border pt-3">
|
||||||
@@ -100,3 +98,17 @@ export function AtRiskStudentCard({
|
|||||||
</li>
|
</li>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DAY_MS = 86_400_000
|
||||||
|
|
||||||
|
/* The same reasons the domain rule weighs, in its order: an absence streak,
|
||||||
|
then the time without coming, and last the declining trend (the only thing
|
||||||
|
left that can flag someone with neither). */
|
||||||
|
function riskReason(student: StudentAtRiskDto): string {
|
||||||
|
if (student.consecutiveAbsences >= 2) return `${student.consecutiveAbsences} faltas seguidas`
|
||||||
|
if (student.riskLevel === 'HIGH' && student.lastAttendedAt) {
|
||||||
|
const days = Math.floor((Date.now() - new Date(student.lastAttendedAt).getTime()) / DAY_MS)
|
||||||
|
return `${days} días sin venir`
|
||||||
|
}
|
||||||
|
return 'Asistencia en baja'
|
||||||
|
}
|
||||||
|
|||||||
@@ -91,13 +91,22 @@ type GroupDetailContextValue = {
|
|||||||
|
|
||||||
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
||||||
|
|
||||||
export function GroupDetailProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
export function GroupDetailProvider({
|
||||||
|
groupId,
|
||||||
|
initialSection = 'members',
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
groupId: string
|
||||||
|
/** Lets a link open the detail straight on Pendientes (Home's "Para atender"). */
|
||||||
|
initialSection?: ListSection
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
|
|
||||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||||
const [listSection, setListSectionState] = useState<ListSection>('members')
|
const [listSection, setListSectionState] = useState<ListSection>(initialSection)
|
||||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||||
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { CheckCircle2, ChevronRight, Wallet } from 'lucide-react'
|
import type { PendingPreRegistrations } from '@gruperly/shared'
|
||||||
|
import { CheckCircle2, ChevronRight, Inbox, Wallet } from 'lucide-react'
|
||||||
import { Avatar } from '../../components/ui'
|
import { Avatar } from '../../components/ui'
|
||||||
import { getGroupsRiskOverview, getPayments } from '../../lib/api'
|
import { getGroupsRiskOverview, getPayments } from '../../lib/api'
|
||||||
import { absenceReason } from '../groups/card'
|
import { absenceReason } from '../groups/card'
|
||||||
@@ -11,8 +12,13 @@ const MAX_AT_RISK = 4
|
|||||||
/* "Para atender": what the teacher has to act on today, across all groups.
|
/* "Para atender": what the teacher has to act on today, across all groups.
|
||||||
Nothing is computed here: the at-risk people are the high-risk `urgentes` of
|
Nothing is computed here: the at-risk people are the high-risk `urgentes` of
|
||||||
`GET /groups-risk/overview` (same query key as the group list, so the cache
|
`GET /groups-risk/overview` (same query key as the group list, so the cache
|
||||||
is shared) and the overdue payments are just the total of the filtered list. */
|
is shared), the overdue payments are just the total of the filtered list and
|
||||||
export function AttentionList() {
|
the pending pre-registrations come with the Home summary. */
|
||||||
|
export function AttentionList({
|
||||||
|
pendingPreRegistrations,
|
||||||
|
}: {
|
||||||
|
pendingPreRegistrations: PendingPreRegistrations[]
|
||||||
|
}) {
|
||||||
const riskQuery = useQuery({
|
const riskQuery = useQuery({
|
||||||
queryKey: ['groups-risk-overview'],
|
queryKey: ['groups-risk-overview'],
|
||||||
queryFn: getGroupsRiskOverview,
|
queryFn: getGroupsRiskOverview,
|
||||||
@@ -41,10 +47,10 @@ export function AttentionList() {
|
|||||||
<div>
|
<div>
|
||||||
<h2 className="text-lg font-bold text-primary">Para atender</h2>
|
<h2 className="text-lg font-bold text-primary">Para atender</h2>
|
||||||
|
|
||||||
{atRisk.length === 0 && overdue === 0 ? (
|
{atRisk.length === 0 && overdue === 0 && pendingPreRegistrations.length === 0 ? (
|
||||||
<p className="mt-3 flex items-center gap-2 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground/70">
|
<p className="mt-3 flex items-center gap-2 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground/70">
|
||||||
<CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
|
<CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
|
||||||
Todo en orden: nadie en riesgo y sin cobros vencidos.
|
Todo en orden: nadie en riesgo, sin cobros vencidos ni preinscripciones.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
||||||
@@ -65,6 +71,32 @@ export function AttentionList() {
|
|||||||
</li>
|
</li>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{/* Someone waiting for an answer goes before the at-risk list: it's
|
||||||
|
the only item where the other side is actively waiting. */}
|
||||||
|
{pendingPreRegistrations.map((group) => (
|
||||||
|
<li key={group.groupId}>
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId: group.groupId }}
|
||||||
|
search={{ section: 'pending' }}
|
||||||
|
className={ROW_CLASS_NAME}
|
||||||
|
>
|
||||||
|
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-accent-soft text-accent">
|
||||||
|
<Inbox className="size-5" aria-hidden="true" />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block text-sm font-semibold text-primary">
|
||||||
|
{group.count === 1
|
||||||
|
? '1 preinscripción por aprobar'
|
||||||
|
: `${group.count} preinscripciones por aprobar`}
|
||||||
|
</span>
|
||||||
|
<span className="block truncate text-xs text-foreground/60">{group.groupName}</span>
|
||||||
|
</span>
|
||||||
|
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
|
||||||
{atRisk.slice(0, MAX_AT_RISK).map((member) => (
|
{atRisk.slice(0, MAX_AT_RISK).map((member) => (
|
||||||
<li key={member.attendeeId}>
|
<li key={member.attendeeId}>
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ export function HomeView() {
|
|||||||
|
|
||||||
<SummaryStats summary={summaryQuery.data} />
|
<SummaryStats summary={summaryQuery.data} />
|
||||||
|
|
||||||
<AttentionList />
|
<AttentionList pendingPreRegistrations={summaryQuery.data.pendingPreRegistrations} />
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
|||||||
@@ -4,10 +4,14 @@ import { GroupDetailProvider } from '../../../../features/groups/detail/GroupDet
|
|||||||
import { GroupDetailView } from '../../../../features/groups/detail/GroupDetailView'
|
import { GroupDetailView } from '../../../../features/groups/detail/GroupDetailView'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/groups/$groupId/')({
|
export const Route = createFileRoute('/_authenticated/groups/$groupId/')({
|
||||||
|
validateSearch: (search: Record<string, unknown>): { section?: 'pending' } => ({
|
||||||
|
section: search.section === 'pending' ? 'pending' : undefined,
|
||||||
|
}),
|
||||||
component: () => {
|
component: () => {
|
||||||
const { groupId } = useParams({ from: '/_authenticated/groups/$groupId/' })
|
const { groupId } = useParams({ from: '/_authenticated/groups/$groupId/' })
|
||||||
|
const { section } = Route.useSearch()
|
||||||
return (
|
return (
|
||||||
<GroupDetailProvider groupId={groupId}>
|
<GroupDetailProvider groupId={groupId} initialSection={section ?? 'members'}>
|
||||||
<GroupDetailView />
|
<GroupDetailView />
|
||||||
</GroupDetailProvider>
|
</GroupDetailProvider>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -46,10 +46,20 @@ export const UpcomingPaymentSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type UpcomingPayment = z.output<typeof UpcomingPaymentSchema>;
|
export type UpcomingPayment = z.output<typeof UpcomingPaymentSchema>;
|
||||||
|
|
||||||
|
/** Pre-registrations from the shared link waiting for the teacher's approval,
|
||||||
|
* per group. Only groups with at least one. */
|
||||||
|
export const PendingPreRegistrationsSchema = z.object({
|
||||||
|
groupId: z.string(),
|
||||||
|
groupName: z.string(),
|
||||||
|
count: z.number().int().positive(),
|
||||||
|
});
|
||||||
|
export type PendingPreRegistrations = z.output<typeof PendingPreRegistrationsSchema>;
|
||||||
|
|
||||||
export const HomeSummarySchema = z.object({
|
export const HomeSummarySchema = z.object({
|
||||||
stats: HomeStatsSchema,
|
stats: HomeStatsSchema,
|
||||||
nextClass: NextClassSchema.nullable(),
|
nextClass: NextClassSchema.nullable(),
|
||||||
upcomingPayments: z.array(UpcomingPaymentSchema),
|
upcomingPayments: z.array(UpcomingPaymentSchema),
|
||||||
|
pendingPreRegistrations: z.array(PendingPreRegistrationsSchema),
|
||||||
});
|
});
|
||||||
export type HomeSummary = z.output<typeof HomeSummarySchema>;
|
export type HomeSummary = z.output<typeof HomeSummarySchema>;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user