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:
@@ -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