feat: add absence notification and analytics features
- Implemented AbsenceNotifyView for notifying absence with session details. - Created AnalyticsView for displaying group analytics and managing students at risk. - Added ClassAttendanceView for marking attendance in classes. - Defined new schemas for analytics and attendance in shared package.
This commit is contained in:
92
apps/backend/src/modules/classes/lib/helpers.ts
Normal file
92
apps/backend/src/modules/classes/lib/helpers.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
AttendeePaymentStatus,
|
||||
ClassToday,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
|
||||
export type ClassesDb = Pick<
|
||||
PrismaClient,
|
||||
'group' | 'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease'
|
||||
>;
|
||||
|
||||
type PaymentLike = {
|
||||
status: 'PENDING' | 'PAID' | 'OVERDUE' | 'CANCELLED';
|
||||
dueDate: Date;
|
||||
};
|
||||
|
||||
// Estado de cobro calculado en tiempo real (sin columna denormalizada):
|
||||
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó.
|
||||
export function resolvePaymentStatus(
|
||||
payments: PaymentLike[],
|
||||
startOfToday: Date,
|
||||
): AttendeePaymentStatus {
|
||||
const hasUnpaid = payments.some(
|
||||
(payment) =>
|
||||
payment.status === 'OVERDUE'
|
||||
|| (payment.status === 'PENDING' && payment.dueDate.getTime() < startOfToday.getTime()),
|
||||
);
|
||||
return hasUnpaid ? 'PENDING' : 'UP_TO_DATE';
|
||||
}
|
||||
|
||||
export function absenceReleaseHours(): number {
|
||||
const raw = process.env.ABSENCE_RELEASE_HOURS;
|
||||
if (raw == null || raw.trim() === '') {
|
||||
return 12;
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 12;
|
||||
}
|
||||
|
||||
export type ClassSessionRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
startsAt: Date;
|
||||
};
|
||||
|
||||
type GroupWithAccess = {
|
||||
createdById: string;
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión.
|
||||
export function ensureSessionAccess(
|
||||
session: ClassSessionRecord & { group: GroupWithAccess },
|
||||
userId: string,
|
||||
): Result<ClassSessionRecord, ProblemDetails> {
|
||||
const isOwner = session.group.createdById === userId;
|
||||
const isMember = session.group.members.length > 0;
|
||||
if (!isOwner && !isMember) {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
value: { id: session.id, groupId: session.groupId, startsAt: session.startsAt },
|
||||
};
|
||||
}
|
||||
|
||||
export function sessionNotFound(sessionId: string): ProblemDetails {
|
||||
return notFoundResourceProblem('Class session', sessionId);
|
||||
}
|
||||
|
||||
export function toClassToday(
|
||||
session: { id: string; startsAt: Date },
|
||||
group: { id: string; name: string; capacity: number | null },
|
||||
enrolledCount: number,
|
||||
hasAttendance: boolean,
|
||||
): ClassToday {
|
||||
return {
|
||||
sessionId: session.id,
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
startsAt: session.startsAt.toISOString(),
|
||||
enrolledCount,
|
||||
capacity: group.capacity,
|
||||
availableSlots:
|
||||
group.capacity == null ? null : Math.max(0, group.capacity - enrolledCount),
|
||||
hasAttendance,
|
||||
};
|
||||
}
|
||||
3
apps/backend/src/modules/classes/lib/index.ts
Normal file
3
apps/backend/src/modules/classes/lib/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './helpers';
|
||||
export * from './notify';
|
||||
export * from './sessions';
|
||||
91
apps/backend/src/modules/classes/lib/notify.ts
Normal file
91
apps/backend/src/modules/classes/lib/notify.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { AttendanceStatus } from '@generated/prisma/client';
|
||||
import type { NotifyAbsenceResult, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem, validationProblem } from '@/http/problem-builders';
|
||||
import type { UnitOfWork } from '@/lib/prisma';
|
||||
import { type ClassesDb, sessionNotFound } from './helpers';
|
||||
|
||||
type RegisterAbsenceDeps = {
|
||||
db: Pick<ClassesDb, 'classSession' | 'attendee'>;
|
||||
unitOfWork: UnitOfWork;
|
||||
};
|
||||
|
||||
type RegisterAbsenceInput = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
now: Date;
|
||||
releaseHours: number;
|
||||
};
|
||||
|
||||
// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token):
|
||||
// - Marca la asistencia como EXCUSED (upsert idempotente).
|
||||
// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo.
|
||||
export async function registerAbsence(
|
||||
deps: RegisterAbsenceDeps,
|
||||
input: RegisterAbsenceInput,
|
||||
): Promise<Result<NotifyAbsenceResult, ProblemDetails>> {
|
||||
const { db, unitOfWork } = deps;
|
||||
const { attendeeId, classSessionId, now, releaseHours } = input;
|
||||
|
||||
const session = await db.classSession.findUnique({ where: { id: classSessionId } });
|
||||
if (!session) {
|
||||
return err(sessionNotFound(classSessionId));
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.findUnique({ where: { id: attendeeId } });
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
if (attendee.groupId !== session.groupId) {
|
||||
return err(
|
||||
validationProblem({ detail: 'El alumno no pertenece al grupo de esta clase.' }),
|
||||
);
|
||||
}
|
||||
|
||||
const anticipationMs = session.startsAt.getTime() - now.getTime();
|
||||
const slotReleased = anticipationMs >= releaseHours * 60 * 60 * 1000;
|
||||
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
await tx.attendance.upsert({
|
||||
where: {
|
||||
attendeeId_classSessionId: {
|
||||
attendeeId,
|
||||
classSessionId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
attendeeId,
|
||||
classSessionId,
|
||||
status: AttendanceStatus.EXCUSED,
|
||||
markedAt: now,
|
||||
},
|
||||
update: {
|
||||
status: AttendanceStatus.EXCUSED,
|
||||
markedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
if (slotReleased) {
|
||||
await tx.slotRelease.upsert({
|
||||
where: {
|
||||
attendeeId_classSessionId: {
|
||||
attendeeId,
|
||||
classSessionId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
attendeeId,
|
||||
classSessionId,
|
||||
isClaimed: false,
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
|
||||
return ok({
|
||||
classSessionId,
|
||||
notified: true,
|
||||
slotReleased,
|
||||
});
|
||||
});
|
||||
}
|
||||
64
apps/backend/src/modules/classes/lib/sessions.ts
Normal file
64
apps/backend/src/modules/classes/lib/sessions.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import type { WeekDay } from '@gruperly/shared';
|
||||
import { todayOccurrence } from '@/modules/home/lib/scheduler';
|
||||
import type { ClassesDb } from './helpers';
|
||||
|
||||
export type TodaySessionCandidate = {
|
||||
groupId: string;
|
||||
startsAt: Date;
|
||||
};
|
||||
|
||||
type ScheduledGroup = {
|
||||
id: string;
|
||||
days: WeekDay[] | null;
|
||||
time: string | null;
|
||||
};
|
||||
|
||||
// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor).
|
||||
export function buildTodayCandidates(
|
||||
groups: ScheduledGroup[],
|
||||
now: Date,
|
||||
timeZone: string,
|
||||
): TodaySessionCandidate[] {
|
||||
const candidates: TodaySessionCandidate[] = [];
|
||||
for (const group of groups) {
|
||||
if (!group.days || group.days.length === 0 || !group.time) {
|
||||
continue;
|
||||
}
|
||||
const startsAt = todayOccurrence({
|
||||
days: group.days,
|
||||
time: group.time,
|
||||
now,
|
||||
timeZone,
|
||||
});
|
||||
if (startsAt) {
|
||||
candidates.push({ groupId: group.id, startsAt });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids.
|
||||
export async function ensureTodaySessions(
|
||||
db: Pick<ClassesDb, 'classSession'>,
|
||||
candidates: TodaySessionCandidate[],
|
||||
): Promise<string[]> {
|
||||
const sessionIds: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
const session = await db.classSession.upsert({
|
||||
where: {
|
||||
groupId_startsAt: {
|
||||
groupId: candidate.groupId,
|
||||
startsAt: candidate.startsAt,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
groupId: candidate.groupId,
|
||||
startsAt: candidate.startsAt,
|
||||
},
|
||||
update: {},
|
||||
select: { id: true },
|
||||
});
|
||||
sessionIds.push(session.id);
|
||||
}
|
||||
return sessionIds;
|
||||
}
|
||||
Reference in New Issue
Block a user