diff --git a/.env.example b/.env.example index 6c4dc94..ac8239f 100644 --- a/.env.example +++ b/.env.example @@ -1,31 +1,33 @@ -# Plantilla de variables para `docker compose`. +# Variable template for `docker compose`. # -# Local: copiá este archivo a `.env` en la raíz y completá los valores. -# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña -# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del -# compose, que es de donde salen los `${...}`). +# Local: copy this file to `.env` at the root and fill in the values. +# Dokploy: no file needed; define the same variables in the Environment tab of +# the Compose service (Dokploy writes them to a `.env` next to the compose +# file, which is where the `${...}` come from). -# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y -# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten -# dominio y por lo tanto la cookie de sesión es first-party. +# Public origin of the app, no trailing slash. The same value feeds WEB_URL and +# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a +# domain, so the session cookie is first-party. WEB_URL="http://localhost:8080" -# PostgreSQL de producción. -# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala -# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza -# el fragmento y falla con P1013 "invalid port number in database URL". +# Production PostgreSQL. +# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space, +# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the +# URL where the fragment starts and fails with P1013 "invalid port number in +# database URL". DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public" -# Generalo con: openssl rand -base64 32 +# Generate it with: openssl rand -base64 32 BETTER_AUTH_SECRET="" -# ── Opcionales ─────────────────────────────────────────────────────────────── +# ── Optional ───────────────────────────────────────────────────────────────── -# Login social con Google. Sin client id/secret no se registra el provider. +# Social login with Google. Without a client id/secret the provider is not +# registered. # GOOGLE_CLIENT_ID="" # GOOGLE_CLIENT_SECRET="" -# Envío de emails (mismas variables que apps/backend/.env.example). +# Email sending (same variables as apps/backend/.env.example). # EMAIL_PROVIDER="smtp" # EMAIL_SERVER_HOST="" # EMAIL_SERVER_PORT="587" @@ -33,6 +35,7 @@ BETTER_AUTH_SECRET="" # EMAIL_SERVER_PASSWORD="" # EMAIL_FROM="Gruperly " -# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga -# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado). +# Only if you want the API on another domain: it is baked into the Vite bundle +# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same +# origin (recommended). # VITE_API_URL="" diff --git a/Dockerfile.backend b/Dockerfile.backend index d3956b5..a5662a9 100644 --- a/Dockerfile.backend +++ b/Dockerfile.backend @@ -5,21 +5,21 @@ FROM oven/bun:1.4-alpine AS base WORKDIR /app ENV CI=1 -# ─── Dependencias ──────────────────────────────────────────────────────────── -# Solo los package.json:bun no necesita el código fuente para resolver el lockfile. +# ─── Dependencies ──────────────────────────────────────────────────────────── +# Only the package.json files: bun needs no source code to resolve the lockfile. FROM base AS deps COPY package.json bun.lock bunfig.toml turbo.json ./ COPY apps/backend/package.json ./apps/backend/ COPY apps/web/package.json ./apps/web/ COPY packages/config/package.json ./packages/config/ COPY packages/shared/package.json ./packages/shared/ -# El cache global de bun pesa ~370MB: se borra en la misma capa. +# bun's global cache weighs ~370MB: it is dropped in the same layer. RUN bun install --frozen-lockfile && rm -rf /root/.bun/install # ─── Prisma Client ─────────────────────────────────────────────────────────── -# El generator "prisma-client" emite TypeScript, así que el cliente generado se -# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no -# necesita conexión, solo leer el schema. +# The "prisma-client" generator emits TypeScript, so the generated client runs +# with Bun without compilation. The URL is a placeholder: `generate` only needs +# to read the schema, not connect to a database. FROM deps AS generate ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder ENV DATABASE_URL=$DATABASE_URL @@ -28,7 +28,7 @@ COPY apps/backend/prisma ./apps/backend/prisma WORKDIR /app/apps/backend RUN bun run db:generate -# ─── Imagen de la API ──────────────────────────────────────────────────────── +# ─── API image ─────────────────────────────────────────────────────────────── FROM base AS api ENV NODE_ENV=production \ PORT=4000 @@ -37,30 +37,30 @@ COPY package.json bun.lock bunfig.toml ./ COPY apps/backend/package.json ./apps/backend/ COPY packages/config/package.json ./packages/config/ COPY packages/shared/package.json ./packages/shared/ -# `prisma` y `dotenv` son dependencies (no dev) porque el entrypoint corre -# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto -# del tooling: biome, typescript, turbo. +# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs +# `prisma migrate deploy` on every boot. With `--production` the rest of the +# tooling does not come in: biome, typescript, turbo. RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install -# El CLI de Prisma carga prisma.config.ts, que apunta al schema. +# The Prisma CLI loads prisma.config.ts, which points to the schema. COPY apps/backend/prisma ./apps/backend/prisma COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts COPY --from=generate /app/apps/backend/generated ./apps/backend/generated COPY apps/backend/tsconfig.json ./apps/backend/ COPY apps/backend/src ./apps/backend/src -# @gruperly/shared se consume como fuente TS; @gruperly/config aporta el -# tsconfig base del que extiende el tsconfig del backend. +# @gruperly/shared is consumed as TS source; @gruperly/config provides the base +# tsconfig that the backend tsconfig extends. COPY packages ./packages COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh RUN chmod +x /usr/local/bin/docker-entrypoint.sh WORKDIR /app/apps/backend EXPOSE 4000 -# Sin `${...}`: el CMD corre bajo /bin/sh (ash), donde eso es un error de sintaxis. +# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error. HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] -# Bun ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json, -# igual que `bun start` en local. +# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json, +# same as `bun start` locally. CMD ["bun", "src/server.ts"] diff --git a/Dockerfile.web b/Dockerfile.web index 06ceae0..d7509c9 100644 --- a/Dockerfile.web +++ b/Dockerfile.web @@ -5,27 +5,27 @@ FROM oven/bun:1.4-alpine AS base WORKDIR /app ENV CI=1 -# ─── Dependencias ──────────────────────────────────────────────────────────── +# ─── Dependencies ──────────────────────────────────────────────────────────── FROM base AS deps COPY package.json bun.lock bunfig.toml turbo.json ./ COPY apps/backend/package.json ./apps/backend/ COPY apps/web/package.json ./apps/web/ COPY packages/config/package.json ./packages/config/ COPY packages/shared/package.json ./packages/shared/ -# El cache global de bun pesa ~370MB: se borra en la misma capa. +# bun's global cache weighs ~370MB: it is dropped in the same layer. RUN bun install --frozen-lockfile && rm -rf /root/.bun/install -# ─── Build de Vite ─────────────────────────────────────────────────────────── +# ─── Vite build ────────────────────────────────────────────────────────────── FROM deps AS build -# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime. -# Vacío = mismo origen: el proxy /api de nginx hace de API. +# Vite replaces import.meta.env.* at build time, not at runtime. +# Empty = same origin: nginx's /api proxy acts as the API. ARG VITE_API_URL="" ENV VITE_API_URL=$VITE_API_URL COPY apps/web ./apps/web COPY packages ./packages RUN bun --filter @gruperly/web build -# ─── Imagen final ──────────────────────────────────────────────────────────── +# ─── Final image ───────────────────────────────────────────────────────────── FROM nginx:1.27-alpine AS web COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/apps/web/dist /usr/share/nginx/html diff --git a/apps/backend/docker-entrypoint.sh b/apps/backend/docker-entrypoint.sh index 9becb38..d30ad75 100755 --- a/apps/backend/docker-entrypoint.sh +++ b/apps/backend/docker-entrypoint.sh @@ -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 "$@" diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index def791f..f6549b7 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -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; } diff --git a/apps/backend/src/lib/email.ts b/apps/backend/src/lib/email.ts index 83abbcf..f320090 100644 --- a/apps/backend/src/lib/email.ts +++ b/apps/backend/src/lib/email.ts @@ -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() } diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts index fcec039..c9bd9e9 100644 --- a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts @@ -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, - /* 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(); - // 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(); const lowAttendanceCountByGroup = new Map(); @@ -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( (earliest, att) => !earliest || att.classSession.startsAt < earliest @@ -257,18 +258,18 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map [row.classSessionId, row.status])); diff --git a/apps/backend/src/modules/analytics/lib/access.ts b/apps/backend/src/modules/analytics/lib/access.ts index 48c03bf..91c803a 100644 --- a/apps/backend/src/modules/analytics/lib/access.ts +++ b/apps/backend/src/modules/analytics/lib/access.ts @@ -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, diff --git a/apps/backend/src/modules/analytics/lib/risk.ts b/apps/backend/src/modules/analytics/lib/risk.ts index affd8bc..5fef6eb 100644 --- a/apps/backend/src/modules/analytics/lib/risk.ts +++ b/apps/backend/src/modules/analytics/lib/risk.ts @@ -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, diff --git a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts index 6c465c7..b457784 100644 --- a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts @@ -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 }, diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts index c3f81a4..e9438df 100644 --- a/apps/backend/src/modules/attendees/features/get-all/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts @@ -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, diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 7a6cde9..d3b86bb 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -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(); diff --git a/apps/backend/src/modules/classes/features/public-details/route.ts b/apps/backend/src/modules/classes/features/public-details/route.ts index 4f62e3c..55fbb05 100644 --- a/apps/backend/src/modules/classes/features/public-details/route.ts +++ b/apps/backend/src/modules/classes/features/public-details/route.ts @@ -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(); diff --git a/apps/backend/src/modules/classes/features/public-notify/route.ts b/apps/backend/src/modules/classes/features/public-notify/route.ts index a44c2e2..850b46c 100644 --- a/apps/backend/src/modules/classes/features/public-notify/route.ts +++ b/apps/backend/src/modules/classes/features/public-notify/route.ts @@ -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(); diff --git a/apps/backend/src/modules/classes/lib/helpers.ts b/apps/backend/src/modules/classes/lib/helpers.ts index fcac3fc..706085b 100644 --- a/apps/backend/src/modules/classes/lib/helpers.ts +++ b/apps/backend/src/modules/classes/lib/helpers.ts @@ -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, diff --git a/apps/backend/src/modules/classes/lib/notify.ts b/apps/backend/src/modules/classes/lib/notify.ts index a456341..b0c6e1c 100644 --- a/apps/backend/src/modules/classes/lib/notify.ts +++ b/apps/backend/src/modules/classes/lib/notify.ts @@ -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, diff --git a/apps/backend/src/modules/classes/lib/sessions.ts b/apps/backend/src/modules/classes/lib/sessions.ts index 6af8e49..d5a5965 100644 --- a/apps/backend/src/modules/classes/lib/sessions.ts +++ b/apps/backend/src/modules/classes/lib/sessions.ts @@ -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, candidates: TodaySessionCandidate[], diff --git a/apps/backend/src/modules/groups/features/get-all/use-case.ts b/apps/backend/src/modules/groups/features/get-all/use-case.ts index e174ad6..fd2bdfe 100644 --- a/apps/backend/src/modules/groups/features/get-all/use-case.ts +++ b/apps/backend/src/modules/groups/features/get-all/use-case.ts @@ -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(); diff --git a/apps/backend/src/modules/groups/lib/helpers.ts b/apps/backend/src/modules/groups/lib/helpers.ts index 52b37e4..f2efc8f 100644 --- a/apps/backend/src/modules/groups/lib/helpers.ts +++ b/apps/backend/src/modules/groups/lib/helpers.ts @@ -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 }; }; diff --git a/apps/backend/src/modules/home/lib/scheduler.ts b/apps/backend/src/modules/home/lib/scheduler.ts index a9f4fbf..633935b 100644 --- a/apps/backend/src/modules/home/lib/scheduler.ts +++ b/apps/backend/src/modules/home/lib/scheduler.ts @@ -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); diff --git a/apps/backend/test/analytics-groups-risk.test.ts b/apps/backend/test/analytics-groups-risk.test.ts index 5ef740f..f5886f3 100644 --- a/apps/backend/test/analytics-groups-risk.test.ts +++ b/apps/backend/test/analytics-groups-risk.test.ts @@ -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 } }; } \ No newline at end of file diff --git a/apps/backend/test/attendance-risk.test.ts b/apps/backend/test/attendance-risk.test.ts index fccd9d0..5e94bac 100644 --- a/apps/backend/test/attendance-risk.test.ts +++ b/apps/backend/test/attendance-risk.test.ts @@ -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, diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts index e2608c7..4ffbb54 100644 --- a/apps/backend/test/attendees-incorporation.test.ts +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -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' } }, diff --git a/apps/backend/test/attendees-list-item.test.ts b/apps/backend/test/attendees-list-item.test.ts index 4bfae10..5a77cf1 100644 --- a/apps/backend/test/attendees-list-item.test.ts +++ b/apps/backend/test/attendees-list-item.test.ts @@ -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 = {}, @@ -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' }], }), ); diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index 1aa7cb0..4cf4098 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -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' }, }, diff --git a/apps/backend/test/classes.test.ts b/apps/backend/test/classes.test.ts index 3daf37b..bd0012e 100644 --- a/apps/backend/test/classes.test.ts +++ b/apps/backend/test/classes.test.ts @@ -77,7 +77,7 @@ function makeSession(overrides: Record = {}) { }; } -// 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); diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts index cf9332b..9e141a6 100644 --- a/apps/backend/test/groups.test.ts +++ b/apps/backend/test/groups.test.ts @@ -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'), diff --git a/apps/backend/test/home-scheduler.test.ts b/apps/backend/test/home-scheduler.test.ts index dba01c2..fabb0cb 100644 --- a/apps/backend/test/home-scheduler.test.ts +++ b/apps/backend/test/home-scheduler.test.ts @@ -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'], diff --git a/apps/backend/test/home.test.ts b/apps/backend/test/home.test.ts index a8a427b..b785603 100644 --- a/apps/backend/test/home.test.ts +++ b/apps/backend/test/home.test.ts @@ -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); diff --git a/apps/backend/test/session-auth.test.ts b/apps/backend/test/session-auth.test.ts index 931a1d1..760e2c9 100644 --- a/apps/backend/test/session-auth.test.ts +++ b/apps/backend/test/session-auth.test.ts @@ -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); diff --git a/apps/web/index.html b/apps/web/index.html index 1e4e453..ddce394 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,14 +2,14 @@ - + Gruperly - + diff --git a/apps/web/scripts/generate-icons.ts b/apps/web/scripts/generate-icons.ts index ec361cd..ba92f48 100644 --- a/apps/web/scripts/generate-icons.ts +++ b/apps/web/scripts/generate-icons.ts @@ -1,11 +1,11 @@ /** - * Genera el set de iconos PWA desde el isotipo SVG de marca. + * Generates the PWA icon set from the brand isotype SVG. * - * Uso: bun --filter @gruperly/web icons + * Usage: bun --filter @gruperly/web icons * - * Las salidas se versionan en `public/`; el build de Vite no las regenera - * (sharp es una devDependency y no debe entrar en la imagen de Docker). - * Re-correr solo cuando cambia `src/assets/brand/isotipo-y-organica.svg`. + * The outputs are versioned in `public/`; the Vite build does not regenerate + * them (sharp is a devDependency and must not end up in the Docker image). + * Re-run only when `src/assets/brand/isotipo-y-organica.svg` changes. */ import { mkdir, readFile, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' @@ -16,30 +16,30 @@ const webDir = dirname(dirname(fileURLToPath(import.meta.url))) const source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg') const publicDir = join(webDir, 'public') -/** Fondo del tema claro; también sirve de lienzo para los iconos opacos. */ +/** Light theme background; it also serves as the canvas for opaque icons. */ const BACKGROUND = '#ffffff' const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const type IconTarget = { file: string size: number - /** Rellena el lienzo con `BACKGROUND` en vez de dejar transparencia. */ + /** Fills the canvas with `BACKGROUND` instead of leaving it transparent. */ opaque: boolean - /** Fracción del lado que ocupa el logo. 1 = sin padding. */ + /** Fraction of the side the logo takes up. 1 = no padding. */ contentRatio: number } const targets: IconTarget[] = [ { file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 }, { file: 'pwa-512x512.png', size: 512, opaque: false, contentRatio: 0.9 }, - // Android recorta los iconos adaptativos en círculo: el contenido útil - // vive en el 80% central del canvas, así que el logo va over white y escalado. + // Android crops adaptive icons in a circle: the useful content lives in the + // central 80% of the canvas, so the logo goes on white and scaled. { file: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 }, { file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 }, ] -// El viewBox del isotipo no arranca en 0 y deja aire alrededor del glifo: -// `trim` recorta ese margen para que el encuadre use el área real del dibujo. +// The isotype viewBox does not start at 0 and leaves air around the glyph: +// `trim` crops that margin so the framing uses the drawing's real area. const logo = await sharp(await readFile(source), { density: 512 }) .trim({ threshold: 1 }) .png() diff --git a/apps/web/src/components/layout/BottomNav.tsx b/apps/web/src/components/layout/BottomNav.tsx index 3e86cb1..07ba316 100644 --- a/apps/web/src/components/layout/BottomNav.tsx +++ b/apps/web/src/components/layout/BottomNav.tsx @@ -20,8 +20,8 @@ export function BottomNav() { isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary', )} > - {/* Pastilla suave detrás del ícono: el estado activo se lee por - color + fondo, no solo por el tono del texto. */} + {/* Soft pill behind the icon: the active state is read by + color + background, not only by the text tone. */}
- {/* `Link` y no ``: en mobile el logo es la única forma de volver al - inicio y un anchor recargaría el documento entero, perdiendo el - estado en memoria (cache de React Query, evento de instalación). */} + {/* `Link` and not ``: on mobile the logo is the only way back to the + home screen and an anchor would reload the whole document, losing + the in-memory state (React Query cache, install event). */} diff --git a/apps/web/src/components/layout/LargeTitle.tsx b/apps/web/src/components/layout/LargeTitle.tsx index 1ffceba..57c2510 100644 --- a/apps/web/src/components/layout/LargeTitle.tsx +++ b/apps/web/src/components/layout/LargeTitle.tsx @@ -4,32 +4,33 @@ import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider' import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse' type LargeTitleProps = { - /** Texto del título. Es el mismo en el grande y en el de la barra: el `h1` - * real es el grande, el de la barra es un duplicado visual. */ + /** Title text. It's the same in the large title and in the bar's copy: the + * real `h1` is the large one, the bar's is a visual duplicate. */ title: string - /** Acción a la izquierda de la barra. En desktop es el link "volver" que - * antes vivía en el cuerpo de la pantalla; en mobile se oculta. */ + /** Action to the left of the bar. On desktop it's the "Volver" link that + * used to live in the screen body; on mobile it's hidden. */ leading?: ReactNode - /** Contexto que no puede desaparecer al scrollear (ej. el contador de - * presentes). Viaja a la barra y se funde con el título. */ + /** Context that can't disappear on scroll (e.g. the present counter). It + * travels to the bar and blends with the title. */ barTrailing?: ReactNode - /** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */ + /** Metadata under the large title: badges, description. It goes away when + * the title collapses. */ children?: ReactNode } /** - * Encabezado de pantalla con Large Title (patrón de iOS): el título arranca - * grande y al scrollear se desliza debajo de la barra, que se opaca y recibe - * el título en versión chica. + * Screen header with Large Title (the iOS pattern): the title starts large and + * slides under the bar as you scroll, while the bar goes opaque and takes the + * title in its small version. * - * El título grande es un bloque normal en el flujo; la barra vive en una caja - * sticky que el layout monta arriba de `
` (ver `ImmersiveBarHost`), así - * el contenido se desliza por debajo sin márgenes negativos ni `fixed` que - * haya que compensar en desktop. + * The large title is a normal block in the flow; the bar lives in a sticky box + * that the layout mounts above `
` (see `ImmersiveBarHost`), so the content + * slides under it without negative margins or a `fixed` we'd have to compensate + * for on desktop. * - * El estado del scroll vive acá adentro a propósito: `children` llega como prop - * ya construido, así React reutiliza los elementos y el subtree de abajo no se - * re-renderiza en cada frame de scroll. + * The scroll state lives in here on purpose: `children` arrives as an already + * built prop, so React reuses the elements and the subtree below doesn't + * re-render on every scroll frame. */ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) { const { titleRef, progress } = useLargeTitleCollapse() @@ -40,9 +41,9 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle {barHost ? createPortal(
- {/* El fondo va en una capa propia: se opaca con el scroll mientras - el título entra, y `leading` (el link "volver") no puede - fundirse con él porque existe siempre. */} + {/* The background goes on its own layer: it goes opaque with the + scroll while the title slides in, and `leading` (the "Volver" + link) can't blend with it because it always exists. */}
- {/* En las rutas immersive la pantalla trae su propia barra (LargeTitle), - con el logo y el nombre del grupo: el header global con logo + tema + - avatar sería una segunda barra compitiendo por los mismos píxeles. */} + {/* On immersive routes the screen brings its own bar (LargeTitle) with + the logo and the group name: the global header with logo + theme + + avatar would be a second bar competing for the same pixels. */} {immersive ? null :
}
- {/* pt-0 en immersive: el padding superior lo aporta la caja de la - barra, y si no el título grande arrancaría 16px más abajo de la - base de la barra y el colapso se mediría corrido. */} + {/* pt-0 on immersive: the bar's box provides the top padding, + otherwise the large title would start 16px below the bottom of the + bar and the collapse would be measured off. */}
- {/* `Link` y no ``: un anchor recargaría el documento y perdería el - estado en memoria (cache de React Query, evento de instalación). */} + {/* `Link` and not ``: an anchor would reload the document and lose the + in-memory state (React Query cache, install event). */} diff --git a/apps/web/src/components/layout/nav-items.ts b/apps/web/src/components/layout/nav-items.ts index 1d3be91..8550fa7 100644 --- a/apps/web/src/components/layout/nav-items.ts +++ b/apps/web/src/components/layout/nav-items.ts @@ -13,10 +13,10 @@ export const NAV_ITEMS: NavItem[] = [ { label: 'Ajustes', to: '/settings', icon: Settings }, ] -/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem - * activo es "Grupos", no ninguno. El prefijo se corta en el separador para - * que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay - * subrutas del home que deban marcarla. */ +/** A section stays active within its subroutes: on `/groups/abc` the active + * item is "Grupos", not none. The prefix is cut at the separator so + * `/groupsomething` isn't taken for "/groups". The root is exact: the home has + * no subroutes that should mark it. */ export function isNavItemActive(pathname: string, to: string): boolean { if (to === '/') return pathname === '/' return pathname === to || pathname.startsWith(`${to}/`) diff --git a/apps/web/src/components/ui/badge.tsx b/apps/web/src/components/ui/badge.tsx index 31689fa..fb1894a 100644 --- a/apps/web/src/components/ui/badge.tsx +++ b/apps/web/src/components/ui/badge.tsx @@ -12,10 +12,10 @@ const variants: Record = { warning: 'bg-warning-soft text-warning', danger: 'bg-danger-soft text-danger', neutral: 'bg-primary-soft text-primary', - /* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la - tinta de acento legible (`accent-fg` es el azul claro en tema oscuro, - 7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1 - y no alcanza el mínimo de 3:1 para contenido no textual. */ + /* Informational state, not an alert: waitlist, free spots. Uses the legible + accent ink (`accent-fg` is the light blue in the dark theme, 7.1:1 on the + card) and not the plain `accent`, which in dark scores 2.2:1 and misses the + 3:1 minimum for non-text content. */ info: 'bg-accent-soft text-accent-fg', } diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx index bbcd5d4..72b3d01 100644 --- a/apps/web/src/components/ui/button.tsx +++ b/apps/web/src/components/ui/button.tsx @@ -28,9 +28,9 @@ export const Button = forwardRef( ref={ref} type={type} className={cn( - // `transition-*` explícito en vez de `transition-all`: solo se animan - // color, fondo, borde y transform. El feedback de presión se anula - // con `motion-reduce` para respetar prefers-reduced-motion. + // Explicit `transition-*` instead of `transition-all`: only color, + // background, border and transform are animated. Press feedback is + // cancelled with `motion-reduce` to respect prefers-reduced-motion. 'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-medium transition-[color,background-color,border-color,fill,stroke,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50', variants[variant], sizes[size], diff --git a/apps/web/src/components/ui/input.tsx b/apps/web/src/components/ui/input.tsx index b132a4f..7ea2080 100644 --- a/apps/web/src/components/ui/input.tsx +++ b/apps/web/src/components/ui/input.tsx @@ -11,8 +11,8 @@ export const Input = forwardRef( para ser accesible. */ + /** Trigger content. It sits inside a - {/* Etiqueta en negro sobre el relleno `danger`: es la única forma de - llegar a AA con el mismo rojo en los dos temas (4.9:1 claro, - 6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */} + {/* Label in black on the `danger` fill: it is the only way to reach AA + with the same red in both themes (4.9:1 light, 6.7:1 dark); in white + they are 3.7:1 and 2.7:1. */} @@ -46,8 +46,8 @@ export function MembersView() { const navigate = useNavigate() const query = searchFilter.trim().toLowerCase() - // El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda: - // es como la mayoría conoce a los alumnos del grupo. + // The phone is not shown on the row but is still a search path: it is how most + // people know the group's attendees. const matchesQuery = (attendee: (typeof attendees)[number]) => !query || attendee.fullName.toLowerCase().includes(query) || @@ -61,9 +61,9 @@ export function MembersView() { const visible = attendees .filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment))) .filter(matchesQuery) - // Orden alfabético fijo: si se ordenara por cobro o asistencia las filas - // saltarían de lugar cada vez que alguien paga o falta, y el nombre es la - // única columna estable de la lista. + // Fixed alphabetical order: if it were sorted by charge or attendance the + // rows would jump around every time someone pays or misses, and the name is + // the only stable column in the list. .sort(byFullName) if (attendeesPending) { @@ -108,8 +108,8 @@ export function MembersView() { const filterBar = overdueCount > 0 ? : null if (visible.length === 0) { - // El filtro de vencidos nunca queda vacío por sí solo (el chip no se muestra - // si no hay vencidos), así que un vacío acá es siempre la búsqueda. + // The overdue filter never ends up empty on its own (the chip is not shown + // if there are none overdue), so an empty list here is always the search. return ( <> {filterBar} diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx index 2999c26..192ab5b 100644 --- a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -9,19 +9,19 @@ import { SectionChips } from './SectionChips' export function MembersWaitlistSection() { const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail() - // Con pocos miembros el buscador es ruido: se alcanza con recorrer la lista. - // Se quita del árbol en vez de esconderse, para no dejar un hueco en la fila. - // En Pendientes no cambia nada: ahí el volumen es el que es. + // With few attendees the search is noise: scrolling the list is enough. It is + // removed from the tree instead of hidden, so as not to leave a gap in the + // row. In Pendientes nothing changes: there the volume is what it is. const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN return ( - // Una sola superficie: la lista va directo sobre el lavado, como la info - // card de arriba, en vez de anidarse en una caja más clara. La separación - // entre controles y datos la dan los propios divisores de fila, el tono - // propio del input y el borde de los chips; una caja intermedia solo - // sumaba un nivel de contención y padding horizontal. - // `overflow-hidden` recorta el hover de las filas y el borde inferior - // contra el radio del panel: las filas son full-bleed. + // A single surface: the list sits directly on the wash, like the info card + // above, instead of nesting inside a lighter box. The separation between + // controls and data comes from the row dividers themselves, the input's own + // tone and the chips' border; an intermediate box only added a level of + // containment and horizontal padding. + // `overflow-hidden` clips the rows' hover and the bottom border against the + // panel's radius: the rows are full-bleed.
@@ -41,9 +41,9 @@ export function MembersWaitlistSection() { ) : null}
- {/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre - pre-inscripción y lista de espera, que no se deduce de los nombres. - En Miembros los rótulos de columna ya dicen todo. */} + {/* Only Pendientes has supporting copy: it explains the difference + between pre-registration and waitlist, which cannot be deduced from + the names. In Miembros the column labels already say everything. */} {listSection === 'pending' ? (

Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo diff --git a/apps/web/src/features/groups/detail/PendingView.tsx b/apps/web/src/features/groups/detail/PendingView.tsx index 4c008a1..35e24ca 100644 --- a/apps/web/src/features/groups/detail/PendingView.tsx +++ b/apps/web/src/features/groups/detail/PendingView.tsx @@ -37,9 +37,9 @@ export function PendingView() { if (!hasAnyEntry && !query) { return ( - // Full-bleed y sin radio propio: el `overflow-hidden` del panel lo recorta - // contra la silueta redondeada. `surface` sobre `primary-soft` hunde el - // bloque; con el lavado anterior se camuflaba. + // Full-bleed and with no radius of its own: the panel's `overflow-hidden` + // clips it against the rounded silhouette. `surface` over `primary-soft` + // sinks the block; with the previous wash it camouflaged.

No hay pendientes

@@ -92,7 +92,7 @@ export function PendingView() { const Icon = section.icon const hasRows = section.count > 0 const titleId = `pending-${section.title.replace(/\s+/g, '-').toLowerCase()}` - // Con búsqueda activa, las secciones sin coincidencias se ocultan. + // With the search on, sections with no matches are hidden. if (!hasRows && query) return null return ( diff --git a/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx b/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx index f820f8c..cc3cc5d 100644 --- a/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx +++ b/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx @@ -9,12 +9,13 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati return ( - {/* `border-foreground/10` y no `border`: en dark `--border` es igual a - `primary-soft`, el fondo de la fila, y el separador desaparecería. */} + {/* `border-foreground/10` and not `border`: in dark `--border` is the same + as `primary-soft`, the row's background, and the separator would + disappear. */} - {/* En móvil el teléfono manda: la fecha vive en el detalle. */} + {/* On mobile the phone leads: the date lives in the detail. */} setSelectedPreRegistration(entry)} onKeyDown={(e) => { @@ -36,8 +38,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati } }} > - {/* `px-3` alinea el texto con el chips y el search de arriba: es el - mismo eje izquierdo de 12px en toda la sección. */} + {/* `px-3` aligns the text with the chips and the search above: it is + the same 12px left axis across the whole section. */}
Nombre TeléfonoSolicitado Detalle @@ -26,7 +27,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
diff --git a/apps/web/src/features/groups/detail/SectionChips.tsx b/apps/web/src/features/groups/detail/SectionChips.tsx index cf9c23d..a54ac79 100644 --- a/apps/web/src/features/groups/detail/SectionChips.tsx +++ b/apps/web/src/features/groups/detail/SectionChips.tsx @@ -34,7 +34,8 @@ export function SectionChips() { {SECTIONS.map((section) => { const isActive = listSection === section.id const count = counts[section.id] - // Ámbar solo cuando hay algo que decidir: pre-inscripciones por revisar. + // Amber only when there is something to decide: pre-registrations to + // review. const isAttention = section.id === 'pending' && preRegistrationsTotal > 0 const Icon = section.icon @@ -45,7 +46,7 @@ export function SectionChips() { aria-pressed={isActive} onClick={() => setListSection(section.id)} className={cn( - // min-h-11 (44px): objetivo táctil mínimo de iOS/Android. + // min-h-11 (44px): minimum iOS/Android touch target. 'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold', 'transition-[background-color,color,border-color,box-shadow] duration-150', 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft', diff --git a/apps/web/src/features/groups/detail/WaitlistTable.tsx b/apps/web/src/features/groups/detail/WaitlistTable.tsx index d59efa1..4053170 100644 --- a/apps/web/src/features/groups/detail/WaitlistTable.tsx +++ b/apps/web/src/features/groups/detail/WaitlistTable.tsx @@ -9,8 +9,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) return ( - {/* `border-foreground/10` y no `border`: en dark `--border` es igual a - `primary-soft`, el fondo de la fila, y el separador desaparecería. */} + {/* `border-foreground/10` and not `border`: in dark `--border` is the same + as `primary-soft`, the row's background, and the separator would + disappear. */} @@ -24,7 +25,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) setSelectedWaitlistEntry(entry)} onKeyDown={(e) => { @@ -34,8 +36,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) } }} > - {/* `px-3` alinea el texto con el chips y el search de arriba: es el - mismo eje izquierdo de 12px en toda la sección. */} + {/* `px-3` aligns the text with the chips and the search above: it is + the same 12px left axis across the whole section. */}
Nombre Teléfono
diff --git a/apps/web/src/features/groups/detail/constants.ts b/apps/web/src/features/groups/detail/constants.ts index 1344b15..faa954e 100644 --- a/apps/web/src/features/groups/detail/constants.ts +++ b/apps/web/src/features/groups/detail/constants.ts @@ -1,11 +1,12 @@ -/* Ajustes de la lista de miembros de la ficha de grupo. Viven acá y no - incrustados en el componente porque son decisiones de producto, no de estilo: - cambiarlas no debería obligar a tocar la fila. */ +/* Tuning of the group detail's member list. It lives here and not embedded in + the component because these are product decisions, not style: changing them + should not force a touch on the row. */ -/* A partir de cuántos días para el vencimiento el cobro pasa a kuning y la fila - avisa. Más atrás ya no es "pronto": o se pagó o quedó en el pasado. */ +/* From how many days to the due date does the charge turn yellow and the row + warn. Further back it is no longer "due soon": either it was paid or it is in + the past. */ export const PAYMENT_DUE_SOON_DAYS = 3 -/* El buscador se muestra a partir de cierta cantidad de miembros. Con pocos, es - más ruido que ayuda: alcanza con mirar la lista. */ +/* The search shows from a certain number of attendees. With few of them it is + more noise than help: looking at the list is enough. */ export const MEMBER_SEARCH_MIN = 8 diff --git a/apps/web/src/features/groups/detail/member-row.ts b/apps/web/src/features/groups/detail/member-row.ts index 763b933..f70e833 100644 --- a/apps/web/src/features/groups/detail/member-row.ts +++ b/apps/web/src/features/groups/detail/member-row.ts @@ -2,12 +2,13 @@ import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared' import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared' import { PAYMENT_DUE_SOON_DAYS } from './constants' -/* La fila del listado no pide al backend juicios de presentación: pide los - datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los - días que faltan cambian según cuándo se mira, así que no pueden venir - guardados desde el servidor. */ +/* The listing's row does not ask the backend for presentation verdicts: it asks + for the raw data (recent classes, current charge) and the text comes from + here. The days remaining change depending on when you look, so they cannot + come stored from the server. */ -/** Días calendario entre dos fechas, sin horas: "vence el día 10" no tiene hora. */ +/** Calendar days between two dates, without times: "due on the 10th" has no + * time of day. */ function calendarDaysBetween(from: Date, to: Date): number { const startOf = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() @@ -20,15 +21,15 @@ export type PaymentState = | { kind: 'overdue'; days: number } /** - * Qué hay que marcarle al cobro en la fila. + * What to mark on the charge in the row. * - * Devuelve `null` cuando no hay nada que avisar: o el miembro no tiene ningún - * cobro registrado, o el que tiene vence más adelante que la ventana de aviso y - * todavía no venció. No es lo mismo que "al día", que es un pago cerrado. + * Returns `null` when there is nothing to warn about: either the attendee has no + * recorded charge, or the one they have is due later than the warning window and + * has not expired yet. That is not the same as "ok", which is a closed payment. * - * Un `PENDING` con vencimiento ya pasado cuenta como vencido, igual que un - * `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo - * actualiza a mano y la fila no puede depender de esa disciplina. + * A `PENDING` whose due date has already passed counts as overdue, same as an + * `OVERDUE`: the stored state often stays at PENDING until someone updates it by + * hand, and the row cannot depend on that discipline. */ export function resolvePaymentState( payment: AttendeeListItem['payment'], @@ -57,7 +58,7 @@ export function paymentStateLabel(state: PaymentState): string { case 'settled': return 'Al día' case 'dueSoon': - // "Vence en 0 d" no es español de persona: hoy y mañana tienen palabras. + // "Vence en 0 d" is not natural Spanish: today and tomorrow have words. if (state.days === 0) return 'Vence hoy' if (state.days === 1) return 'Vence mañana' return `Vence en ${state.days} d` @@ -67,20 +68,20 @@ export function paymentStateLabel(state: PaymentState): string { } export type AttendanceSummary = { - /** Estados a dibujar, del más antiguo al más reciente. */ + /** States to draw, from the oldest to the most recent. */ dots: AttendanceStatus[] attended: number recorded: number - /** "Sin clases aún" cuando no hay nada registrado. */ + /** "Sin clases aún" when nothing is recorded. */ label: string } -/** Los últimos puntos de clase registrados, contados sobre esa misma ventana. */ +/** The last recorded class points, counted over that same window. */ export function summarizeAttendance( recentAttendance: AttendanceStatus[], ): AttendanceSummary { - // La ventana la fija el backend; el corte final evita que una fila se alargue - // si el contrato llegara con más clases de las previstas. + // The window is set by the backend; the final cut prevents a row from getting + // longer if the contract ever delivers more classes than expected. const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT) const recorded = dots.length @@ -97,7 +98,7 @@ export function summarizeAttendance( } } -/** Orden alfabético fijo del listado. */ +/** The listing's fixed alphabetical order. */ export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number { return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' }) } diff --git a/apps/web/src/features/onboarding/ConfirmationStep.tsx b/apps/web/src/features/onboarding/ConfirmationStep.tsx index 3dfc98c..cca8c43 100644 --- a/apps/web/src/features/onboarding/ConfirmationStep.tsx +++ b/apps/web/src/features/onboarding/ConfirmationStep.tsx @@ -17,7 +17,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) const { refresh } = useAuth() const goToDashboard = () => { - // Revalida la caché (estado del onboarding, sesión, grupos) antes de redirigir. + // Revalidates the cache (onboarding state, session, groups) before redirecting. void queryClient.invalidateQueries() void refresh() void navigate({ to: '/' }) diff --git a/apps/web/src/features/onboarding/OnboardingProvider.tsx b/apps/web/src/features/onboarding/OnboardingProvider.tsx index 8294b4a..2017151 100644 --- a/apps/web/src/features/onboarding/OnboardingProvider.tsx +++ b/apps/web/src/features/onboarding/OnboardingProvider.tsx @@ -35,7 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { useEffect(() => { const status = statusQuery.data if (!status) return - // Si interrumpió después de conectar el cobro, retomamos en el paso del grupo. + // If they dropped out after connecting payments, we resume at the group step. if (status.step === 'PAYMENT_CONNECTED') { setStep((current) => (current === 0 ? 2 : current)) } diff --git a/apps/web/src/features/pwa/InstallPrompt.tsx b/apps/web/src/features/pwa/InstallPrompt.tsx index c8b8420..2d3ef67 100644 --- a/apps/web/src/features/pwa/InstallPrompt.tsx +++ b/apps/web/src/features/pwa/InstallPrompt.tsx @@ -3,8 +3,8 @@ import { InstallBanner } from './InstallBanner' import { IosInstallHint } from './IosInstallHint' /** - * Presenta el aviso de instalación. Cuándo mostrarse lo decide `PwaProvider` - * (sesión iniciada + dwell cumplido); acá solo se dibuja lo que corresponda. + * Renders the install prompt. `PwaProvider` decides when it should show (signed + * in + dwell satisfied); here we only draw whatever applies. */ export function InstallPrompt() { const { canPrompt, canShowIosHint, promptInstall, dismiss } = usePwa() diff --git a/apps/web/src/features/pwa/IosInstallHint.tsx b/apps/web/src/features/pwa/IosInstallHint.tsx index 63980e7..91551bc 100644 --- a/apps/web/src/features/pwa/IosInstallHint.tsx +++ b/apps/web/src/features/pwa/IosInstallHint.tsx @@ -5,9 +5,9 @@ type IosInstallHintProps = { } /** - * Safari en iOS no expone `beforeinstallprompt`: no hay forma de disparar la - * instalación desde la web, hay que instruir al usuario. Solo informa, sin - * botón de acción. + * Safari on iOS does not expose `beforeinstallprompt`: there is no way to trigger + * the install from the web, the user has to be instructed. It only informs, with + * no action button. */ export function IosInstallHint({ onDismiss }: IosInstallHintProps) { return ( diff --git a/apps/web/src/features/pwa/PwaProvider.tsx b/apps/web/src/features/pwa/PwaProvider.tsx index 7f6abe5..bbcb36b 100644 --- a/apps/web/src/features/pwa/PwaProvider.tsx +++ b/apps/web/src/features/pwa/PwaProvider.tsx @@ -13,16 +13,16 @@ import { useAuth } from '../../context/AuthProvider' import { useToast } from '../../components/ui' import { InstallPrompt } from './InstallPrompt' -/** `beforeinstallprompt` todavía no está en lib.dom (Chromium >= 108). */ +/** `beforeinstallprompt` is not in lib.dom yet (Chromium >= 108). */ type BeforeInstallPromptEvent = Event & { prompt: () => Promise userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> } type PwaContextValue = { - /** El navegador ofreció instalar y el usuario todavía no lo decidió. */ + /** The browser offered to install and the user has not decided yet. */ canPrompt: boolean - /** Safari en iOS: no hay `prompt()`, hay que instruir al usuario. */ + /** Safari on iOS: there is no `prompt()`, the user has to be instructed. */ canShowIosHint: boolean promptInstall: () => Promise dismiss: () => void @@ -31,19 +31,19 @@ type PwaContextValue = { const PwaContext = createContext(null) /** - * El descarte es definitivo: una vez que el usuario dice "ahora no" no se vuelve - * a preguntar. Comparte clave con la pista de iOS porque el motivo es el mismo. + * The dismissal is final: once the user says "not now" we never ask again. It + * shares a key with the iOS hint because the reason is the same. */ const DISMISSED_KEY = 'pwa-install-dismissed' /** - * Cuánto hay que quedarse en la misma ruta antes de ofrecer instalar. El evento - * `beforeinstallprompt` llega a los segundos, así que sin este margen el banner - * cae en medio de la primera tarea de la visita. + * How long you have to stay on the same route before we offer to install. The + * `beforeinstallprompt` event arrives within seconds, so without this margin the + * banner lands in the middle of the visit's first task. */ const DWELL_MS = 20_000 -/** iOS Safari no dispara `beforeinstallprompt`: se chequea el modo standalone. */ +/** iOS Safari does not fire `beforeinstallprompt`: we check the standalone mode instead. */ function isStandalone() { return ( window.matchMedia('(display-mode: standalone)').matches || @@ -52,9 +52,9 @@ function isStandalone() { } /** - * iOS real, Safari real. Excluye Chrome/Firefox/Edge/Opera en iOS: usan WebKit - * pero también los instala desde Safari, así que la instrucción de compartir - * no aplica. El iPad de iPadOS 13+ se reporta como MacIntel con touch points. + * Real iOS, real Safari. Excludes Chrome/Firefox/Edge/Opera on iOS: they use + * WebKit but also install from Safari, so the share instruction does not apply. + * iPadOS 13+ iPads report as MacIntel with touch points. */ function detectIos() { if (isStandalone()) return false @@ -69,11 +69,12 @@ function detectIos() { } /** - * El registro se hace desde el provider y no con `injectRegister: 'auto'` para - * poder avisar cuando el shell quedó cacheado. El flag es de módulo porque - * StrictMode monta dos veces en dev y `onOfflineReady` dispararía dos toasts. - * No se limpia en el unmount: StrictMode lo resetea en el mismo ciclo de montaje - * y volvería a registrar. Con HMR el módulo se re-evalua y arranca en false. + * Registration is done from the provider and not with `injectRegister: 'auto'` so + * we can tell the user when the shell has been cached. The flag is a module + * variable because StrictMode mounts twice in dev and `onOfflineReady` would fire + * two toasts. It is not cleared on unmount: StrictMode resets it in the same + * mount cycle and we would register again. With HMR the module is re-evaluated + * and starts at false. */ let registered = false @@ -103,7 +104,7 @@ export function PwaProvider({ children }: { children: ReactNode }) { useEffect(() => { const onBeforeInstallPrompt = (event: Event) => { - // Sin preventDefault el navegador muestra su propio mini-infobar. + // Without preventDefault the browser shows its own mini-infobar. event.preventDefault() setInstallEvent(event as BeforeInstallPromptEvent) } @@ -120,25 +121,25 @@ export function PwaProvider({ children }: { children: ReactNode }) { } }, []) - // `PwaProvider` monta fuera del `RouterProvider`, así que no puede usar - // `useRouterState`: se suscribe al singleton. Conviene tener la ruta acá y no - // en el componente que muestra el banner, porque `AppLayoutGuard` desmonta - // `RootLayout` cada vez que su query de onboarding vuelve a `pending` y un - // timer de dwell en el hijo se perdería en cada navegación. + // `PwaProvider` mounts outside the `RouterProvider`, so it cannot use + // `useRouterState`: it subscribes to the singleton. The route is kept here and + // not in the component that shows the banner, because `AppLayoutGuard` + // unmounts `RootLayout` every time its onboarding query goes back to `pending`, + // and a dwell timer in the child would be lost on every navigation. useEffect( () => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)), [], ) - // Durante el alta inicial no se ofrece instalar: la persona todavía no - // conoce la app. El timer ni siquiera corre, así que al salir arranca de cero - // en la primera pantalla real. + // During the initial sign-up we do not offer to install: the person does not + // know the app yet. The timer does not even run, so leaving the flow starts it + // from scratch on the first real screen. const inOnboarding = pathname.startsWith('/onboarding') useEffect(() => { - // Navegar antes de que se cumpla el tiempo reinicia la cuenta: tampoco - // estamos pidiendo instalar a alguien que está peleando con la app. Una - // vez cumplido queda armed y no se oculta más al navegar. + // Navigating before the time is up restarts the count: we are not asking + // someone who is busy fighting the app to install it either. Once it is + // settled it stays armed and no longer hides on navigation. if (settled || inOnboarding) return const timer = setTimeout(() => setSettled(true), DWELL_MS) return () => clearTimeout(timer) @@ -163,12 +164,12 @@ export function PwaProvider({ children }: { children: ReactNode }) { }, [info]) /** - * Sin sesión no hay nada que instalar todavía: la primera vez que alguien - * conoce la app es instalándola, no pidiéndole que la instale. + * Without a session there is nothing to install yet: the first time someone + * meets the app is by installing it, not by being asked to install it. * - * OJO: `_authenticated` NO es un guard de sesión. `AppLayoutGuard` renderiza - * `RootLayout` aunque no haya usuario, así que el gate se chequea acá y no - * se puede inferir de dónde se monte el prompt. + * WATCH OUT: `_authenticated` is NOT a session guard. `AppLayoutGuard` renders + * `RootLayout` even when there is no user, so the gate is checked here and + * cannot be inferred from where the prompt is mounted. */ const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding diff --git a/apps/web/src/hooks/useLargeTitleCollapse.ts b/apps/web/src/hooks/useLargeTitleCollapse.ts index e0fc799..afd13bd 100644 --- a/apps/web/src/hooks/useLargeTitleCollapse.ts +++ b/apps/web/src/hooks/useLargeTitleCollapse.ts @@ -1,8 +1,8 @@ import { useEffect, useRef, useState } from 'react' -/* Alto de la barra de navegación donde entra el título chico. Tiene que - coincidir con el `h-14` de `LargeTitle`: la barra es sticky contra el borde - superior de la ventana y el título grande se mide contra este valor. */ +/* Height of the navigation bar where the small title slides in. It has to + match the `h-14` of `LargeTitle`: the bar is sticky to the top edge of the + window and the large title is measured against this value. */ const BAR_HEIGHT = 56 function clamp01(value: number) { @@ -11,13 +11,13 @@ function clamp01(value: number) { } /** - * Progreso de colapso de un Large Title: 0 con el título grande desplegado, - * 1 cuando quedó por completo tapado detrás de la barra. + * Collapse progress of a Large Title: 0 with the large title fully shown, + * 1 once it's completely hidden behind the bar. * - * El progreso sale de la posición del título, no del tiempo: se recalcula en - * cada frame mientras se scrollea. Por eso el gesto se siente pegado al dedo - * en vez de "animado", y por eso `requestAnimationFrame` sirve para agrupar - * eventos de scroll, no para interpolar la animación. + * The progress comes from the title's position, not from time: it is + * recalculated on every frame while scrolling. That's why the gesture feels + * stuck to the finger instead of "animated", and why `requestAnimationFrame` + * is there to batch scroll events, not to interpolate the animation. */ export function useLargeTitleCollapse() { const titleRef = useRef(null) @@ -32,11 +32,11 @@ export function useLargeTitleCollapse() { const measure = () => { frame = 0 const { top, height } = title.getBoundingClientRect() - // 0 cuando el borde superior del título llega a la base de la barra, 1 - // cuando su borde inferior también llegó (quedó enteramente debajo). + // 0 when the title's top edge reaches the bottom of the bar, 1 when its + // bottom edge got there too (it ended up entirely underneath). const next = clamp01((BAR_HEIGHT - top) / (height || BAR_HEIGHT)) - // Los títulos de grupo llegan asíncrono y pueden cambiar de alto entre - // renders: sin este umbral se re-renderiza en cada frame de scroll. + // Group titles arrive asynchronously and can change height between + // renders: without this threshold it re-renders on every scroll frame. setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next)) } @@ -48,8 +48,8 @@ export function useLargeTitleCollapse() { window.addEventListener('scroll', schedule, { passive: true }) window.addEventListener('resize', schedule) - // El nombre del grupo se carga después del primer render y la webfont puede - // cambiar el alto del título: el rango de colapso depende de esa medida. + // The group name loads after the first render and the webfont can change + // the title's height: the collapse range depends on that measurement. const observer = new ResizeObserver(schedule) observer.observe(title) diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 7fe2b8e..27f2a1f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1,9 +1,10 @@ @import "tailwindcss"; -/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en - lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el - service worker precachea todo lo emitido, casi 1 MB que nunca se descarga. - El archivo .woff2 sí viene del paquete, con hash y cache immutable. */ +/* Self-hosted Inter variable. We declare only latin and latin-ext by hand + instead of importing @fontsource's wght.css: that one brings all 7 subsets + and the service worker precaches everything emitted, almost 1 MB that never + gets downloaded. The .woff2 file does come from the package, hashed with an + immutable cache. */ @font-face { font-family: "Inter Variable"; font-style: normal; @@ -25,7 +26,7 @@ @custom-variant dark (&:where(.dark, .dark *)); @theme inline { - /* Escala de marca (identidad fija, igual a la landing) */ + /* Brand scale (fixed identity, same as the landing) */ --color-brand-50: var(--brand-50); --color-brand-100: var(--brand-100); --color-brand-200: var(--brand-200); @@ -38,12 +39,12 @@ --color-brand-900: var(--brand-900); --color-brand-950: var(--brand-950); - /* Colores de la gráfica del isotipo/logotipo */ + /* Colors sampled from the logo mark */ --color-brand-night: var(--brand-night); --color-brand-celeste: var(--brand-celeste); --color-brand-cloud: var(--brand-cloud); - /* Tokens semánticos (conmutan con tema claro/oscuro) */ + /* Semantic tokens (switch with the light/dark theme) */ --color-background: var(--background); --color-surface: var(--surface); --color-primary: var(--primary); @@ -70,14 +71,14 @@ --color-attendance-attention: var(--attendance-attention); --color-attendance-ok: var(--attendance-ok); - /* Border radius por defecto */ + /* Default border radius */ --radius-xl: 0.75rem; - /* Tipografía (igual que la landing) */ - /* @fontsource-variable/inter registra la familia como "Inter Variable" */ + /* Typography (same as the landing) */ + /* @fontsource-variable/inter registers the family as "Inter Variable" */ --font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif; - /* Animaciones */ + /* Animations */ --animate-fade-in: fade-in 0.2s ease-out; --animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both; @@ -101,7 +102,7 @@ :root { color-scheme: light; - /* Escala de marca */ + /* Brand scale */ --brand-50: #eef4ff; --brand-100: #dbe6fe; --brand-200: #bfd3fe; @@ -117,17 +118,17 @@ --brand-celeste: #93b4fd; --brand-cloud: #eef4ff; - /* Tema claro */ + /* Light theme */ --background: #ffffff; --surface: #ffffff; --primary: #0f172a; --primary-soft: #f1f5f9; --foreground: #475569; - /* Texto secundario sobre superficies suaves (tarjetas). En tema claro el - gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre - `background`, así que acá no hay que mover nada: mismo valor, mismo - contrato. El token existe igual para que "secundario" sea un nombre y no - una coincidencia de color. */ + /* Secondary text on soft surfaces (cards). In the light theme the + `foreground` gray already scores 6.9:1 on `primary-soft` and 7.6:1 on + `background`, so there's nothing to move here: same value, same contract. + The token exists anyway so "secondary" is a name and not a color + coincidence. */ --secondary: #475569; --accent: #2544ea; --accent-strong: #1d33d8; @@ -140,18 +141,18 @@ --success-soft: #ecfdf5; --warning: #b45309; --warning-soft: #fffbeb; - /* naranja: escalón de severidad para la misma familia de alertas (aviso por - asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la - tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */ + /* Orange: severity step for the same alert family (attendance and capacity + warnings). It scores 4.9:1 on `warning-strong-soft` and 4.4:1 on the card, + so it works for text and for a subtle border. */ --warning-strong: #c2410c; --warning-strong-soft: #fff7ed; --danger: #f43f5e; --danger-soft: #fff1f2; - /* Rojo legible como TEXTO. `--danger` da 3.35:1 sobre la tarjeta en tema - claro, así que como texto no llega al 4.5:1 de AA (sí sirve como relleno, - donde el mínimo es 3:1). Es el mismo patrón que `accent` / `accent-fg`: un - color para superficies grandes y su versión legible para rotular. Este - #be123c da 5.74:1 sobre la tarjeta y 5.72:1 sobre `danger-soft`. */ + /* Red legible as TEXT. In the light theme `--danger` scores 3.35:1 on the + card, so as text it misses AA's 4.5:1 (it does work as a fill, where the + minimum is 3:1). Same pattern as `accent` / `accent-fg`: one color for + large surfaces and a legible version of it for labels. This #be123c scores + 5.74:1 on the card and 5.72:1 on `danger-soft`. */ --danger-fg: #be123c; --attendance-high: #d63b3b; --attendance-attention: #f5a623; @@ -161,16 +162,16 @@ .dark { color-scheme: dark; - /* Tema oscuro (paleta slate/brand de la landing) */ + /* Dark theme (slate/brand palette from the landing) */ --background: #020617; --surface: #0f172a; --primary: #f1f5f9; --primary-soft: #1e293b; --foreground: #94a3b8; - /* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la - tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior. - El salto importa en las superficies suaves, que son las que dominan las - tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */ + /* Secondary goes one step up from `foreground`: 7.1:1 on the card (#1e293b) + and 9.8:1 on the background, against 5.7:1 for the previous gray. The step + matters on soft surfaces, which are what dominates list cards: supporting + text there is what gets lost the most. */ --secondary: #a8b6c8; --accent: #2544ea; --accent-strong: #1d33d8; @@ -183,15 +184,15 @@ --success-soft: color-mix(in srgb, var(--success) 15%, transparent); --warning: #fcd34d; --warning-soft: color-mix(in srgb, var(--warning) 15%, transparent); - /* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el - mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo - translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */ + /* In dark the "orange" has to gain lightness to reach the same contrast as + its light version: #fb923c scores 4.7:1 on the badge's translucent + background, against 4.1:1 for the #f97316 of the standard palette. */ --warning-strong: #fb923c; --warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent); --danger: #fb7185; --danger-soft: color-mix(in srgb, var(--danger) 15%, transparent); - /* En oscuro `#fb7185` ya da 5.44:1 sobre la tarjeta: legible como texto y de - sobra como relleno, así que acá no hay que mover nada. */ + /* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and + more than enough as a fill, so there's nothing to move here. */ --danger-fg: var(--danger); } @@ -205,14 +206,14 @@ min-height: 100dvh; } - /* iOS (Safari y standalone) hace auto-zoom al enfocar un control de - formulario con font-size < 16px, y al cerrar el teclado no restaura el - scale: la app queda con zoom. El `Input` ya sube a 16px en mobile - (`text-base sm:text-sm`); esto es la red de seguridad para textareas, - selects o inputs crudos que se agreguen más adelante. - El 639px calza con el breakpoint `sm` de Tailwind. El `!important` es - a propósito: sin él, una clase `text-sm` en un input futuro ganaría por - especificidad y reintroduciría el bug sin avisar. */ + /* iOS (Safari and standalone) auto-zooms when a form control with font-size + < 16px is focused, and on keyboard close it doesn't restore the scale: + the app is left zoomed in. `Input` already goes to 16px on mobile + (`text-base sm:text-sm`); this is the safety net for textareas, selects or + raw inputs added later. + The 639px matches Tailwind's `sm` breakpoint. The `!important` is on + purpose: without it a `text-sm` class on a future input would win on + specificity and reintroduce the bug without warning. */ @media (max-width: 639px) { input, textarea, diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 0ab864d..810d146 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -80,7 +80,7 @@ async function apiFetch(path: string, init?: RequestInit): Promise { problem = body as ProblemDetails } } catch { - // Sin cuerpo JSON: usamos el error genérico. + // No JSON body: we use the generic error. } throw new ApiError(res.status, problem) } @@ -108,9 +108,9 @@ export const createGroup = (payload: CreateFirstGroup) => body: JSON.stringify(payload), }) -/* La pantalla de grupos no tiene paginación: se pide el máximo permitido para - que ningún grupo quede fuera de la lista, y la zona horaria del browser para - que el backend ordene por la próxima clase en la hora local de la persona. */ +/* The groups screen has no pagination: we ask for the maximum allowed so no + group is left out of the listing, and for the browser time zone so the + backend sorts by the next class in the person's local time. */ const GROUPS_PAGE_SIZE = 100 export const getGroups = () => { @@ -222,7 +222,7 @@ export const removeGroupAttendee = ( }, ) -// — Día a Día: clases y asistencia — +// — Day to day: classes and attendance — export const getClassesToday = () => apiFetch(`/api/v1/classes/today${timeZoneParam()}`) @@ -251,7 +251,7 @@ export const publicNotifyAbsence = (payload: PublicNotifyAbsence) => body: JSON.stringify(payload), }) -// — Analíticas y gestión de riesgo — +// — Analytics and risk management — export const getGroupAnalytics = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}/analytics`) diff --git a/apps/web/src/lib/file-parser.ts b/apps/web/src/lib/file-parser.ts index 1b50bcb..2ed8b64 100644 --- a/apps/web/src/lib/file-parser.ts +++ b/apps/web/src/lib/file-parser.ts @@ -18,11 +18,11 @@ export function normalizePhone(rawPhone: string): string { } /** - * Parsea texto CSV con soporte para: - * - Delimitadores automáticos (coma, punto y coma, tabulador) - * - Comillas y comillas escapadas ("") + * Parses CSV text with support for: + * - Automatic delimiters (comma, semicolon, tab) + * - Quotes and escaped quotes ("") * - UTF-8 BOM - * - Saltos de línea CRLF o LF + * - CRLF or LF line breaks */ export function parseCsvContent(content: string): string[][] { const cleanContent = content.replace(/^\uFEFF/, ''); @@ -30,7 +30,7 @@ export function parseCsvContent(content: string): string[][] { if (lines.length === 0) return []; - // Detectar delimitador basado en la primera línea + // Detect the delimiter from the first line const firstLine = lines[0]; const commaCount = (firstLine.match(/,/g) || []).length; const semicolonCount = (firstLine.match(/;/g) || []).length; @@ -56,7 +56,7 @@ export function parseCsvContent(content: string): string[][] { if (char === '"') { if (insideQuote && line[i + 1] === '"') { currentCell += '"'; - i++; // Saltear comilla escapada + i++; // Skip the escaped quote } else { insideQuote = !insideQuote; } @@ -75,8 +75,8 @@ export function parseCsvContent(content: string): string[][] { } /** - * Parsea un archivo XLSX de Excel extrayendo sharedStrings y sheet1.xml - * utilizando DecompressionStream nativo del navegador sin dependencias externas. + * Parses an Excel XLSX file by extracting sharedStrings and sheet1.xml with + * the browser's native DecompressionStream, without external dependencies. */ export async function parseXlsxContent(buffer: ArrayBuffer): Promise { const view = new DataView(buffer); @@ -112,7 +112,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise entries.set(fileName, new Uint8Array(decompressed)); } } catch { - // Ignorar archivos que no se puedan descomprimir + // Ignore files that can't be decompressed } } } @@ -120,7 +120,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise offset = dataStart + compressedSize; } - // Parsear strings compartidos + // Parse the shared strings const sharedStringsData = entries.get('xl/sharedStrings.xml'); const sharedStrings: string[] = []; if (sharedStringsData) { @@ -138,7 +138,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise } } - // Parsear sheet1.xml + // Parse sheet1.xml const sheetData = entries.get('xl/worksheets/sheet1.xml'); if (!sheetData) { throw new Error('No se pudo encontrar la hoja de cálculo principal en el archivo Excel.'); @@ -174,7 +174,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise } /** - * Normaliza una matriz 2D en objetos de contactos con detección inteligente de columnas. + * Normalizes a 2D matrix into contact objects with smart column detection. */ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] { if (rawRows.length === 0) return []; @@ -219,7 +219,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] } } - // Fallbacks posicionales si no se detectaron encabezados explícitos + // Positional fallbacks when no explicit headers were detected if (!hasHeader) { firstNameCol = 0; lastNameCol = 1; @@ -230,7 +230,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] } if (phoneCol === -1) { - // Buscar la primera columna que parezca un número telefónico + // Look for the first column that looks like a phone number for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) { const sample = rawRows[1][c]; if (/^[\d\s+\-()]{6,}$/.test(sample)) { @@ -291,7 +291,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] } /** - * Descarga una plantilla de ejemplo en formato CSV para la carga masiva. + * Downloads a sample template in CSV format for the bulk upload. */ export function downloadAttendeeTemplateCsv() { const csvContent = diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts index 919e960..4403875 100644 --- a/apps/web/src/lib/format.ts +++ b/apps/web/src/lib/format.ts @@ -51,18 +51,18 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ') } -/* Un importe se escribe con el país de la persona: su moneda y su regional - (separadores, posición del símbolo), sin conversión — el importe lo fija - quien creó el grupo y no se toca. El país sale de la zona horaria del - sistema y, si no se conoce, del idioma del browser (ver countryOf). Sin - país conocido se pinta con el símbolo $ genérico, nunca con un código - inventado. La firma acepta moneda y locale para forzarlas (tests, print) - sin tocar los call sites. */ +/* An amount is written with the person's country: its currency and its regional + format (separators, symbol position), with no conversion — the amount is set + by whoever created the group and is never touched. The country comes from the + system time zone and, when it's unknown, from the browser language (see + countryOf). With no known country we fall back to the generic $ symbol, + never to an invented code. The signature takes a currency and a locale to + force them (tests, print) without touching the call sites. */ -/* La configuración regional del browser manda en cómo se pintan los datos. - Se lee en cada llamada (es un accessor barato) para que un cambio de idioma - del sistema se refleje sin recargar; lo caro es construir el formatter, así - que esos se memorizan por locale/moneda. */ +/* The browser's regional settings decide how the data is rendered. It's read + on every call (it's a cheap accessor) so a system language change shows up + without a reload; building the formatter is the expensive part, so those are + memoized per locale/currency. */ type BrowserNavigator = { language?: string; languages?: readonly string[] } function browserLocale(): string | undefined { @@ -78,14 +78,14 @@ export function formatPrice( locale?: string, ): string { if (price == null) return '—' - // Importes enteros sin decimales ($50.000); con centavos se respetan. + // Whole amounts with no decimals ($50.000); cents are kept when present. const hasCents = !Number.isInteger(price) const browser = locale ?? browserLocale() const country = countryOf(browser) const resolvedCurrency = currency ?? currencyForRegion(country) - // Los separadores y la posición del símbolo siguen al país: un browser en - // inglés en Argentina tiene que ver $50.000, no ARS 50,000. Con la locale - // pasada explícita no se toca nada (tests, print). + // Separators and symbol position follow the country: an English browser in + // Argentina has to see $50.000, not ARS 50,000. When the locale is passed + // explicitly nothing is touched (tests, print). const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}` @@ -103,27 +103,28 @@ export function formatPrice( return tidyCurrencySpacing(formatter.format(price)) } -/* Intl separa el símbolo de la moneda con un espacio duro: "$ 50.000" se lee - como dos tokens sueltos. Lo quitamos solo cuando separa símbolo de número; - entre dígitos y código ("50.000 ARS") el no-break space evita el corte. */ +/* Intl separates the currency symbol with a hard space: "$ 50.000" reads as two + loose tokens. We strip it only when it separates symbol from number; between + digits and the code ("50.000 ARS") the non-breaking space prevents the + break. */ const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu function tidyCurrencySpacing(value: string): string { return value.replace(SYMBOL_GAP, '$1') } -/* ── Teléfonos ────────────────────────────────────────────────────────────── +/* ── Phones ───────────────────────────────────────────────────────────────── - Presentación, nunca persistencia: los links wa.me siguen usando los dígitos - crudos. El formato sale de la región del propio número cuando su prefijo de - país es reconocible; si el número es nacional, manda la región del browser - (y si esa región no la conocemos, la de la app: AR). Si nada encaja se cae - a E.164 (+331234567890) o al valor original, siempre preferible a un número - inventado. */ + Presentation, never persistence: the wa.me links still use the raw digits. + The format comes from the region of the number itself when its country + prefix is recognizable; if the number is national, the browser's region wins + (and if we don't know that region, the app's: AR). If nothing matches we fall + back to E.164 (+331234567890) or to the original value, always preferable to + an invented number. */ type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX' -/** Prefijos de país que sabemos agrupar. */ +/** Country prefixes we know how to group. */ const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [ { region: 'AR', code: '54' }, { region: 'ES', code: '34' }, @@ -141,15 +142,15 @@ export function formatPhoneDisplay( const hasPlus = raw.startsWith('+') let digits = raw.replace(/\D/g, '') - // "0054…" es el mismo indicio internacional que "+54…". + // "0054…" is the same international hint as "+54…". const hasDoubleZero = !hasPlus && raw.startsWith('00') if (hasDoubleZero) digits = digits.slice(2) if (digits.length < 6) return raw const withCallingCode = formatWithCallingCode(digits) if (withCallingCode) return withCallingCode - // Número de una región que no agrupamos: al menos se separa en bloques de a - // 3 para que no se lea como un muro de dígitos. El `+` se conserva si lo había. + // Number from a region we don't group: at least it's split into groups of 3 + // so it doesn't read like a wall of digits. The `+` is kept if there was one. if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}` return ( @@ -158,7 +159,7 @@ export function formatPhoneDisplay( ) } -/** Bloques de a 3 desde la derecha: el sobrante de 1-2 dígitos queda a la izquierda. */ +/** Groups of 3 from the right: the leftover 1-2 digits stay on the left. */ function groupByThrees(digits: string): string { const groups: string[] = [] let rest = digits @@ -170,7 +171,7 @@ function groupByThrees(digits: string): string { return groups.join(' ') } -/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */ +/** Tries the country prefix only if what follows fits its rules. */ function formatWithCallingCode(digits: string): string | null { for (const { region, code } of COUNTRY_CALLING_CODES) { if (!digits.startsWith(code)) continue @@ -180,12 +181,12 @@ function formatWithCallingCode(digits: string): string | null { return null } -/** Región ISO → región con reglas propias. CA comparte NANP con US. */ +/** ISO region → region with its own rules. CA shares NANP with US. */ function appRegion(region: string | undefined): PhoneRegion { if (region === 'US' || region === 'CA') return 'US' if (region === 'ES') return 'ES' if (region === 'MX') return 'MX' - // Sin región reconocible seguimos siendo una app de Argentina. + // With no recognizable region we are still an Argentine app. return 'AR' } @@ -210,12 +211,12 @@ function formatArNational(digits: string, withCountry: boolean): string | null { let national = digits let isMobile = false - // Móvil argentino: 9 + 10 dígitos nacionales. + // Argentine mobile: 9 + 10 national digits. if (national.length === 11 && national.startsWith('9')) { national = national.slice(1) isMobile = true } - // 0 de trunk nacional: además implica que el número es argentino. + // National trunk 0: it also implies the number is Argentine. if (national.startsWith('0') && national.length >= 9) { national = national.slice(1) withCountry = true @@ -229,8 +230,8 @@ function formatArNational(digits: string, withCountry: boolean): string | null { function groupArNational(digits: string): string { if (digits.length === 10) { - // 11 es el único área de 2 dígitos (Gran Buenos Aires); el resto se - // agrupa 4-2-4, que es el patrón de las áreas de 4 dígitos. + // 11 is the only 2-digit area code (Gran Buenos Aires); the rest group + // 4-2-4, which is the pattern for 4-digit area codes. return digits.startsWith('11') ? `${digits.slice(0, 2)} ${digits.slice(2, 6)}-${digits.slice(6)}` : `${digits.slice(0, 4)} ${digits.slice(4, 6)}-${digits.slice(6)}` @@ -240,31 +241,31 @@ function groupArNational(digits: string): string { return digits } -/** NANP (US/CA): 10 dígitos con área e intercambio que arrancan en 2–9. */ +/** NANP (US/CA): 10 digits with area and exchange starting in 2–9. */ function formatUsNational(digits: string): string | null { if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1) if (digits.length !== 10) return null if (digits[0] === '0' || digits[0] === '1' || digits[3] === '0' || digits[3] === '1') return null - // Convención doméstica: el "1" del país no se escribe. + // Domestic convention: the country "1" is not written. return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}` } -/** España: 9 dígitos (móvil 6/7, fijo 8/9) agrupados 3-2-2-2. */ +/** Spain: 9 digits (mobile 6/7, landline 8/9) grouped 3-2-2-2. */ function formatEsNational(digits: string, withCountry: boolean): string | null { if (digits.length !== 9 || !'6789'.includes(digits[0])) return null const local = `${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 7)} ${digits.slice(7)}` return withCountry ? `+34 ${local}` : local } -/** México: 10 dígitos agrupados 2-4-4. */ +/** Mexico: 10 digits grouped 2-4-4. */ function formatMxNational(digits: string, withCountry: boolean): string | null { if (digits.length !== 10 || digits[0] === '0' || digits[0] === '1') return null const local = `${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}` return withCountry ? `+52 ${local}` : local } -// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez -// de "Vence día 10": se lee como una promesa, no como un dato suelto. +// The due date is worded as a phrase ("Vence el día 10 de cada mes") instead of +// "Vence día 10": it reads as a promise, not as a bare fact. export function formatBillingMeta( billingType: BillingType | null, dueDay: number | null, diff --git a/apps/web/src/lib/immersive-routes.ts b/apps/web/src/lib/immersive-routes.ts index b2efc6b..bb78068 100644 --- a/apps/web/src/lib/immersive-routes.ts +++ b/apps/web/src/lib/immersive-routes.ts @@ -1,11 +1,11 @@ -/* Rutas "immersive": las que arman su propia barra de navegación con - `LargeTitle` (título grande que colapsa) y por eso no muestran el header - global con logo + toggle de tema + avatar. +/* "Immersive" routes: the ones that build their own navigation bar with + `LargeTitle` (a large title that collapses) and therefore don't show the + global header with logo + theme toggle + avatar. - El patrón se resuelve a mano y no con `matchRoute` porque las dos rutas - llevan parámetros (`matchRoute` los exige) y porque las rutas hijas NO son - immersive aunque compartan prefijo: `/groups/:id/attendees/new` sigue usando - el header global. */ + The pattern is resolved by hand and not with `matchRoute` because the two + routes carry params (`matchRoute` requires them) and because child routes are + NOT immersive even when they share a prefix: `/groups/:id/attendees/new` + still uses the global header. */ const IMMERSIVE_SEGMENTS: ReadonlyArray = [ ['groups', ':id'], @@ -13,9 +13,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray = [ ['class', ':id', 'attendance'], ] -/* Rutas estáticas que ocupan el lugar de un parámetro. Sin esta lista - `/groups/new` (crear grupo) se tomaría por una ficha de grupo y perdería el - header global. */ +/* Static routes that sit where a param would go. Without this list + `/groups/new` (create group) would be taken for a group detail page and would + lose the global header. */ const STATIC_SEGMENTS: ReadonlySet = new Set(['new']) export function isImmersiveRoute(pathname: string) { diff --git a/apps/web/src/lib/region.ts b/apps/web/src/lib/region.ts index 47e5b43..4f54417 100644 --- a/apps/web/src/lib/region.ts +++ b/apps/web/src/lib/region.ts @@ -1,24 +1,24 @@ -/* De dónde es la persona y cómo se le escriben los números. +/* Where the person is from and how their numbers get written. - El idioma del browser dice en qué idioma se está, no en qué país se está: - con "en-US" a alguien en Argentina lo trata como estadounidense, y con - "es-419" no dice ningún país. La zona horaria —que sí expone el sistema— - es la señal del país real; el idioma solo define cuando la zona no se - conoce. Con el país resuelto salen la moneda (REGION_CURRENCY) y la - regional con la que se formatea (REGION_LOCALE), para que un browser en - inglés en Argentina vea $50.000 y no ARS 50,000. + The browser language says what language you're in, not what country you're + in: with "en-US" it treats someone in Argentina as American, and with + "es-419" it says no country at all. The time zone — which the system does + expose — is the signal for the real country; the language only decides when + the time zone is unknown. With the country resolved you get the currency + (REGION_CURRENCY) and the locale it's formatted with (REGION_LOCALE), so an + English browser in Argentina sees $50.000 and not ARS 50,000. - Estos mapas son dato a mano (Intl no expone región → moneda ni región → - locale). Solo definen cómo se PINTA un importe: el valor persistido no - cambia ni se convierte. Si el país no está en ninguno, formatPrice cae al - símbolo $ genérico. */ + These maps are hand-written data (Intl exposes neither region → currency nor + region → locale). They only define how an amount is RENDERED: the persisted + value doesn't change and isn't converted. If the country is in neither map, + formatPrice falls back to the generic $ symbol. */ export const REGION_CURRENCY: Record = { - // Norteamérica + // North America CA: 'CAD', US: 'USD', - // Latinoamérica y Caribe + // Latin America and the Caribbean AR: 'ARS', BO: 'BOB', BR: 'BRL', @@ -40,7 +40,7 @@ export const REGION_CURRENCY: Record = { UY: 'UYU', VE: 'VES', - // Zona euro + // Eurozone AT: 'EUR', BE: 'EUR', HR: 'EUR', @@ -62,7 +62,7 @@ export const REGION_CURRENCY: Record = { SI: 'EUR', ES: 'EUR', - // Fuera de la zona euro + // Outside the eurozone CH: 'CHF', GB: 'GBP', CZ: 'CZK', @@ -75,15 +75,15 @@ export const REGION_CURRENCY: Record = { UA: 'UAH', } -/** Regional con la que se formatea para cada país. México y Argentina usan - separadores distintos (1,234.56 vs 1.234,56), así que el locale va con el - país y no solo con el idioma. */ +/** Locale each country is formatted with. Mexico and Argentina use different + separators (1,234.56 vs 1.234,56), so the locale follows the country and not + just the language. */ export const REGION_LOCALE: Record = { - // Norteamérica + // North America CA: 'en-CA', US: 'en-US', - // Latinoamérica y Caribe + // Latin America and the Caribbean AR: 'es-AR', BO: 'es-BO', BR: 'pt-BR', @@ -105,7 +105,7 @@ export const REGION_LOCALE: Record = { UY: 'es-UY', VE: 'es-VE', - // Zona euro + // Eurozone AT: 'de-AT', BE: 'nl-BE', HR: 'hr-HR', @@ -127,7 +127,7 @@ export const REGION_LOCALE: Record = { SI: 'sl-SI', ES: 'es-ES', - // Fuera de la zona euro + // Outside the eurozone CH: 'de-CH', GB: 'en-GB', CZ: 'cs-CZ', @@ -140,16 +140,16 @@ export const REGION_LOCALE: Record = { UA: 'uk-UA', } -/* Zona horaria IANA → región ISO 3166-1 alpha-2. +/* IANA time zone → ISO 3166-1 alpha-2 region. - Cobertura: las zonas de los países de arriba, agrupadas por prefijo - (America/Argentina/*) o por la ciudad en la zona (Sao_Paulo). Cubre las - zonas principales; una zona desconocida cae al país del idioma. */ + Coverage: the time zones of the countries above, grouped by prefix + (America/Argentina/*) or by the city in the zone (Sao_Paulo). It covers the + main zones; an unknown zone falls back to the country of the language. */ export const TIMEZONE_REGION: Record = { - // ── Latinoamérica ───────────────────────────────────────────────────────── + // ── Latin America ───────────────────────────────────────────────────────── 'America/Argentina/': 'AR', - // Chromium/ICU reporta en la forma legacy (sin el prefijo "Argentina/") las - // zonas argentinas más comunes: America/Argentina/Buenos_Aires → America/Buenos_Aires. + // Chromium/ICU reports the most common Argentine zones in the legacy form + // (without the "Argentina/" prefix): America/Argentina/Buenos_Aires → America/Buenos_Aires. 'America/Buenos_Aires': 'AR', 'America/Catamarca': 'AR', 'America/Cordoba': 'AR', @@ -182,7 +182,7 @@ export const TIMEZONE_REGION: Record = { 'America/Santo_Domingo': 'DO', 'America/Puerto_Rico': 'PR', - // ── Norteamérica ───────────────────────────────────────────────────────── + // ── North America ───────────────────────────────────────────────────────── 'America/New_York': 'US', 'America/Detroit': 'US', 'America/Chicago': 'US', @@ -199,7 +199,7 @@ export const TIMEZONE_REGION: Record = { 'America/Regina': 'CA', 'America/St_Johns': 'CA', - // ── Europa ─────────────────────────────────────────────────────────────── + // ── Europe ─────────────────────────────────────────────────────────────── 'Europe/Madrid': 'ES', 'Atlantic/Canary': 'ES', 'Atlantic/Faeroe': 'ES', @@ -244,8 +244,8 @@ export function regionForTimezone(timezone: string | undefined): string | undefi return prefix ? TIMEZONE_REGION[prefix] : undefined } -/** Región del locale (es-MX → MX). Un locale sin país se maximiza, pero solo - como último recurso: countryOf prefiere la zona horaria. */ +/** Region of the locale (es-MX → MX). A locale without a country is + maximized, but only as a last resort: countryOf prefers the time zone. */ export function regionOf(locale: string | undefined): string | undefined { if (!locale || typeof Intl.Locale === 'undefined') return undefined try { @@ -255,9 +255,9 @@ export function regionOf(locale: string | undefined): string | undefined { } } -/** País de la persona: el de la zona horaria, y si no se conoce, el del - idioma. `en` sin país no se maximiza a US a propósito: un usuario en - México con el browser en inglés caería en dólares. */ +/** The person's country: the one from the time zone and, when unknown, the one + from the language. A bare `en` is deliberately not maximized to US: a user in + Mexico with an English browser would end up in dollars. */ export function countryOf(locale: string | undefined): string | undefined { return regionForTimezone(browserTimezone()) ?? regionOf(locale) } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index e72bdeb..a46049c 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -10,14 +10,14 @@ export default defineConfig({ react(), tailwindcss(), VitePWA({ - // `autoUpdate` activa skipWaiting + clientsClaim: el SW nuevo toma el - // control en el próximo load sin pedirle nada al usuario. + // `autoUpdate` turns on skipWaiting + clientsClaim: the new SW takes + // control on the next load without asking the user for anything. registerType: 'autoUpdate', - // El registro se hace desde PwaProvider para poder avisar cuando la app - // ya está lista para operar sin conexión. + // Registration is done from PwaProvider so we can tell the user when the + // app is ready to work offline. injectRegister: null, - // Los iconos ya entran por `workbox.globPatterns`; con - // `includeManifestIcons` se listarían dos veces en el precache. + // The icons already come in through `workbox.globPatterns`; with + // `includeManifestIcons` they would be listed twice in the precache. includeManifestIcons: false, manifest: { name: 'Gruperly', @@ -48,24 +48,26 @@ export default defineConfig({ ], }, workbox: { - // El woff2 de Inter se importa desde node_modules: Vite lo emite a - // assets/ con hash y entra al precache para que la app abra offline. + // Inter's woff2 is imported from node_modules: Vite emits it to + // assets/ with a hash and it goes into the precache so the app opens + // offline. globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'], - // Solo el script del SW queda fuera: precachearlo cachearía la versión - // vieja. El runtime `workbox-.js` sí se precachea a propósito, así - // el SW puede arrancar sin red. No usar `**/workbox-*.js`: ese patrón - // también matchea `workbox-window.*.js`, que es el módulo cliente que - // importa `virtual:pwa-register` y sin él falla el registro. + // Only the SW script is left out: precaching it would cache the old + // version. The `workbox-.js` runtime *is* precached on purpose, so + // the SW can boot without network. Do not use `**/workbox-*.js`: that + // pattern also matches `workbox-window.*.js`, which is the client module + // that imports `virtual:pwa-register` and without it registration fails. globIgnores: ['**/sw.js'], - // App shell para toda navegación, incluidas las rutas profundas - // /join/$token y /report-absence/$token. + // App shell for every navigation, including the deep routes + // /join/$token and /report-absence/$token. navigateFallback: '/index.html', navigateFallbackDenylist: [/^\/api\//], cleanupOutdatedCaches: true, runtimeCaching: [ { - // La API nunca se cachea: son datos de cobros y una respuesta - // vieja sería peor que un error. Offline carga el shell, no los datos. + // The API is never cached: it holds payment data and a stale + // response is worse than an error. Offline loads the shell, not + // the data. urlPattern: ({ url, request }) => request.method !== 'GET' || url.pathname.startsWith('/api/'), handler: 'NetworkOnly', }, diff --git a/docker-compose.yml b/docker-compose.yml index ff89ce3..0b070c7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,14 +1,15 @@ -# Deploy en Dokploy (o `docker compose up --build` en cualquier lado). +# Deploy on Dokploy (or `docker compose up --build` anywhere). # -# El dominio público se expone una sola vez, en `web`: nginx sirve el bundle de -# Vite y hace de proxy de /api hacia el contenedor `api`. Eso deja la cookie de -# sesión first-party (no hace falta SameSite=None) y vuelve innecesario el -# preflight CORS. Si preferís subdominio aparte para la API, quitá el bloque -# `location /api/` de apps/web/nginx.conf y seteá VITE_API_URL al construir web. +# The public domain is exposed once, on `web`: nginx serves the Vite bundle and +# proxies /api to the `api` container. That keeps the session cookie +# first-party (no SameSite=None needed) and makes the CORS preflight +# unnecessary. If you rather have the API on its own subdomain, drop the +# `location /api/` block from apps/web/nginx.conf and set VITE_API_URL when +# building web. x-backend-env: &backend-env NODE_ENV: production - # Web y API comparten dominio público: mismo origen para cookies y CORS. + # Web and API share the public domain: same origin for cookies and CORS. DATABASE_URL: "${DATABASE_URL:?falta DATABASE_URL}" WEB_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" BETTER_AUTH_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" @@ -42,26 +43,26 @@ services: dockerfile: Dockerfile.web target: web args: - # Se hornea en el bundle. Vacío = mismo origen (proxy /api de nginx). + # Baked into the bundle. Empty = same origin (nginx's /api proxy). VITE_API_URL: ${VITE_API_URL:-} restart: unless-stopped depends_on: - api ports: - # Publicación en el host, solo para probar en local. En Dokploy el dominio - # va al puerto 80 del contenedor: Traefik no pasa por el mapeo. + # Host publishing, only for local testing. On Dokploy the domain goes to + # port 80 of the container: Traefik does not go through the mapping. - "8080:80" networks: - default - # Dokploy agrega dokploy-network solo al servicio con dominio, así que hay - # que declararla explícitamente para que Traefik llegue a este contenedor. + # Dokploy adds dokploy-network only to the service with a domain, so it has + # to be declared explicitly for Traefik to reach this container. - dokploy-network -# Red compartida de Dokploy: es donde viven las bases de datos que administra -# Dokploy. Sin esto, el contenedor api no resuelve ni alcanza a la base y Prisma -# falla con P1001 "Can't reach database server". +# Dokploy shared network: that is where the databases Dokploy manages live. +# Without it, the api container neither resolves nor reaches the database and +# Prisma fails with P1001 "Can't reach database server". # -# Fuera de Dokploy hay que crearla una vez antes del primer `docker compose up`: +# Outside Dokploy you have to create it once, before the first `docker compose up`: # docker network create dokploy-network networks: dokploy-network: diff --git a/packages/shared/src/lib/attendance-risk.ts b/packages/shared/src/lib/attendance-risk.ts index b5399b3..6164e61 100644 --- a/packages/shared/src/lib/attendance-risk.ts +++ b/packages/shared/src/lib/attendance-risk.ts @@ -1,99 +1,102 @@ import type { AttendanceRiskLevelDto, AttendanceStatus } from '../schemas/attendance.js'; -/* Riesgo de abandono de un alumno, derivado del historial de asistencia. - Vive en `shared` y no importa nada de UI: lo usan el resumen por grupo del - backend, la tarjeta del listado y la sección de seguimiento del Inicio. +/* Dropout risk of an attendee, derived from the attendance history. + It lives in `shared` and imports nothing from the UI: the backend's + per-group summary, the listing card and the Home follow-up section use it. - Los umbrales viven todos acá, en un solo objeto. La regla es de negocio - ("3 faltas seguidas = alguien se está yendo"), no de pantalla, así que un - componente nunca debería escribir el número crudo. + All the thresholds live here, in a single object. The rule is a business + rule ("3 consecutive absences = someone is leaving"), not a screen rule, so + a component should never write the raw number. - ── Qué clase se considera ──────────────────────────────────────────────── - El modelo actual guarda la asistencia como `Attendance` (una fila por alumno - y clase, con `PRESENT` / `ABSENT` / `EXCUSED`) colgando de un `ClassSession` - que tiene `startsAt`. No existe columna de "clase cancelada", así que las - dos señales de que una clase no computa son: + ── Which classes count ─────────────────────────────────────────────────── + The current model stores attendance as `Attendance` (one row per attendee + and class, with `PRESENT` / `ABSENT` / `EXCUSED`) hanging off a `ClassSession` + that has `startsAt`. There is no "class cancelled" column, so the two signals + that a class does not count are: - - `status: null` — la clase pasó y nadie registró asistencia. Sin dato no hay - ni asistencia ni ausencia: no entra en el promedio y **corta** la racha (si - no, un alumno con una clase sin registrar entre dos faltas tendría una - racha que nunca ocurrió). - - `status: 'EXCUSED'` — el alumno avisó la ausencia con anticipación y le - liberaron el lugar (`SlotRelease`). Es la clase que "no cuenta": corta la - racha igual que `PRESENT` y tampoco entra en el promedio. + - `status: null` — the class happened and nobody recorded attendance. With + no record there is neither attendance nor absence: it does not enter the + average and it **breaks** the streak (otherwise, an attendee with an + unrecorded class between two absences would have a streak that never + happened). + - `status: 'EXCUSED'` — the attendee gave notice ahead of time and the spot + was released to them (`SlotRelease`). This is the class that "does not + count": it breaks the streak just like `PRESENT` and it does not enter the + average either. - Sólo entran al cálculo las clases que (a) ya ocurrieron, `startsAt <= now`, y - (b) son posteriores al alta del alumno, `startsAt >= enrolledAt`. Un alumno - recién incorporado no es penalizado por clases en las que todavía no estaba - inscripto. */ + Only the classes that (a) already happened, `startsAt <= now`, and (b) come + after the attendee's enrollment, `startsAt >= enrolledAt`, enter the + computation. A newly enrolled attendee is not penalized for classes they + were not enrolled in yet. */ -/** El mismo tipo que valida `attendanceRiskLevelSchema` cuando el nivel viaja - * por la API: una sola definición para el dominio y el transporte. */ +/** The same type `attendanceRiskLevelSchema` validates when the level travels + * over the API: a single definition for both domain and transport. */ export type AttendanceRiskLevel = AttendanceRiskLevelDto; /** - * Umbrales de la regla de riesgo. Mover estos números cambia el semáforo de - * toda la app, así que son la única fuente: nada más los hardcodea. + * Thresholds of the risk rule. Moving these numbers changes the status light + * across the whole app, so this is the only source: nothing else hardcodes + * them. */ export const ATTENDANCE_RISK_RULES = { - /** Faltas consecutivas sin justificar desde las cuales el riesgo es alto. */ + /** Unexcused absences in a streak from which the risk is high. */ highAbsenceStreak: 3, - /** Faltas consecutivas sin justificar desde las cuales hay que mirar. */ + /** Unexcused absences in a streak from which attention is needed. */ attentionAbsenceStreak: 2, - /** Días sin aparecer a una clase desde los cuales el riesgo es alto. */ + /** Days since last showing up to a class from which the risk is high. */ highInactivityDays: 10, - /** Tamaño de cada ventana de la tendencia: 4 clases recientes vs 4 anteriores. */ + /** Size of each trend window: 4 recent classes vs the 4 before them. */ trendWindowSize: 4, - /** Clases con dato necesarias para evaluar la tendencia. Con menos que esto - * (6 = 4 + 2) cualquier movimiento es ruido, no tendencia. */ + /** Marked classes needed to evaluate the trend. With fewer than this + * (6 = 4 + 2) any movement is noise, not a trend. */ trendMinClasses: 6, - /** Cuántas clases hay que haber perdido entre una ventana y la otra para que - * la tendencia cuente como "claramente" a la baja. Se cuenta en clases y no - * en puntos porcentuales a propósito: con ventana de 4 el salto más chico - * posible ya es de 25 puntos, así que un umbral en puntos no distinguiría - * "se le cayó una clase" de "se está yendo". Dos clases sí lo distingue. */ + /** How many classes have to be lost between one window and the other for + * the trend to count as "clearly" dropping. Counted in classes and not in + * percentage points on purpose: with a window of 4 the smallest possible + * jump is already 25 points, so a threshold in points would not tell + * "they missed a class" apart from "they are leaving". Two classes do. */ trendDropClasses: 2, } as const; -/** Una clase del grupo, vista desde un alumno. */ +/** A class of the group, seen from one attendee. */ export type MemberClassSession = { sessionId: string; - /** Instante real de la clase (ISO). */ + /** Actual moment of the class (ISO). */ startsAt: string; - /** `null` cuando la clase pasó y no hay registro de asistencia. */ + /** `null` when the class happened and there is no attendance record. */ status: AttendanceStatus | null; }; export type MemberAttendance = { attendeeId: string; fullName: string; - /** Momento del alta en el grupo (`Attendee.createdAt`), ISO. */ + /** Moment of enrollment in the group (`Attendee.createdAt`), ISO. */ enrolledAt: string; - /** Clases del grupo. Las funciones no asumen orden ni completitud. */ + /** The group's classes. The functions assume neither order nor completeness. */ sessions: MemberClassSession[]; }; export type GroupAttendanceInput = { groupId: string; - /** `null` cuando el grupo no tiene cupo definido. */ + /** `null` when the group has no capacity defined. */ capacity: number | null; - /** Miembros esperando cupo (`GroupWaitlistEntry` en PENDING). */ + /** Members waiting for a spot (`GroupWaitlistEntry` in PENDING). */ waitlistCount: number; members: MemberAttendance[]; - /** Momento de referencia. Por defecto `new Date()`. */ + /** Reference moment. Defaults to `new Date()`. */ now?: Date; }; export type MemberRiskSignals = { level: AttendanceRiskLevel; - /** Faltas consecutivas sin justificar, contadas desde la clase más reciente. */ + /** Unexcused absences in a streak, counted from the most recent class. */ consecutiveAbsences: number; - /** Días desde la última clase con presencia, o `null` si nunca asistió a - * ninguna clase elegible. */ + /** Days since the last class with presence, or `null` if they never attended + * any eligible class. */ daysSinceLastAttendance: number | null; - /** Asistencia 0..100 sobre las clases con dato, o `null` si no hay ninguna. */ + /** Attendance 0..100 over the marked classes, or `null` if there are none. */ attendanceRate: number | null; - /** Clase con dato sobre las cuales se puede emitir un juicio. */ + /** Marked classes a verdict can be based on. */ markedClasses: number; }; @@ -106,23 +109,23 @@ export type GroupAttendanceSummary = { riesgoAlto: number; atencion: number; ok: number; - /** Lugares del cupo sin ocupar. Con el grupo lleno o sin cupo, 0. */ + /** Free spots in the capacity. 0 when the group is full or has no capacity. */ libres: number; - /** Miembros esperando cupo. */ + /** Members waiting for a spot. */ enEspera: number; - /** Miembros que hay que mirar primero, ordenados de peor a mejor. */ + /** Members to look at first, ordered worst to best. */ urgentes: UrgentMember[]; - /** El peor nivel presente en el grupo, o `null` si el grupo está vacío. */ + /** The worst level present in the group, or `null` if the group is empty. */ peorNivel: AttendanceRiskLevel | null; - /** Asistencia promedio del grupo 0..100 sobre las clases con dato, o `null`. */ + /** Group average attendance 0..100 over the marked classes, or `null`. */ asistencia: number | null; }; const DAY_MS = 24 * 60 * 60 * 1000; /** - * Nivel de riesgo de un alumno. Es el atajo a `summarizeMemberAttendance` para - * cuando solo hace falta el semáforo. + * Risk level of an attendee. Shortcut to `summarizeMemberAttendance` for when + * only the status light is needed. */ export function getMemberAttendanceRisk( member: MemberAttendance, @@ -131,31 +134,31 @@ export function getMemberAttendanceRisk( return summarizeMemberAttendance(member, now).level; } -/** Todas las señales de un alumno, no solo el veredicto. */ +/** All the signals of an attendee, not just the verdict. */ export function summarizeMemberAttendance( member: MemberAttendance, now: Date = new Date(), ): MemberRiskSignals { const sessions = eligibleSessions(member, now); - // `eligibleSessions` devuelve de la más antigua a la más reciente, así que la - // racha se cuenta desde el final. PRESENT, EXCUSED y las clases sin registro - // cortan la cadena: una clase justificada o sin dato no es una falta más. + // `eligibleSessions` returns oldest to newest, so the streak is counted from + // the end. PRESENT, EXCUSED and classes with no record break the chain: an + // excused class or one with no record is not one more absence. let consecutiveAbsences = 0; for (let index = sessions.length - 1; index >= 0; index -= 1) { if (sessions[index].status !== 'ABSENT') break; consecutiveAbsences += 1; } - // `eligibleSessions` devuelve de la más antigua a la más reciente, así que - // "la última clase con presencia" es la primera que aparece yendo desde el - // final. (Se recorre al revés y no con `findLast` porque el target del repo es - // ES2022 y ese método es ES2023.) + // `eligibleSessions` returns oldest to newest, so "the last class with + // presence" is the first one found walking from the end. (It walks backwards + // instead of using `findLast` because the repo targets ES2022 and that + // method is ES2023.) const lastAttendedAt = lastPresentAt(sessions); - // Si nunca asistió a ninguna clase elegible, la referencia es la última clase - // que tuvo: "hace cuánto no lo vemos" sigue siendo cierto, y evita que un - // alumno con dos faltas de hace dos meses quede en verde para siempre. + // If they never attended any eligible class, the reference is the last class + // they had: "how long have we not seen them" still holds, and it keeps an + // attendee with two absences from two months ago from staying green forever. const reference = lastAttendedAt ?? sessions.at(-1)?.startsAt; const daysSinceLastAttendance = reference ? Math.floor((now.getTime() - new Date(reference).getTime()) / DAY_MS) @@ -176,7 +179,7 @@ export function summarizeMemberAttendance( }; } -/** Veredicto: primero la racha y la inactividad, después la tendencia. */ +/** Verdict: first the streak and the inactivity, then the trend. */ function classify( consecutiveAbsences: number, daysSinceLastAttendance: number | null, @@ -197,12 +200,12 @@ function classify( } /** - * Conteo por nivel del grupo, lugares libres y los miembros más urgentes. + * Count per level for the group, free spots and the most urgent members. * - * `libres` se acota a 0 porque el detalle cuenta todos los miembros, sin - * filtro de estado: un grupo con más miembros que lugares (o con el cupo sin - * definir) tiene 0 libres, nunca negativos. Un grupo vacío tiene los tres - * conteos en 0, `libres` igual al cupo y `peorNivel` en `null`. + * `libres` is clamped to 0 because the detail page counts every member, with + * no status filter: a group with more members than spots (or with no capacity + * defined) has 0 free, never negative ones. An empty group has all three counts + * at 0, `libres` equal to the capacity and `peorNivel` at `null`. */ export function getGroupAttendanceSummary( group: GroupAttendanceInput, @@ -216,8 +219,8 @@ export function getGroupAttendanceSummary( const riesgoAlto = urgentes.filter((member) => member.level === 'riesgo_alto').length; const atencion = urgentes.filter((member) => member.level === 'atencion').length; - // Una parte de los miembros ya tiene señal: el promedio entre los que sí - // tienen. Los alumnos sin ninguna clase registrada no mueven la aguja. + // Part of the members already have a signal: the average is over the ones + // that do. Attendees with no recorded class do not move the needle. const rates = urgentes .map((member) => member.attendanceRate) .filter((rate): rate is number => rate !== null); @@ -237,10 +240,10 @@ export function getGroupAttendanceSummary( asistencia, }; - /* Orden de urgencia: peor nivel primero; dentro del mismo nivel, quien - tiene más faltas seguidas, después quien hace más que no aparece, después - quien tiene menos asistencia. El nombre nunca desempata: dos personas con - la misma señal mantienen el orden en que llegaron. */ + /* Urgency order: worst level first; within the same level, whoever has more + consecutive absences, then whoever has gone the longest without showing + up, then whoever has the lower attendance. The name never breaks the tie: + two people with the same signal keep the order they arrived in. */ function byUrgency(a: UrgentMember, b: UrgentMember): number { const level = levelWeight(b.level) - levelWeight(a.level); if (level !== 0) return level; @@ -254,21 +257,21 @@ export function getGroupAttendanceSummary( } /** - * Asistencia de las últimas 4 clases con dato contra las 4 anteriores. Solo se - * declara la caída cuando hay historia para las dos ventanas: con una sola no - * hay contra qué comparar, y adivinar sería marcar alumnos que recién empiezan. + * Attendance over the last 4 marked classes against the 4 before them. The + * drop-off is only declared when there is history for both windows: with one + * alone there is nothing to compare against, and guessing would flag attendees + * who are just starting out. * - * Con ventana de 4, la diferencia mínima no nula es de una clase, que es ruido: - * por eso el umbral es de `trendDropClasses` clases perdidas y no de "cualquier - * descenso". + * With a window of 4, the smallest non-zero difference is one class, which is + * noise: that is why the threshold is `trendDropClasses` lost classes and not + * "any decrease". */ function isDeclining(sessions: MemberClassSession[]): boolean { const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } = ATTENDANCE_RISK_RULES; if (sessions.length < minClasses) return false; - // `sessions` viene de más antigua a más reciente, así que la ventana - // reciente es la cola. + // `sessions` comes oldest to newest, so the recent window is the tail. const recent = sessions.slice(-size); const previous = sessions.slice(-size * 2, -size); if (previous.length === 0 || recent.length === 0) return false; @@ -280,7 +283,7 @@ function isDeclining(sessions: MemberClassSession[]): boolean { } } -/** Inicio de la clase con presencia más reciente, o `undefined` si no tiene ninguna. */ +/** Start of the most recent class with presence, or `undefined` if they have none. */ function lastPresentAt(sessions: MemberClassSession[]): string | undefined { for (let index = sessions.length - 1; index >= 0; index -= 1) { if (sessions[index].status === 'PRESENT') return sessions[index].startsAt; @@ -288,7 +291,7 @@ function lastPresentAt(sessions: MemberClassSession[]): string | undefined { return undefined; } -/** Clases que ya ocurrieron y en las que el alumno ya estaba inscripto. */ +/** Classes that already happened and in which the attendee was already enrolled. */ function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSession[] { const enrolledAt = new Date(member.enrolledAt).getTime(); const nowMs = now.getTime(); @@ -301,7 +304,7 @@ function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSessi .sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime()); } -/** Clase con dato: sin `EXCUSED` (no computa) y sin nula (no hay registro). */ +/** Marked class: neither `EXCUSED` (does not count) nor null (no record). */ function isMarked(session: MemberClassSession): boolean { return session.status === 'PRESENT' || session.status === 'ABSENT'; } diff --git a/packages/shared/src/schemas/analytics.ts b/packages/shared/src/schemas/analytics.ts index 733e9bf..f8a81a2 100644 --- a/packages/shared/src/schemas/analytics.ts +++ b/packages/shared/src/schemas/analytics.ts @@ -69,10 +69,10 @@ export type UpdateStudentStatusResult = z.output; -/** Cuántos miembros van en la lista de urgentes del resumen. La tarjeta del - * listado solo nombra al primero o dos; el detalle tiene su propia pantalla - * de alumnos en riesgo, así que el resumen no necesita arrastrar al grupo - * entero por la red. */ +/** How many members go in the summary's urgent list. The listing card only + * names the first one or two; the detail page has its own at-risk students + * screen, so the summary does not need to drag the whole group over the + * network. */ export const URGENT_MEMBERS_LIMIT = 5; export const UrgentMemberSummarySchema = z.object({ @@ -85,21 +85,22 @@ export const UrgentMemberSummarySchema = z.object({ }); export type UrgentMemberSummary = z.output; -/* El nivel es el peor alumno del grupo; los dos contadores dicen por qué se - dispara, para que la lista pueda nombrar el motivo en vez de un "riesgo". - Son disjuntos: un miembro con racha de faltas va solo en el primero, y el - segundo agrupa a los que solo cruzan por asistencia baja. */ +/* The level is the worst attendee in the group; the two counters say why it + fires, so the list can name the reason instead of a bare "risk". They are + disjoint: a member with an absence streak lands only in the first, and the + second groups those who only cross over for low attendance. */ export const GroupRiskSummarySchema = z.object({ groupId: z.string(), groupName: z.string(), riskLevel: groupRiskLevelSchema, absenceStreakCount: z.number().int().min(0), lowAttendanceCount: z.number().int().min(0), - /* Lo que come la tarjeta del listado y la sección de seguimiento del Inicio. - Sale de `getGroupAttendanceSummary` (packages/shared/src/lib/attendance-risk.ts), - que ya recibe todo el historial en memoria: el resumen por nivel no se puede - derivar de los dos contadores de arriba, porque "ok" es la diferencia y los - lugares libres salen del cupo, no de la asistencia. */ + /* What the listing card and the Home follow-up section consume. It comes + from `getGroupAttendanceSummary` (packages/shared/src/lib/attendance-risk.ts), + which already receives the whole history in memory: the per-level summary + cannot be derived from the two counters above, because "ok" is the + difference and the free spots come from the capacity, not from + attendance. */ riesgoAlto: z.number().int().min(0), atencion: z.number().int().min(0), ok: z.number().int().min(0), diff --git a/packages/shared/src/schemas/attendance.ts b/packages/shared/src/schemas/attendance.ts index 93a2f7c..97c2c74 100644 --- a/packages/shared/src/schemas/attendance.ts +++ b/packages/shared/src/schemas/attendance.ts @@ -6,9 +6,9 @@ const isoDateTimeSchema = z.string().datetime(); export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']); export type AttendanceStatus = z.output; -/* Los tres niveles del semáforo de asistencia, en el orden de la regla (de - mejor a peor). El dominio los usa como tipo y este schema los valida cuando - viajan por la API, así que hay una sola definición. */ +/* The three levels of the attendance status light, in rule order (best to + worst). The domain uses them as a type and this schema validates them when + they travel over the API, so there is a single definition. */ export const attendanceRiskLevelSchema = z.enum(['ok', 'atencion', 'riesgo_alto']); export type AttendanceRiskLevelDto = z.output; diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index 45b108c..64cfcd1 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -9,9 +9,9 @@ const pageSchema = createPageSchema(); const pageSizeSchema = createPageSizeSchema(10); const paginationSchema = createPaginationSchema(); -/* Cuántas clases recientes viajan por miembro en el listado. Es el tamaño de la - tira de puntos del roster, no una ventana de análisis: la analítica pide - HISTORY_SESSIONS_LIMIT clases aparte. */ +/* How many recent class sessions travel per member in the listing. This is the + size of the roster's dot strip, not an analysis window: analytics asks for + HISTORY_SESSIONS_LIMIT classes separately. */ export const RECENT_ATTENDANCE_LIMIT = 5; export const AttendeeDtoSchema = z.object({ @@ -49,9 +49,9 @@ export const AttendeeQuerySchema = z.object({ export type AttendeeQuery = z.output; /** - * Cobro del período vigente, tal como está en la base: sin columna - * desnormalizada y sin veredicto calculado. El backend devuelve el pago - * impago más reciente; el cliente decide cómo presentarlo. + * Charge for the current period, as stored in the database: no denormalized + * column and no computed verdict. The backend returns the most recent unpaid + * payment; the client decides how to present it. */ export const AttendeePaymentSummarySchema = z.object({ status: paymentStatusSchema, @@ -60,15 +60,14 @@ export const AttendeePaymentSummarySchema = z.object({ export type AttendeePaymentSummary = z.output; /** - * Item del listado de miembros: `AttendeeDto` más el resumen que la fila - * necesita para no vaciarse de datos. Es un superconjunto, así que todo - * consumidor del DTO plano sigue sirviéndose sin cambios; solo los listados - * verían estos dos campos extra. + * Member listing item: `AttendeeDto` plus the summary the row needs so it does + * not run dry of data. It is a superset, so every consumer of the plain DTO + * keeps working unchanged; only the listings see these two extra fields. */ export const AttendeeListItemSchema = AttendeeDtoSchema.extend({ - /** Últimas clases de más antigua a más reciente. Vacío si nunca se registró ninguna. */ + /** Most recent class sessions, oldest to newest. Empty if none was ever recorded. */ recentAttendance: z.array(attendanceStatusSchema).max(RECENT_ATTENDANCE_LIMIT), - /** `null` si no hay ningún cobro impago registrado. */ + /** `null` if there is no unpaid charge on record. */ payment: AttendeePaymentSummarySchema.nullable(), }); export type AttendeeListItem = z.output; diff --git a/packages/shared/src/schemas/enums.ts b/packages/shared/src/schemas/enums.ts index d6416c4..77d8086 100644 --- a/packages/shared/src/schemas/enums.ts +++ b/packages/shared/src/schemas/enums.ts @@ -1,6 +1,6 @@ import { z } from 'zod'; -// Días de la semana en que se dictan las clases. +// Weekdays on which classes are held. export const weekdaySchema = z.enum([ 'MONDAY', 'TUESDAY', @@ -12,10 +12,10 @@ export const weekdaySchema = z.enum([ ]); export type WeekDay = z.output; -// Procesadores de pago soportados. +// Supported payment processors. export const paymentProviderSchema = z.enum(['MERCADO_PAGO', 'STRIPE']); export type PaymentProvider = z.output; -// Frecuencia de cobro de un grupo. +// Billing frequency of a group. export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']); export type BillingType = z.output; \ No newline at end of file diff --git a/packages/shared/src/schemas/groups.ts b/packages/shared/src/schemas/groups.ts index 8037eff..bb6db5e 100644 --- a/packages/shared/src/schemas/groups.ts +++ b/packages/shared/src/schemas/groups.ts @@ -15,7 +15,7 @@ export const GroupDtoSchema = z.object({ createdById: z.string(), createdAt: isoDateTimeSchema, updatedAt: isoDateTimeSchema, - // Horario y cobro: quedan vacíos si el grupo aún no tiene configurado el plan. + // Schedule and billing: null while the group has no plan configured yet. days: z.array(weekdaySchema).nullable(), time: z.string().nullable(), capacity: z.number().int().min(1).nullable(), @@ -45,11 +45,11 @@ export const InviteTokenResultSchema = z.object({ }); export type InviteTokenResult = z.output; -/* En el listado cada grupo viaja con sus dos contadores de ocupación porque la - card los muestra: `attendeesCount` son los miembros del grupo (todos, igual - que cuenta el detalle) y `waitlistCount` los que están en lista de espera - esperando cupo (PENDING). La lista de pre-inscriptos es otra cosa y no - entra acá. */ +/* In the listing every group travels with its two occupancy counters because + the card shows them: `attendeesCount` are the group's members (all of them, + same as the detail page counts) and `waitlistCount` those on the waitlist + waiting for a spot (PENDING). The pre-registrations list is a different + thing and does not belong here. */ export const GroupListItemSchema = GroupDtoSchema.extend({ attendeesCount: z.number().int().min(0), waitlistCount: z.number().int().min(0), @@ -59,7 +59,7 @@ export type GroupListItem = z.output; export const GroupQuerySchema = z.object({ page: pageSchema, pageSize: pageSizeSchema, - // Zona de la persona: el listado se ordena por la próxima clase en su hora local. + // The person's time zone: the listing sorts by the next class in their local time. timeZone: timeZoneSchema.optional(), }); export type GroupQuery = z.output; diff --git a/packages/shared/src/schemas/onboarding.ts b/packages/shared/src/schemas/onboarding.ts index a210edf..0262c31 100644 --- a/packages/shared/src/schemas/onboarding.ts +++ b/packages/shared/src/schemas/onboarding.ts @@ -5,10 +5,10 @@ import { GroupDtoSchema } from './groups.js'; export type { BillingType, PaymentProvider, WeekDay } from './enums.js'; export { billingTypeSchema, paymentProviderSchema, weekdaySchema } from './enums.js'; -// Paso 2: vincula la cuenta de cobro del profesor. +// Step 2: link the teacher's payment account. export const ConnectPaymentSchema = z.strictObject({ provider: paymentProviderSchema, - // Para el MVP se conecta en modo simulación / sandbox. + // For the MVP it connects in simulation / sandbox mode. sandbox: z.boolean().default(true), accessToken: z.string().optional(), }); @@ -21,7 +21,7 @@ export const ConnectPaymentResultSchema = z.object({ }); export type ConnectPaymentResult = z.output; -// Paso 3: crea el primer grupo del profesor. +// Step 3: create the teacher's first group. export const CreateFirstGroupSchema = z.strictObject({ name: z .string() @@ -64,7 +64,7 @@ export const CreateFirstGroupResultSchema = z.object({ }); export type CreateFirstGroupResult = z.output; -// Estado del onboarding para retomar el flujo si se interrumpió. +// Onboarding state, to resume the flow if it was interrupted. export const onboardingStepSchema = z.enum(['NOT_STARTED', 'PAYMENT_CONNECTED', 'COMPLETED']); export type OnboardingStep = z.output;