chore: update comments and documentation for clarity and consistency across various files
- Translated comments from Spanish to English in vite.config.ts, docker-compose.yml, attendance-risk.ts, analytics.ts, attendance.ts, attendees.ts, enums.ts, groups.ts, and onboarding.ts. - Improved descriptions for better understanding of code functionality and purpose. - Ensured uniformity in terminology and phrasing throughout the codebase.
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
#!/bin/sh
|
||||
# Entrypoint de producción del backend: aplica las migraciones y levanta el
|
||||
# servidor en el mismo contenedor.
|
||||
# Production entrypoint for the backend: applies the migrations and starts the
|
||||
# server in the same container.
|
||||
#
|
||||
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo
|
||||
# serían ~10MB por un shebang).
|
||||
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||
# installed (adding it would be ~10MB for a shebang).
|
||||
#
|
||||
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una
|
||||
# base ya migrada a mano o una que se gestiona fuera de este despliegue).
|
||||
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||
# a database already migrated by hand, or one managed outside this deployment).
|
||||
set -e
|
||||
|
||||
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||
@@ -18,8 +18,8 @@ else
|
||||
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||
i=1
|
||||
|
||||
# La base puede seguir arrancando cuando este contenedor ya empezó, y un
|
||||
# deploy suele convivir con un reinicio de Postgres.
|
||||
# The database may still be starting up when this container is already
|
||||
# running, and a deploy usually overlaps a Postgres restart.
|
||||
while [ "$i" -le "$attempts" ]; do
|
||||
if bun run db:deploy; then
|
||||
echo "migrate: listo"
|
||||
@@ -37,6 +37,6 @@ else
|
||||
done
|
||||
fi
|
||||
|
||||
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop`
|
||||
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma).
|
||||
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||
exec "$@"
|
||||
|
||||
@@ -27,7 +27,7 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|
||||
const normalizedPath = normalizePath(path);
|
||||
|
||||
// Aviso de ausencia con token personal del alumno (sin sesión).
|
||||
// Absence notice sent with the attendee's personal token (no session).
|
||||
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@ type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
|
||||
// Colores de marca (mismo sistema que la web: index.css de apps/web).
|
||||
// Brand colors (same system as the web app: index.css in apps/web).
|
||||
const BRAND_600 = '#2544ea'
|
||||
const TEXT_STRONG = '#0f172a'
|
||||
const TEXT_MUTED = '#475569'
|
||||
const ON_ACCENT = '#ffffff'
|
||||
const LINK_BG = BRAND_600
|
||||
|
||||
// Logotipo embebido como data URI para que los mails no dependan de hosting.
|
||||
// Logo embedded as a data URI so the emails don't depend on hosting.
|
||||
function loadLogoTypoDataUri(): string {
|
||||
try {
|
||||
const base64 = readFileSync(
|
||||
@@ -66,7 +66,7 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
// With no SMTP configured (dev) the flow still doesn't break: it only logs a warning
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
@@ -111,8 +111,8 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||
// Add implementations and switch between them with EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ import {
|
||||
} from '../../lib/risk';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
/* Cuántas clases se miran hacia atrás por alumno. Es el techo real del modelo:
|
||||
los `class_sessions` no se crean solos, se materializan cuando alguien entra
|
||||
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20
|
||||
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el
|
||||
porcentaje de asistencia que muestra la tarjeta. */
|
||||
/* 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 = {
|
||||
@@ -42,7 +42,7 @@ type GroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
capacity: number | null;
|
||||
/** Los que todavía esperan cupo (`GroupWaitlistEntry` en PENDING). */
|
||||
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
||||
_count: { waitlist: number };
|
||||
};
|
||||
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||
@@ -54,10 +54,10 @@ type AttendanceRow = {
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
||||
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
|
||||
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
|
||||
// Risk status light summary per group for the group listing.
|
||||
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
|
||||
// any is at medium risk and NONE otherwise. The counters state the reason
|
||||
// (consecutive absences or low attendance) so the listing can name it.
|
||||
export class GetGroupsRiskOverview {
|
||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||
|
||||
@@ -92,10 +92,10 @@ export class GetGroupsRiskOverview {
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el
|
||||
historial completo del alumno, no sobre la ventana mensual. Sin recorte
|
||||
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`,
|
||||
sobre las clases del grupo y no sobre estas filas. */
|
||||
/* No date filter, as before: the status light streak counts over the
|
||||
attendee's full history, not over the monthly window. No cap either:
|
||||
the cut to the last 20 classes is done by `memberSessions`, over the
|
||||
group's classes and not over these rows. */
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: {
|
||||
@@ -118,9 +118,10 @@ export class GetGroupsRiskOverview {
|
||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||
|
||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
|
||||
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
|
||||
// a racha y aun así quedan por debajo del mínimo de asistencia.
|
||||
// Why there is risk, computed in the same pass: a member with an absence
|
||||
// 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>();
|
||||
|
||||
@@ -169,14 +170,14 @@ export class GetGroupsRiskOverview {
|
||||
}
|
||||
|
||||
/**
|
||||
* El resumen por nivel que consumen la tarjeta del listado y la sección de
|
||||
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función
|
||||
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla
|
||||
* no tenga dos copias: una acá y otra en el cliente.
|
||||
* The per-level summary consumed by the listing card and the Home follow-up
|
||||
* section. It comes from `getGroupAttendanceSummary`, the same domain function
|
||||
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||
* copies: one here and another in the client.
|
||||
*
|
||||
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen
|
||||
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo
|
||||
* para pintar el indicador.
|
||||
* `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
|
||||
* paint the indicator.
|
||||
*/
|
||||
function buildSummaryFields(
|
||||
group: GroupRow,
|
||||
@@ -194,9 +195,9 @@ function buildSummaryFields(
|
||||
.filter((attendee) => attendee.groupId === group.id)
|
||||
.map((attendee) => {
|
||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
||||
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej.
|
||||
// creado hoy pero con clases pasadas registradas), su fecha efectiva de
|
||||
// incorporación es la de la primera clase a la que se le tomó asistencia.
|
||||
// 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 = attendeeAttendances.reduce<Date | null>(
|
||||
(earliest, att) =>
|
||||
!earliest || att.classSession.startsAt < earliest
|
||||
@@ -257,18 +258,18 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
||||
return byAttendee;
|
||||
}
|
||||
|
||||
/* El universo de clases es el del grupo, no el de las filas de `Attendance`.
|
||||
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así
|
||||
que "esta clase pasó y no hay registro de este alumno" es un estado real y
|
||||
frecuente, no una falta. Si la lista se armara desde las filas de asistencia
|
||||
esas clases no existirían y la racha no se cortaría: dos faltas separadas por
|
||||
una clase sin marcar se contarían como tres seguidas.
|
||||
El dominio ya las trata como neutras (`status: null`), así que acá solo hay
|
||||
que elegir bien el universo y dejar el criterio en un solo lado.
|
||||
`sessions` viene de más reciente a más antigua, así que quedarse con las
|
||||
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El
|
||||
recorte va por alumno y no global para que un grupo con mucha historia no le
|
||||
robe ventana a los grupos que se listan después. */
|
||||
/* 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]));
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso.
|
||||
// Verifies the user is the group owner or a member. Returns the group if they have access.
|
||||
export async function findGroupForUser(
|
||||
db: AnalyticsAccessDb,
|
||||
groupId: string,
|
||||
|
||||
@@ -5,14 +5,14 @@ export type AttendanceStreamEntry = {
|
||||
|
||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||
|
||||
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
|
||||
/** Minimum streak of unexcused absences that already triggers risk. */
|
||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
||||
|
||||
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
|
||||
/** Monthly attendance (30-day window) below which there is risk. */
|
||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
||||
|
||||
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
|
||||
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
|
||||
// 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) {
|
||||
@@ -24,7 +24,7 @@ export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
return streak;
|
||||
}
|
||||
|
||||
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
|
||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.status === 'PRESENT') {
|
||||
@@ -34,8 +34,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Porcentaje de asistencia sobre el total de sesiones del período.
|
||||
// Las sesiones sin registrar cuentan como no asistidas.
|
||||
// Attendance rate over the total number of sessions in the period.
|
||||
// Sessions with no record count as not attended.
|
||||
export function monthlyAttendanceRate(
|
||||
entries: AttendanceStreamEntry[],
|
||||
totalSessions: number,
|
||||
@@ -47,7 +47,7 @@ export function monthlyAttendanceRate(
|
||||
return Math.round((present / totalSessions) * 100);
|
||||
}
|
||||
|
||||
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%.
|
||||
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
|
||||
export function classifyRisk(
|
||||
consecutiveAbsences: number,
|
||||
monthlyRate: number,
|
||||
|
||||
@@ -41,7 +41,7 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Cargar teléfonos existentes del grupo
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
|
||||
@@ -18,18 +18,18 @@ export class ListAttendees {
|
||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con
|
||||
una petición por miembro. Ambas relaciones vienen acotadas a propósito:
|
||||
la tabla de pagos crece un renglón por mes y para siempre, y el listado
|
||||
solo necesita el estado actual de cada persona. */
|
||||
/* Each row's summary travels in the same query instead of being built
|
||||
with one request per member. Both relations are capped on purpose:
|
||||
the payments table grows one row per month forever, and the listing
|
||||
only needs each person's current state. */
|
||||
db.attendee.findMany({
|
||||
...(where ? { where } : {}),
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
// Por fecha de la clase, no por `markedAt`: marcar la asistencia
|
||||
// tarde no debe cambiar qué clase cuenta como reciente.
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
|
||||
@@ -14,7 +14,7 @@ export type AttendeeRecord = {
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
/** Item del listado con el resumen de asistencia y cobro ya resuelto. */
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
|
||||
payments: {
|
||||
@@ -39,15 +39,15 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
};
|
||||
}
|
||||
|
||||
/* El renglón que resume el cobro vigente. Si hay algo impago manda el de
|
||||
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos
|
||||
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada
|
||||
impago, el último pago cerrado sirve para marcar la fila como al día. */
|
||||
/* The row that summarizes the current charge. If something is unpaid the
|
||||
oldest due date wins: someone carrying an old charge has to see how many
|
||||
days late they are, not the due date of a new charge. If nothing is left
|
||||
unpaid, the last closed payment serves to mark the row as ok. */
|
||||
function pickRelevantPayment(
|
||||
payments: AttendeeListItemRecord['payments'],
|
||||
): AttendeeListItem['payment'] {
|
||||
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos
|
||||
// acá también evita que un cargo anulado gane la fila por ser el más antiguo.
|
||||
// CANCELLED is not a charge. The query already filters them out, but dropping
|
||||
// them here too keeps a voided charge from winning the row for being the oldest.
|
||||
const byDueDate = payments
|
||||
.filter((payment) => payment.status !== 'CANCELLED')
|
||||
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
|
||||
@@ -60,8 +60,8 @@ function pickRelevantPayment(
|
||||
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
|
||||
}
|
||||
|
||||
/* La consulta viene en orden descendente; la fila los muestra de más antigua a
|
||||
más reciente para que el punto de la derecha sea el último hecho. */
|
||||
/* The query comes in descending order; the row shows them from oldest to most
|
||||
recent so the dot on the right is the latest event. */
|
||||
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
@@ -71,8 +71,8 @@ export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeL
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||
* Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
|
||||
* Keeps a leading '+' for international numbers.
|
||||
*/
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal.
|
||||
// Public route (whitelisted in session-auth): the attendee gets in with their personal token.
|
||||
route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
|
||||
const query = c.req.valid('query') as AbsenceQuery;
|
||||
const useCase = new GetAbsenceDetails();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token.
|
||||
// Public route (whitelisted in session-auth): the attendee reports an absence with a token.
|
||||
route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
|
||||
const payload = c.req.valid('json') as PublicNotifyAbsence;
|
||||
const useCase = new PublicNotifyAbsenceUseCase();
|
||||
|
||||
@@ -18,8 +18,8 @@ type PaymentLike = {
|
||||
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ó.
|
||||
// Payment status computed in real time (no denormalized column):
|
||||
// PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
|
||||
export function resolvePaymentStatus(
|
||||
payments: PaymentLike[],
|
||||
startOfToday: Date,
|
||||
@@ -52,7 +52,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión.
|
||||
// Verifies the user is the owner or a member of the group that owns the session.
|
||||
export function ensureSessionAccess(
|
||||
session: ClassSessionRecord & { group: GroupWithAccess },
|
||||
userId: string,
|
||||
|
||||
@@ -17,9 +17,9 @@ type RegisterAbsenceInput = {
|
||||
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.
|
||||
// Shared core of the absence notice (authenticated teacher and attendee with a token):
|
||||
// - Marks the attendance as EXCUSED (idempotent upsert).
|
||||
// - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot.
|
||||
export async function registerAbsence(
|
||||
deps: RegisterAbsenceDeps,
|
||||
input: RegisterAbsenceInput,
|
||||
|
||||
@@ -13,7 +13,7 @@ type ScheduledGroup = {
|
||||
time: string | null;
|
||||
};
|
||||
|
||||
// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor).
|
||||
// Computes which groups have a class today (from days/time and the teacher's time zone).
|
||||
export function buildTodayCandidates(
|
||||
groups: ScheduledGroup[],
|
||||
now: Date,
|
||||
@@ -37,7 +37,7 @@ export function buildTodayCandidates(
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids.
|
||||
// Materializes (idempotent upsert) today's ClassSession rows and returns their ids.
|
||||
export async function ensureTodaySessions(
|
||||
db: Pick<ClassesDb, 'classSession'>,
|
||||
candidates: TodaySessionCandidate[],
|
||||
|
||||
@@ -24,9 +24,9 @@ type ListGroupsDeps = {
|
||||
const OCCUPANCY_COUNT_INCLUDE = {
|
||||
_count: {
|
||||
select: {
|
||||
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
|
||||
// Group members. No status filter, same as the detail page counts.
|
||||
attendees: true,
|
||||
// Lista de espera: los que todavía esperan cupo (los revisados salen).
|
||||
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
|
||||
waitlist: { where: { status: 'PENDING' as const } },
|
||||
},
|
||||
},
|
||||
@@ -43,10 +43,10 @@ export class ListGroups {
|
||||
const now = this.deps.now ?? new Date();
|
||||
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
||||
|
||||
// Traemos los grupos del usuario con sus contadores y los ordenamos acá:
|
||||
// la próxima clase se deriva de días + hora, no hay columna por la que
|
||||
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la
|
||||
// zona horaria de la persona (o la del servidor si no viaja).
|
||||
// We fetch the user's groups with their counters and sort them here: the next
|
||||
// class is derived from days + time, there is no column to sort on in the
|
||||
// database. It's the same engine the home summary uses, with the person's
|
||||
// time zone (or the server's if it doesn't come along).
|
||||
const records: GroupListRecord[] = await db.group.findMany({
|
||||
where,
|
||||
include: OCCUPANCY_COUNT_INCLUDE,
|
||||
@@ -58,9 +58,9 @@ export class ListGroups {
|
||||
nextAt: nextOccurrenceAt(record, now, timeZone),
|
||||
}));
|
||||
|
||||
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
|
||||
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
|
||||
que era el criterio anterior de la lista. */
|
||||
/* A group with no schedule has no class to compare, so it goes last;
|
||||
between groups with the same class (or with no schedule) the newest one
|
||||
breaks the tie, which was the listing's previous criterion. */
|
||||
const ordered = withNextClass.sort((a, b) => {
|
||||
if (a.nextAt !== null && b.nextAt !== null) {
|
||||
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();
|
||||
|
||||
@@ -21,10 +21,10 @@ export type GroupRecord = {
|
||||
inviteToken?: string | null;
|
||||
};
|
||||
|
||||
/* El listado suma los contadores de ocupación a cada grupo para que la card los
|
||||
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma
|
||||
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de
|
||||
espera solo los que siguen esperando cupo (PENDING). */
|
||||
/* The listing adds the occupancy counters to each group so the card can show
|
||||
them without asking for one endpoint per group. They come from the `_count` of
|
||||
the same query: all the members (same as the detail page counts) and only the
|
||||
waitlist entries still waiting for a spot (PENDING). */
|
||||
export type GroupListRecord = GroupRecord & {
|
||||
_count?: { attendees: number; waitlist: number };
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { WeekDay } from '@gruperly/shared';
|
||||
|
||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City';
|
||||
|
||||
// Ventana (en horas) durante la que una clase ya arrancada se muestra como "en curso".
|
||||
// Window (in hours) during which an already started class shows as "in progress".
|
||||
export const CLASS_WINDOW_HOURS = 2;
|
||||
export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000;
|
||||
|
||||
@@ -21,7 +21,7 @@ export type NextClassOccurrence = {
|
||||
isNow: boolean;
|
||||
};
|
||||
|
||||
// Convierte un tiempo de "pared" (wall clock) expresado en `timeZone` al instante absoluto.
|
||||
// Converts a "wall clock" time expressed in `timeZone` into the absolute instant.
|
||||
export function zonedWallClockToUtc(wall: string, timeZone: string): Date {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall);
|
||||
if (!match) {
|
||||
@@ -145,8 +145,8 @@ function pad(value: number): string {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
// Instante absoluto de la clase de HOY (aunque la hora ya haya pasado), o null si el grupo
|
||||
// no tiene clase programada para el día de `now` en `timeZone`.
|
||||
// Absolute instant of TODAY's class (even if the time has already passed), or null if the
|
||||
// group has no class scheduled for `now`'s day in `timeZone`.
|
||||
export function todayOccurrence(opt: {
|
||||
days: WeekDay[];
|
||||
time: string;
|
||||
@@ -181,7 +181,7 @@ export function todayOccurrence(opt: {
|
||||
return zonedWallClockToUtc(wall, timeZone);
|
||||
}
|
||||
|
||||
// Primer instante del día de `now` en `timeZone` (medianoche local).
|
||||
// First instant of `now`'s day in `timeZone` (local midnight).
|
||||
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
||||
|
||||
@@ -78,8 +78,8 @@ describe('GET /groups-risk/overview', () => {
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// `toMatchObject` porque el item ahora arrastra también el resumen por nivel
|
||||
// que consume la tarjeta; acá se está probando el semáforo de siempre.
|
||||
// `toMatchObject` because the item now also carries the per-level summary
|
||||
// the card consumes; here we are testing the usual status light.
|
||||
expect(await res.json()).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
@@ -117,21 +117,21 @@ describe('GET /groups-risk/overview', () => {
|
||||
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
||||
]);
|
||||
prismaFetchAttendanceFindMany([
|
||||
// Dos faltas seguidas: cuenta en el motivo de faltas.
|
||||
// Two consecutive absences: counts toward the absence reason.
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||
// Sin racha, pero asiste menos de la mitad de las clases del mes.
|
||||
// No streak, but attends less than half of the month's classes.
|
||||
attendance('a-2', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-2', 's3', 'ABSENT', at(3)),
|
||||
attendance('a-2', 's4', 'ABSENT', at(4)),
|
||||
// Al día.
|
||||
// Ok.
|
||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-3', 's2', 'PRESENT', at(2)),
|
||||
attendance('a-3', 's3', 'PRESENT', at(3)),
|
||||
attendance('a-3', 's4', 'PRESENT', at(4)),
|
||||
// Otra vez por racha, en el otro grupo.
|
||||
// Again via streak, in the other group.
|
||||
attendance('b-1', 's5', 'ABSENT', at(1)),
|
||||
attendance('b-1', 's6', 'ABSENT', at(2)),
|
||||
]);
|
||||
@@ -160,9 +160,9 @@ describe('GET /groups-risk/overview', () => {
|
||||
});
|
||||
});
|
||||
|
||||
/* Lo que consume la tarjeta del listado. El semáforo de arriba ya tenía sus
|
||||
tests; lo que faltaba era fijar el payload nuevo contra el mismo endpoint,
|
||||
porque es el contrato que el frontend lee. */
|
||||
/* What the listing card consumes. The status light above already had its
|
||||
tests; what was missing was pinning the new payload against the same
|
||||
endpoint, because that is the contract the frontend reads. */
|
||||
it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
|
||||
prismaFetchAttendeeFindMany([
|
||||
@@ -175,10 +175,10 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// El mock ignora el `orderBy`, así que las filas van de la más reciente a la
|
||||
// más antigua como las devolvería Prisma: de ese orden depende la racha.
|
||||
// `at(n)` son n días hacia atrás; el resumen descarta lo que no ocurrió, así
|
||||
// que las fechas tienen que estar en el pasado y no en el futuro.
|
||||
// The mock ignores `orderBy`, so the rows come most recent first, as Prisma
|
||||
// would return them: the streak depends on that order.
|
||||
// `at(n)` is n days back; the summary drops what has not happened yet, so
|
||||
// the dates have to be in the past, not in the future.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
@@ -197,11 +197,11 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
riesgoAlto: 1,
|
||||
atencion: 1,
|
||||
ok: 1,
|
||||
// El cupo es de 5 y hay 3 miembros, no 2: los lugares libres se calculan
|
||||
// contra el cupo y no como "los que no tienen ninguna señal".
|
||||
// Capacity is 5 and there are 3 members, not 2: free spots are computed
|
||||
// against capacity, not as "the ones with no signal at all".
|
||||
libres: 2,
|
||||
enEspera: 2,
|
||||
// Promedio de las tasas ya redondeadas por persona: 0, 33 y 100 → 44.
|
||||
// Average of the already-rounded per-person rates: 0, 33 and 100 → 44.
|
||||
asistencia: 44,
|
||||
});
|
||||
expect(items[0].urgentes).toEqual([
|
||||
@@ -218,8 +218,8 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
fullName: 'Diego Soto',
|
||||
level: 'atencion',
|
||||
consecutiveAbsences: 2,
|
||||
// Cuenta desde su última clase con presencia, no desde la más
|
||||
// reciente del grupo: la suya fue hace 3 días.
|
||||
// Counted from their last class they attended, not from the group's
|
||||
// most recent one: theirs was 3 days ago.
|
||||
daysSinceLastAttendance: 3,
|
||||
attendanceRate: 33,
|
||||
},
|
||||
@@ -267,9 +267,9 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// Falta, clase sin marcar, falta. Leyendo solo las filas de `Attendance` esto
|
||||
// parecería una racha de 2 y el grupo saldría en atención; la clase del medio
|
||||
// pasó y no tiene registro, así que la racha real es de 1.
|
||||
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
|
||||
// would look like a streak of 2 and the group would land in attention; the
|
||||
// middle class happened and has no record, so the real streak is 1.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
@@ -289,7 +289,7 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
|
||||
level: 'ok',
|
||||
consecutiveAbsences: 1,
|
||||
daysSinceLastAttendance: 1,
|
||||
// Las dos clases con dato fueron falta; la del medio no entra al promedio.
|
||||
// Both marked classes were absences; the middle one does not go into the average.
|
||||
attendanceRate: 0,
|
||||
},
|
||||
]);
|
||||
@@ -303,9 +303,9 @@ it('las faltas pegadas hasta la última clase sí cuentan como racha', async ()
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// La racha se cuenta hacia atrás desde la clase más reciente, así que llegan
|
||||
// justo hasta el final: s1 y s2 pegadas, y la de hace 3 días sin registrar,
|
||||
// que queda antes de la racha y no la toca.
|
||||
// The streak is counted backwards from the most recent class, so they reach
|
||||
// exactly the end: s1 and s2 back to back, and the one 3 days ago is
|
||||
// unmarked, which falls before the streak and does not touch it.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
@@ -336,10 +336,11 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// Mismas dos faltas pegadas del caso anterior, pero la clase más reciente
|
||||
// (s1) es la que no tiene registro. Como la racha se cuenta desde el final y
|
||||
// "sin dato" no es ausencia, no hay racha: se ve la asimetría a propósito,
|
||||
// porque es lo mismo que ya pasa con una clase justificada.
|
||||
// The same two back-to-back absences as the previous case, but the most
|
||||
// recent class (s1) is the one with no record. Since the streak is counted
|
||||
// from the end and "no record" is not an absence, there is no streak: the
|
||||
// asymmetry is there on purpose, because it is the same thing that already
|
||||
// happens with an excused class.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
@@ -366,7 +367,7 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
|
||||
|
||||
it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]);
|
||||
// El alumno fue creado hoy (offset 0), pero tiene 3 faltas en clases de hace 7, 3 y 1 días.
|
||||
// The attendee was created today (offset 0), but has 3 absences in classes 7, 3 and 1 days ago.
|
||||
prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
@@ -388,10 +389,10 @@ it('reconoce asistencias previas a la fecha de alta del alumno como historial v
|
||||
expect(items[0].absenceStreakCount).toBe(1);
|
||||
});
|
||||
|
||||
/* El use-case pide `capacity` y el conteo de lista de espera para poder calcular
|
||||
los lugares libres, y `fullName` + `createdAt` de cada alumno para el resumen
|
||||
por nivel. Los fixtures los dan para que los tests viejos no tengan que
|
||||
saber de eso. */
|
||||
/* The use-case asks for `capacity` and the waitlist count to compute the
|
||||
free spots, and `fullName` + `createdAt` of every attendee for the per-level
|
||||
summary. The fixtures provide them so the older tests don't have to know
|
||||
about that. */
|
||||
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
|
||||
return { id, name, capacity, _count: { waitlist: waiting } };
|
||||
}
|
||||
@@ -416,9 +417,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
|
||||
db.attendance.findMany.mockResolvedValue(rows);
|
||||
}
|
||||
|
||||
/* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo
|
||||
con las filas de asistencia, y sin ese cruce toda clase quedaría sin registro
|
||||
para todo el mundo. */
|
||||
/* The `classSessionId` matters: the summary is built by cross-referencing the
|
||||
group's class sessions with the attendance rows, and without that join every
|
||||
class would have no record for everyone. */
|
||||
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
|
||||
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
|
||||
}
|
||||
@@ -8,30 +8,29 @@ import {
|
||||
summarizeMemberAttendance,
|
||||
} from '@gruperly/shared';
|
||||
|
||||
/* La regla de riesgo es de negocio, no de pantalla: estos tests la fijan para
|
||||
que cambiar un umbral o refactorizar el filtro de clases no mueva el
|
||||
semáforo de la lista de grupos en silencio.
|
||||
/* The risk rule is business logic, not a screen concern: these tests pin it so
|
||||
that changing a threshold or refactoring the class filter doesn't quietly
|
||||
move the status light of the group list.
|
||||
|
||||
Dos helpers de armazón:
|
||||
Two test-scaffold helpers:
|
||||
|
||||
- `dense` mete las clases en días consecutivos, para que "hace cuánto no lo
|
||||
vemos" quede siempre cerca y el caso aísle la regla que dice probar (una
|
||||
clase por semana haría saltar el umbral de inactividad en casi todo).
|
||||
- `series` respeta los offsets que se le pasan, para los casos que sí
|
||||
necesitan huecos.
|
||||
- `dense` puts the classes on consecutive days, so that "how long since we
|
||||
saw them" is always close by and the case isolates the rule it claims to
|
||||
test (one class a week would trip the inactivity threshold almost always).
|
||||
- `series` honors the offsets it is given, for the cases that do need gaps.
|
||||
|
||||
Todas las fechas se cuelgan de un `NOW` fijo: la función recibe el momento
|
||||
como argumento justamente para poder testear sin reloj. */
|
||||
All dates hang off a fixed `NOW`: the function takes the moment as an
|
||||
argument precisely so it can be tested without a clock. */
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const NOW = new Date('2026-09-30T20:00:00.000Z');
|
||||
|
||||
/** Días hacia atrás desde `NOW`, en ISO. Negativo = clase futura. */
|
||||
/** Days back from `NOW`, in ISO. Negative = future class. */
|
||||
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
|
||||
|
||||
type Status = MemberClassSession['status'];
|
||||
|
||||
/** Clases en días consecutivos, de la más antigua a la más reciente. */
|
||||
/** Classes on consecutive days, oldest first. */
|
||||
function dense(statuses: Status[]): MemberClassSession[] {
|
||||
return statuses.map((status, index) => ({
|
||||
sessionId: `ses_${statuses.length - index}`,
|
||||
@@ -40,7 +39,7 @@ function dense(statuses: Status[]): MemberClassSession[] {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Clases con los offsets que se le pasen, en cualquier orden. */
|
||||
/** Classes with the offsets given, in any order. */
|
||||
function series(rows: [Status, number][]): MemberClassSession[] {
|
||||
return rows.map(([status, offsetDays], index) => ({
|
||||
sessionId: `ses_${index}`,
|
||||
@@ -69,7 +68,7 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('no cuenta clases que todavía no ocurrieron', () => {
|
||||
// Asistió a las tres últimas y falta a las tres siguientes: nadie se está yendo.
|
||||
// Attended the last three and is absent for the next three: nobody is drifting away.
|
||||
const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]]));
|
||||
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
|
||||
});
|
||||
@@ -78,14 +77,15 @@ describe('getMemberAttendanceRisk', () => {
|
||||
const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(3);
|
||||
// 4 días sin aparecer: el nivel viene de la racha, no del tiempo sin venir.
|
||||
// 4 days since last showing up: the level comes from the streak, not from the
|
||||
// time since they last came.
|
||||
expect(señales.daysSinceLastAttendance).toBe(4);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('una racha larguísima sin ninguna clase con presencia igual es riesgo alto', () => {
|
||||
// Nunca asistió a una clase elegible: la referencia para "hace cuánto no lo
|
||||
// vemos" es la última clase, así que no queda en verde para siempre.
|
||||
// Never attended an eligible class: the reference for "how long since we saw
|
||||
// them" is the last class, so it doesn't stay green forever.
|
||||
const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(5);
|
||||
@@ -99,8 +99,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
|
||||
// Una sola falta, la más reciente: la racha no llega. El nivel lo dispara
|
||||
// el tiempo sin aparecer.
|
||||
// A single absence, the most recent one: the streak doesn't reach. What drives
|
||||
// the level is the time since they last showed up.
|
||||
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -110,8 +110,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
|
||||
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
|
||||
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
|
||||
// Dos faltas de racha: la atención le llega por la racha, y los 10 días
|
||||
// justos no mueven el nivel.
|
||||
// Two streak absences: attention comes from the streak, and exactly 10 days
|
||||
// does not move the level.
|
||||
expect(
|
||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
|
||||
).toBe('atencion');
|
||||
@@ -121,9 +121,9 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una tendencia a la baja da atención', () => {
|
||||
// 12 clases con dato. Las 4 anteriores al 100%, las 4 últimas al 50%, y la
|
||||
// más reciente es un PRESENT: racha 0 y asistencia reciente, así que la
|
||||
// tendencia es lo único que puede disparar la alerta.
|
||||
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
|
||||
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
|
||||
// the only thing that can raise the alert.
|
||||
const candidato = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
|
||||
@@ -135,8 +135,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('perder una sola clase no es tendencia', () => {
|
||||
// Mismo caso que el anterior con una clase menos perdida en la ventana
|
||||
// reciente: 3 de 4 contra 4 de 4. Es ruido, no una caída.
|
||||
// Same case as the previous one with one class fewer missed in the recent
|
||||
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
|
||||
const estable = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
|
||||
@@ -145,16 +145,16 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('la tendencia necesita historia para las dos ventanas', () => {
|
||||
// 5 clases con dato: la ventana anterior quedaría con una sola, así que no
|
||||
// hay contra qué comparar.
|
||||
// 5 marked classes: the previous window would be left with a single one, so
|
||||
// there is nothing to compare against.
|
||||
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
|
||||
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('la racha manda sobre la tendencia', () => {
|
||||
// 16 clases: 4 anteriores al 100%, y las 4 últimas con 3 faltas seguidas
|
||||
// una clase con presencia. La tendencia sola daría atención; las 3 faltas
|
||||
// seguidas de punta dan riesgo alto, que es lo que tiene que ganar.
|
||||
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
|
||||
// absences and one attended class. The trend alone would give attention;
|
||||
// the 3 trailing absences give high risk, which is what has to win.
|
||||
const alumno = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
|
||||
@@ -166,8 +166,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
|
||||
// Faltó, la de en medio no tiene registro, volvió a faltar. La racha real
|
||||
// es de una, no de dos.
|
||||
// Absent, the middle one has no record, absent again. The real streak
|
||||
// is one, not two.
|
||||
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(conHueco, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -177,8 +177,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una clase justificada es la clase que no cuenta', () => {
|
||||
// Faltó, avisó, volvió a faltar: la racha es de una, y el promedio ignora la
|
||||
// clase justificada en vez de contarla como asistencia o como falta.
|
||||
// Absent, notified, absent again: the streak is one, and the average ignores
|
||||
// the excused class instead of counting it as attendance or as an absence.
|
||||
const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(justificada, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -293,7 +293,7 @@ describe('getGroupAttendanceSummary', () => {
|
||||
members: [
|
||||
conNivel('a', 'ok'),
|
||||
{ attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) },
|
||||
// Recién Chess: sin clases con dato, no mueve el promedio.
|
||||
// Just joined Chess: no marked classes, so they don't move the average.
|
||||
{ attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
|
||||
],
|
||||
now: NOW,
|
||||
|
||||
@@ -412,7 +412,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
|
||||
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
// Simular que ya existe un alumno con teléfono '11111111'
|
||||
// Simulate that an attendee with phone '11111111' already exists
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ phone: '11111111' },
|
||||
] as never);
|
||||
@@ -434,8 +434,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
attendees: [
|
||||
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
|
||||
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Ya existe en BD
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicado dentro del lote
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
|
||||
],
|
||||
}),
|
||||
});
|
||||
@@ -484,8 +484,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
// El resumen de la fila se pide en la misma consulta: una petición por
|
||||
// miembro sería N+1 sobre un listado de hasta 100.
|
||||
// The row summary is requested in the same query: one request per
|
||||
// member would be N+1 over a listing of up to 100.
|
||||
include: {
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
|
||||
@@ -2,8 +2,8 @@ import { describe, expect, it } from 'bun:test';
|
||||
import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers';
|
||||
import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
/* El resumen de la fila se arma en memoria: qué clase cuenta como reciente y
|
||||
qué cobro se muestra. Son las dos decisiones que la fila leen. */
|
||||
/* The row summary is built in memory: which class counts as recent and
|
||||
which payment is shown. Those are the two decisions the row reads. */
|
||||
|
||||
function record(
|
||||
overrides: Partial<AttendeeListItemRecord> = {},
|
||||
@@ -32,7 +32,7 @@ describe('toAttendeeListItemDto', () => {
|
||||
it('invierte la asistencia para que la clase más reciente quede a la derecha', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
// Llega de más reciente a más antigua.
|
||||
// It arrives from most recent to oldest.
|
||||
attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -33,7 +33,7 @@ const attendeeRow = {
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
};
|
||||
|
||||
// Lo que devuelve el mock de Prisma: la fila más las relaciones del resumen.
|
||||
// What the Prisma mock returns: the row plus the summary relations.
|
||||
const attendee = {
|
||||
...attendeeRow,
|
||||
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
|
||||
@@ -58,8 +58,8 @@ describe('attendees routes', () => {
|
||||
...attendeeRow,
|
||||
createdAt: attendeeRow.createdAt.toISOString(),
|
||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||
// La consulta viene de más reciente a más antigua; la fila los
|
||||
// muestra al revés, con la clase más reciente a la derecha.
|
||||
// The query comes most recent first; the row shows them
|
||||
// the other way around, with the most recent class on the right.
|
||||
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
|
||||
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
|
||||
},
|
||||
|
||||
@@ -77,7 +77,7 @@ function makeSession(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Fecha "hoy" a las 19:00 UTC, del día real del runner.
|
||||
// "Today" at 19:00 UTC, on the runner's real day.
|
||||
function todayAtUtc() {
|
||||
const date = new Date();
|
||||
date.setUTCHours(19, 0, 0, 0);
|
||||
|
||||
@@ -84,8 +84,8 @@ describe('groups routes', () => {
|
||||
const where = {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
};
|
||||
// Los contadores de ocupación viajan en la misma consulta; la lista de
|
||||
// espera cuenta solo los PENDING, los que siguen esperando cupo.
|
||||
// The occupancy counters ride along in the same query; the waitlist
|
||||
// counts only PENDING, the ones still waiting for a spot.
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where,
|
||||
include: {
|
||||
@@ -131,8 +131,8 @@ describe('groups routes', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
// Lunes 2026-01-05 al mediodía en Ciudad de México: la clase de las 18:00
|
||||
// todavía no empieza, así que ese grupo va primero.
|
||||
// Monday 2026-01-05 at noon in Mexico City: the 18:00 class
|
||||
// hasn't started yet, so that group goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
@@ -140,7 +140,7 @@ describe('groups routes', () => {
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
// A igual clase se pone delante el más nuevo, que era el criterio anterior.
|
||||
// On a tie the newest one goes first, which was the previous criterion.
|
||||
expect(result.value.data.map((item) => item.id)).toEqual([
|
||||
'hoy-tarde',
|
||||
'hoy-tarde-viejo',
|
||||
@@ -157,8 +157,8 @@ describe('groups routes', () => {
|
||||
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// Lunes al mediodía: la clase de las 10:00 de A ya pasó, así que su
|
||||
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero.
|
||||
// Monday at noon: A's 10:00 class already happened, so its
|
||||
// next occurrence is next Monday and B (Wednesday) goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
|
||||
@@ -5,7 +5,7 @@ const TZ = 'America/Mexico_City';
|
||||
|
||||
describe('nextClassOccurrence', () => {
|
||||
it('devuelve la próxima clase de hoy cuando aún no arrancó', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -21,7 +21,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('marca en curso si la clase arrancó hace menos de la ventana', () => {
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // miércoles 19:00 hora CDMX (1 h tras la clase)
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // Wednesday 19:00 CDMX time (1 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -37,7 +37,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('salta a la próxima semana si la clase ya pasó la ventana', () => {
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // miércoles 21:00 hora CDMX (3 h tras la clase)
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // Wednesday 21:00 CDMX time (3 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -53,7 +53,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('elige la ocurrencia más próxima entre varios días', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
|
||||
@@ -69,7 +69,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('cruza de mes sin problema', () => {
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // martes 12:00 hora CDMX (último día de septiembre es miércoles 30)
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // Tuesday 12:00 CDMX time (September's last day is Wednesday the 30th)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['THURSDAY'],
|
||||
|
||||
@@ -193,7 +193,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires (UTC-3). La clase de las 10:00 ya arrancó.
|
||||
// 10:23 in Buenos Aires (UTC-3). The 10:00 class already started.
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' });
|
||||
|
||||
@@ -212,7 +212,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires, pero la zona por defecto es CDMX → las 07:23 CDMX (aún no empieza).
|
||||
// 10:23 in Buenos Aires, but the default zone is CDMX → 07:23 CDMX (not started yet).
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId);
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('session auth', () => {
|
||||
it('classifies absence notification endpoints as public (token-based)', () => {
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).toBe(true);
|
||||
// Las rutas autenticadas de clases siguen protegidas.
|
||||
// The authenticated class routes stay protected.
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/today')).toBe(false);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false);
|
||||
|
||||
Reference in New Issue
Block a user