- Add the `kidsGroups` plan feature (Pro) and `Group.audience` (ADULTS | KIDS); creating or switching a group to KIDS requires the feature, existing KIDS groups keep working after a downgrade. - Model the adult in charge as a Person linked through `person_guardians`; migrate the old guardian_name/guardian_phone columns and drop them. - Kids quick add: kid + guardian form, guardian lookup by phone to pick an existing kid or add a sibling; backend rejects KIDS adds without guardian. - Attendee page: "Adulto a cargo" section with siblings, editable via PATCH /groups/:gid/attendees/:aid/guardian. - Contact phone (WhatsApp jobs, attention, student access invite, students at risk, attendee actions) prefers the guardian's phone. - Edit group screen (PATCH /groups/:gid, owner only); switching back to ADULTS is blocked while kids have no phone of their own. - Hide bulk import in KIDS groups until it carries guardian data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
4.8 KiB
TypeScript
145 lines
4.8 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 { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
|
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, ...guardianSelect } } },
|
|
}).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,
|
|
// The number to reach them on: the adult in charge for a kid.
|
|
phone: contactPhone(attendee),
|
|
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;
|
|
} |