chore: update comments and documentation for clarity and consistency across various files

- Translated comments from Spanish to English in vite.config.ts, docker-compose.yml, attendance-risk.ts, analytics.ts, attendance.ts, attendees.ts, enums.ts, groups.ts, and onboarding.ts.
- Improved descriptions for better understanding of code functionality and purpose.
- Ensured uniformity in terminology and phrasing throughout the codebase.
This commit is contained in:
Jose Selesan
2026-10-01 16:06:54 -03:00
parent 01b35691df
commit 69275c37b4
100 changed files with 1121 additions and 1086 deletions

View File

@@ -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. # Local: copy this file to `.env` at the root and fill in the values.
# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña # Dokploy: no file needed; define the same variables in the Environment tab of
# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del # the Compose service (Dokploy writes them to a `.env` next to the compose
# compose, que es de donde salen los `${...}`). # file, which is where the `${...}` come from).
# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y # Public origin of the app, no trailing slash. The same value feeds WEB_URL and
# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten # BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
# dominio y por lo tanto la cookie de sesión es first-party. # domain, so the session cookie is first-party.
WEB_URL="http://localhost:8080" WEB_URL="http://localhost:8080"
# PostgreSQL de producción. # Production PostgreSQL.
# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala # The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza # escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
# el fragmento y falla con P1013 "invalid port number in database URL". # 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" 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="" 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_ID=""
# GOOGLE_CLIENT_SECRET="" # 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_PROVIDER="smtp"
# EMAIL_SERVER_HOST="" # EMAIL_SERVER_HOST=""
# EMAIL_SERVER_PORT="587" # EMAIL_SERVER_PORT="587"
@@ -33,6 +35,7 @@ BETTER_AUTH_SECRET=""
# EMAIL_SERVER_PASSWORD="" # EMAIL_SERVER_PASSWORD=""
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>" # EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga # Only if you want the API on another domain: it is baked into the Vite bundle
# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado). # and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
# origin (recommended).
# VITE_API_URL="" # VITE_API_URL=""

View File

@@ -5,21 +5,21 @@ FROM oven/bun:1.4-alpine AS base
WORKDIR /app WORKDIR /app
ENV CI=1 ENV CI=1
# ─── Dependencias ──────────────────────────────────────────────────────────── # ─── Dependencies ────────────────────────────────────────────────────────────
# Solo los package.json:bun no necesita el código fuente para resolver el lockfile. # Only the package.json files: bun needs no source code to resolve the lockfile.
FROM base AS deps FROM base AS deps
COPY package.json bun.lock bunfig.toml turbo.json ./ COPY package.json bun.lock bunfig.toml turbo.json ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY apps/web/package.json ./apps/web/ COPY apps/web/package.json ./apps/web/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ 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 RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
# ─── Prisma Client ─────────────────────────────────────────────────────────── # ─── Prisma Client ───────────────────────────────────────────────────────────
# El generator "prisma-client" emite TypeScript, así que el cliente generado se # The "prisma-client" generator emits TypeScript, so the generated client runs
# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no # with Bun without compilation. The URL is a placeholder: `generate` only needs
# necesita conexión, solo leer el schema. # to read the schema, not connect to a database.
FROM deps AS generate FROM deps AS generate
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
ENV DATABASE_URL=$DATABASE_URL ENV DATABASE_URL=$DATABASE_URL
@@ -28,7 +28,7 @@ COPY apps/backend/prisma ./apps/backend/prisma
WORKDIR /app/apps/backend WORKDIR /app/apps/backend
RUN bun run db:generate RUN bun run db:generate
# ─── Imagen de la API ──────────────────────────────────────────────────────── # ─── API image ───────────────────────────────────────────────────────────────
FROM base AS api FROM base AS api
ENV NODE_ENV=production \ ENV NODE_ENV=production \
PORT=4000 PORT=4000
@@ -37,30 +37,30 @@ COPY package.json bun.lock bunfig.toml ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ COPY packages/shared/package.json ./packages/shared/
# `prisma` y `dotenv` son dependencies (no dev) porque el entrypoint corre # `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto # `prisma migrate deploy` on every boot. With `--production` the rest of the
# del tooling: biome, typescript, turbo. # tooling does not come in: biome, typescript, turbo.
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install 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 ./apps/backend/prisma
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
COPY apps/backend/tsconfig.json ./apps/backend/ COPY apps/backend/tsconfig.json ./apps/backend/
COPY apps/backend/src ./apps/backend/src COPY apps/backend/src ./apps/backend/src
# @gruperly/shared se consume como fuente TS; @gruperly/config aporta el # @gruperly/shared is consumed as TS source; @gruperly/config provides the base
# tsconfig base del que extiende el tsconfig del backend. # tsconfig that the backend tsconfig extends.
COPY packages ./packages COPY packages ./packages
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh RUN chmod +x /usr/local/bin/docker-entrypoint.sh
WORKDIR /app/apps/backend WORKDIR /app/apps/backend
EXPOSE 4000 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 \ 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))" 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"] ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
# Bun ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json, # Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
# igual que `bun start` en local. # same as `bun start` locally.
CMD ["bun", "src/server.ts"] CMD ["bun", "src/server.ts"]

View File

@@ -5,27 +5,27 @@ FROM oven/bun:1.4-alpine AS base
WORKDIR /app WORKDIR /app
ENV CI=1 ENV CI=1
# ─── Dependencias ──────────────────────────────────────────────────────────── # ─── Dependencies ────────────────────────────────────────────────────────────
FROM base AS deps FROM base AS deps
COPY package.json bun.lock bunfig.toml turbo.json ./ COPY package.json bun.lock bunfig.toml turbo.json ./
COPY apps/backend/package.json ./apps/backend/ COPY apps/backend/package.json ./apps/backend/
COPY apps/web/package.json ./apps/web/ COPY apps/web/package.json ./apps/web/
COPY packages/config/package.json ./packages/config/ COPY packages/config/package.json ./packages/config/
COPY packages/shared/package.json ./packages/shared/ 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 RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
# ─── Build de Vite ─────────────────────────────────────────────────────────── # ─── Vite build ──────────────────────────────────────────────────────────────
FROM deps AS build FROM deps AS build
# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime. # Vite replaces import.meta.env.* at build time, not at runtime.
# Vacío = mismo origen: el proxy /api de nginx hace de API. # Empty = same origin: nginx's /api proxy acts as the API.
ARG VITE_API_URL="" ARG VITE_API_URL=""
ENV VITE_API_URL=$VITE_API_URL ENV VITE_API_URL=$VITE_API_URL
COPY apps/web ./apps/web COPY apps/web ./apps/web
COPY packages ./packages COPY packages ./packages
RUN bun --filter @gruperly/web build RUN bun --filter @gruperly/web build
# ─── Imagen final ──────────────────────────────────────────────────────────── # ─── Final image ─────────────────────────────────────────────────────────────
FROM nginx:1.27-alpine AS web FROM nginx:1.27-alpine AS web
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/apps/web/dist /usr/share/nginx/html COPY --from=build /app/apps/web/dist /usr/share/nginx/html

View File

@@ -1,12 +1,12 @@
#!/bin/sh #!/bin/sh
# Entrypoint de producción del backend: aplica las migraciones y levanta el # Production entrypoint for the backend: applies the migrations and starts the
# servidor en el mismo contenedor. # server in the same container.
# #
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo # This is POSIX sh, not bash: the image is alpine and does not ship bash
# serían ~10MB por un shebang). # installed (adding it would be ~10MB for a shebang).
# #
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una # Set RUN_MIGRATIONS=false to start without touching the database (for example,
# base ya migrada a mano o una que se gestiona fuera de este despliegue). # a database already migrated by hand, or one managed outside this deployment).
set -e set -e
: "${DATABASE_URL:?falta DATABASE_URL}" : "${DATABASE_URL:?falta DATABASE_URL}"
@@ -18,8 +18,8 @@ else
delay="${MIGRATE_RETRY_DELAY:-5}" delay="${MIGRATE_RETRY_DELAY:-5}"
i=1 i=1
# La base puede seguir arrancando cuando este contenedor ya empezó, y un # The database may still be starting up when this container is already
# deploy suele convivir con un reinicio de Postgres. # running, and a deploy usually overlaps a Postgres restart.
while [ "$i" -le "$attempts" ]; do while [ "$i" -le "$attempts" ]; do
if bun run db:deploy; then if bun run db:deploy; then
echo "migrate: listo" echo "migrate: listo"
@@ -37,6 +37,6 @@ else
done done
fi fi
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop` # exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma). # (the server uses it to close Bun.serve and disconnect Prisma).
exec "$@" exec "$@"

View File

@@ -27,7 +27,7 @@ export function isPublicApiRequest(method: string, path: string): boolean {
const normalizedPath = normalizePath(path); 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') { if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
return true; return true;
} }

View File

@@ -5,14 +5,14 @@ type VerificationEmailData = { email: string; url: string; name?: string }
type PasswordResetEmailData = { email: string; url: string; name?: string } type PasswordResetEmailData = { email: string; url: string; name?: string }
type InvitationEmailData = { email: string; url: string; organizationName: 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 BRAND_600 = '#2544ea'
const TEXT_STRONG = '#0f172a' const TEXT_STRONG = '#0f172a'
const TEXT_MUTED = '#475569' const TEXT_MUTED = '#475569'
const ON_ACCENT = '#ffffff' const ON_ACCENT = '#ffffff'
const LINK_BG = BRAND_600 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 { function loadLogoTypoDataUri(): string {
try { try {
const base64 = readFileSync( const base64 = readFileSync(
@@ -66,7 +66,7 @@ class SMTPEmailProvider implements EmailProvider {
} }
private async send(to: string, subject: string, html: string) { 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) { if (!process.env.EMAIL_SERVER_HOST) {
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`) console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
return return
@@ -111,8 +111,8 @@ class SMTPEmailProvider implements EmailProvider {
} }
} }
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark). // Future: transactional providers (Resend, SendGrid, Postmark).
// Añadir implementaciones y alternar con EMAIL_PROVIDER. // Add implementations and switch between them with EMAIL_PROVIDER.
export function createEmailProvider(): EmailProvider { export function createEmailProvider(): EmailProvider {
return new SMTPEmailProvider() return new SMTPEmailProvider()
} }

View File

@@ -21,11 +21,11 @@ import {
} from '../../lib/risk'; } from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; 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: /* How many classes we look back per attendee. That is the real ceiling of the
los `class_sessions` no se crean solos, se materializan cuando alguien entra model: `class_sessions` are not created on their own, they get materialized
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20 when someone opens "today's classes", so pulling years of rows makes no
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el sense. 20 classes is enough for the streak, for the 4+4 trend window and for
porcentaje de asistencia que muestra la tarjeta. */ the attendance rate the card shows. */
const MEMBER_HISTORY_LIMIT = 20; const MEMBER_HISTORY_LIMIT = 20;
type GetGroupsRiskOverviewDeps = { type GetGroupsRiskOverviewDeps = {
@@ -42,7 +42,7 @@ type GroupRow = {
id: string; id: string;
name: string; name: string;
capacity: number | null; 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 }; _count: { waitlist: number };
}; };
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date }; type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
@@ -54,10 +54,10 @@ type AttendanceRow = {
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
// Resumen de semáforo de riesgo por grupo para la lista de grupos. // Risk status light summary per group for the group listing.
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si // A group is HIGH if it has at least one attendee at high risk, MEDIUM if
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el // any is at medium risk and NONE otherwise. The counters state the reason
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo. // (consecutive absences or low attendance) so the listing can name it.
export class GetGroupsRiskOverview { export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -92,10 +92,10 @@ export class GetGroupsRiskOverview {
select: { id: true, groupId: true, startsAt: true }, select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' }, orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>, }) as Promise<SessionRow[]>,
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el /* No date filter, as before: the status light streak counts over the
historial completo del alumno, no sobre la ventana mensual. Sin recorte attendee's full history, not over the monthly window. No cap either:
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`, the cut to the last 20 classes is done by `memberSessions`, over the
sobre las clases del grupo y no sobre estas filas. */ group's classes and not over these rows. */
db.attendance.findMany({ db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds } } }, where: { attendee: { groupId: { in: groupIds } } },
select: { select: {
@@ -118,9 +118,10 @@ export class GetGroupsRiskOverview {
const streamByAttendee = groupAttendanceByAttendee(attendances); const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>(); const worstRiskByGroup = new Map<string, GroupRiskLevel>();
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas // Why there is risk, computed in the same pass: a member with an absence
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan // streak counts in the first counter and only there; the second one
// a racha y aun así quedan por debajo del mínimo de asistencia. // groups the members that don't reach a streak and are still below the
// attendance minimum.
const absenceStreakCountByGroup = new Map<string, number>(); const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>(); const lowAttendanceCountByGroup = new Map<string, number>();
@@ -169,14 +170,14 @@ export class GetGroupsRiskOverview {
} }
/** /**
* El resumen por nivel que consumen la tarjeta del listado y la sección de * The per-level summary consumed by the listing card and the Home follow-up
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función * section. It comes from `getGroupAttendanceSummary`, the same domain function
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla * that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
* no tenga dos copias: una acá y otra en el cliente. * copies: one here and another in the client.
* *
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen * `libres` and `enEspera` come from here and not from the `Attendee` count: the
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo * summary counts the group members and the card needs the capacity slots to
* para pintar el indicador. * paint the indicator.
*/ */
function buildSummaryFields( function buildSummaryFields(
group: GroupRow, group: GroupRow,
@@ -194,9 +195,9 @@ function buildSummaryFields(
.filter((attendee) => attendee.groupId === group.id) .filter((attendee) => attendee.groupId === group.id)
.map((attendee) => { .map((attendee) => {
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? []; const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej. // If the attendee has attendances before their enrollment date in the
// creado hoy pero con clases pasadas registradas), su fecha efectiva de // DB (e.g. created today but with past classes already recorded), their
// incorporación es la de la primera clase a la que se le tomó asistencia. // effective join date is the first class they were marked for.
const earliestAttendance = attendeeAttendances.reduce<Date | null>( const earliestAttendance = attendeeAttendances.reduce<Date | null>(
(earliest, att) => (earliest, att) =>
!earliest || att.classSession.startsAt < earliest !earliest || att.classSession.startsAt < earliest
@@ -257,18 +258,18 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
return byAttendee; return byAttendee;
} }
/* El universo de clases es el del grupo, no el de las filas de `Attendance`. /* The universe of classes is the group's, not the `Attendance` rows'.
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así Attendance is recorded attendee by attendee and only when someone marks a
que "esta clase pasó y no hay registro de este alumno" es un estado real y class, so "this class happened and this attendee has no record" is a real
frecuente, no una falta. Si la lista se armara desde las filas de asistencia and frequent state, not an absence. If the list were built from the
esas clases no existirían y la racha no se cortaría: dos faltas separadas por attendance rows those classes wouldn't exist and the streak wouldn't break:
una clase sin marcar se contarían como tres seguidas. two absences separated by an unmarked class would count as three in a row.
El dominio ya las trata como neutras (`status: null`), así que acá solo hay The domain already treats them as neutral (`status: null`), so all that is
que elegir bien el universo y dejar el criterio en un solo lado. left here is to pick the right universe and keep the criterion on one side.
`sessions` viene de más reciente a más antigua, así que quedarse con las `sessions` comes from most recent to oldest, so keeping the first
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El `MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
recorte va por alumno y no global para que un grupo con mucha historia no le and not global, so a group with a long history doesn't steal window from
robe ventana a los grupos que se listan después. */ the groups listed after it. */
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] { function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status])); const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));

View File

@@ -12,7 +12,7 @@ type GroupWithAccess = {
members: { userId: string }[]; 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( export async function findGroupForUser(
db: AnalyticsAccessDb, db: AnalyticsAccessDb,
groupId: string, groupId: string,

View File

@@ -5,14 +5,14 @@ export type AttendanceStreamEntry = {
export type RiskLevel = 'HIGH' | 'MEDIUM'; 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; 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; export const MIN_RISK_MONTHLY_RATE = 50;
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente. // Counts the consecutive unexcused absences from the most recent class.
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena. // Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number { export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
let streak = 0; let streak = 0;
for (const entry of entries) { for (const entry of entries) {
@@ -24,7 +24,7 @@ export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
return streak; 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 { export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
for (const entry of entries) { for (const entry of entries) {
if (entry.status === 'PRESENT') { if (entry.status === 'PRESENT') {
@@ -34,8 +34,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
return null; return null;
} }
// Porcentaje de asistencia sobre el total de sesiones del período. // Attendance rate over the total number of sessions in the period.
// Las sesiones sin registrar cuentan como no asistidas. // Sessions with no record count as not attended.
export function monthlyAttendanceRate( export function monthlyAttendanceRate(
entries: AttendanceStreamEntry[], entries: AttendanceStreamEntry[],
totalSessions: number, totalSessions: number,
@@ -47,7 +47,7 @@ export function monthlyAttendanceRate(
return Math.round((present / totalSessions) * 100); 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( export function classifyRisk(
consecutiveAbsences: number, consecutiveAbsences: number,
monthlyRate: number, monthlyRate: number,

View File

@@ -41,7 +41,7 @@ export class BulkCreateAttendeesUseCase {
return err(noGroupAccessProblem()); return err(noGroupAccessProblem());
} }
// Cargar teléfonos existentes del grupo // Load the group's existing phone numbers
const existingAttendees = await db.attendee.findMany({ const existingAttendees = await db.attendee.findMany({
where: { groupId }, where: { groupId },
select: { phone: true }, select: { phone: true },

View File

@@ -18,18 +18,18 @@ export class ListAttendees {
const where = query.groupId ? { groupId: query.groupId } : undefined; const where = query.groupId ? { groupId: query.groupId } : undefined;
const [records, total] = await Promise.all([ const [records, total] = await Promise.all([
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con /* Each row's summary travels in the same query instead of being built
una petición por miembro. Ambas relaciones vienen acotadas a propósito: with one request per member. Both relations are capped on purpose:
la tabla de pagos crece un renglón por mes y para siempre, y el listado the payments table grows one row per month forever, and the listing
solo necesita el estado actual de cada persona. */ only needs each person's current state. */
db.attendee.findMany({ db.attendee.findMany({
...(where ? { where } : {}), ...(where ? { where } : {}),
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: { include: {
// Por fecha de la clase, no por `markedAt`: marcar la asistencia // By class date, not by `markedAt`: marking attendance late must not
// tarde no debe cambiar qué clase cuenta como reciente. // change which class counts as recent.
attendances: { attendances: {
orderBy: { classSession: { startsAt: 'desc' } }, orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT, take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -14,7 +14,7 @@ export type AttendeeRecord = {
updatedAt: Date; 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 & { export type AttendeeListItemRecord = AttendeeRecord & {
attendances: { status: AttendeeListItem['recentAttendance'][number] }[]; attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
payments: { 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 /* The row that summarizes the current charge. If something is unpaid the
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos oldest due date wins: someone carrying an old charge has to see how many
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada days late they are, not the due date of a new charge. If nothing is left
impago, el último pago cerrado sirve para marcar la fila como al día. */ unpaid, the last closed payment serves to mark the row as ok. */
function pickRelevantPayment( function pickRelevantPayment(
payments: AttendeeListItemRecord['payments'], payments: AttendeeListItemRecord['payments'],
): AttendeeListItem['payment'] { ): AttendeeListItem['payment'] {
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos // CANCELLED is not a charge. The query already filters them out, but dropping
// acá también evita que un cargo anulado gane la fila por ser el más antiguo. // them here too keeps a voided charge from winning the row for being the oldest.
const byDueDate = payments const byDueDate = payments
.filter((payment) => payment.status !== 'CANCELLED') .filter((payment) => payment.status !== 'CANCELLED')
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime()); .sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
@@ -60,8 +60,8 @@ function pickRelevantPayment(
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() }; return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
} }
/* La consulta viene en orden descendente; la fila los muestra de más antigua a /* The query comes in descending order; the row shows them from oldest to most
más reciente para que el punto de la derecha sea el último hecho. */ recent so the dot on the right is the latest event. */
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem { export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
return { return {
...toAttendeeDto(record), ...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. * Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
* Conserva el '+' si lo tiene al inicio para números internacionales. * Keeps a leading '+' for international numbers.
*/ */
export function normalizePhone(rawPhone: string): string { export function normalizePhone(rawPhone: string): string {
const trimmed = rawPhone.trim(); const trimmed = rawPhone.trim();

View File

@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
const route = new Hono(); 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) => { route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
const query = c.req.valid('query') as AbsenceQuery; const query = c.req.valid('query') as AbsenceQuery;
const useCase = new GetAbsenceDetails(); const useCase = new GetAbsenceDetails();

View File

@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
const route = new Hono(); 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) => { route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
const payload = c.req.valid('json') as PublicNotifyAbsence; const payload = c.req.valid('json') as PublicNotifyAbsence;
const useCase = new PublicNotifyAbsenceUseCase(); const useCase = new PublicNotifyAbsenceUseCase();

View File

@@ -18,8 +18,8 @@ type PaymentLike = {
dueDate: Date; dueDate: Date;
}; };
// Estado de cobro calculado en tiempo real (sin columna denormalizada): // Payment status computed in real time (no denormalized column):
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó. // PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
export function resolvePaymentStatus( export function resolvePaymentStatus(
payments: PaymentLike[], payments: PaymentLike[],
startOfToday: Date, startOfToday: Date,
@@ -52,7 +52,7 @@ type GroupWithAccess = {
members: { userId: string }[]; 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( export function ensureSessionAccess(
session: ClassSessionRecord & { group: GroupWithAccess }, session: ClassSessionRecord & { group: GroupWithAccess },
userId: string, userId: string,

View File

@@ -17,9 +17,9 @@ type RegisterAbsenceInput = {
releaseHours: number; releaseHours: number;
}; };
// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token): // Shared core of the absence notice (authenticated teacher and attendee with a token):
// - Marca la asistencia como EXCUSED (upsert idempotente). // - Marks the attendance as EXCUSED (idempotent upsert).
// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo. // - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot.
export async function registerAbsence( export async function registerAbsence(
deps: RegisterAbsenceDeps, deps: RegisterAbsenceDeps,
input: RegisterAbsenceInput, input: RegisterAbsenceInput,

View File

@@ -13,7 +13,7 @@ type ScheduledGroup = {
time: string | null; 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( export function buildTodayCandidates(
groups: ScheduledGroup[], groups: ScheduledGroup[],
now: Date, now: Date,
@@ -37,7 +37,7 @@ export function buildTodayCandidates(
return candidates; 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( export async function ensureTodaySessions(
db: Pick<ClassesDb, 'classSession'>, db: Pick<ClassesDb, 'classSession'>,
candidates: TodaySessionCandidate[], candidates: TodaySessionCandidate[],

View File

@@ -24,9 +24,9 @@ type ListGroupsDeps = {
const OCCUPANCY_COUNT_INCLUDE = { const OCCUPANCY_COUNT_INCLUDE = {
_count: { _count: {
select: { 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, 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 } }, waitlist: { where: { status: 'PENDING' as const } },
}, },
}, },
@@ -43,10 +43,10 @@ export class ListGroups {
const now = this.deps.now ?? new Date(); const now = this.deps.now ?? new Date();
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput; const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
// Traemos los grupos del usuario con sus contadores y los ordenamos acá: // We fetch the user's groups with their counters and sort them here: the next
// la próxima clase se deriva de días + hora, no hay columna por la que // class is derived from days + time, there is no column to sort on in the
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la // database. It's the same engine the home summary uses, with the person's
// zona horaria de la persona (o la del servidor si no viaja). // time zone (or the server's if it doesn't come along).
const records: GroupListRecord[] = await db.group.findMany({ const records: GroupListRecord[] = await db.group.findMany({
where, where,
include: OCCUPANCY_COUNT_INCLUDE, include: OCCUPANCY_COUNT_INCLUDE,
@@ -58,9 +58,9 @@ export class ListGroups {
nextAt: nextOccurrenceAt(record, now, timeZone), nextAt: nextOccurrenceAt(record, now, timeZone),
})); }));
/* Un grupo sin horario no tiene clase que comparar, así que va al final; /* A group with no schedule has no class to compare, so it goes last;
entre grupos con la misma clase (o sin horario) desempata el más nuevo, between groups with the same class (or with no schedule) the newest one
que era el criterio anterior de la lista. */ breaks the tie, which was the listing's previous criterion. */
const ordered = withNextClass.sort((a, b) => { const ordered = withNextClass.sort((a, b) => {
if (a.nextAt !== null && b.nextAt !== null) { if (a.nextAt !== null && b.nextAt !== null) {
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime(); return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();

View File

@@ -21,10 +21,10 @@ export type GroupRecord = {
inviteToken?: string | null; inviteToken?: string | null;
}; };
/* El listado suma los contadores de ocupación a cada grupo para que la card los /* The listing adds the occupancy counters to each group so the card can show
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma them without asking for one endpoint per group. They come from the `_count` of
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de the same query: all the members (same as the detail page counts) and only the
espera solo los que siguen esperando cupo (PENDING). */ waitlist entries still waiting for a spot (PENDING). */
export type GroupListRecord = GroupRecord & { export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number }; _count?: { attendees: number; waitlist: number };
}; };

View File

@@ -2,7 +2,7 @@ import type { WeekDay } from '@gruperly/shared';
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City'; 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_HOURS = 2;
export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000; export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000;
@@ -21,7 +21,7 @@ export type NextClassOccurrence = {
isNow: boolean; 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 { export function zonedWallClockToUtc(wall: string, timeZone: string): Date {
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall); const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall);
if (!match) { if (!match) {
@@ -145,8 +145,8 @@ function pad(value: number): string {
return String(value).padStart(2, '0'); return String(value).padStart(2, '0');
} }
// Instante absoluto de la clase de HOY (aunque la hora ya haya pasado), o null si el grupo // Absolute instant of TODAY's class (even if the time has already passed), or null if the
// no tiene clase programada para el día de `now` en `timeZone`. // group has no class scheduled for `now`'s day in `timeZone`.
export function todayOccurrence(opt: { export function todayOccurrence(opt: {
days: WeekDay[]; days: WeekDay[];
time: string; time: string;
@@ -181,7 +181,7 @@ export function todayOccurrence(opt: {
return zonedWallClockToUtc(wall, timeZone); 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 { export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
const { year, month, day } = wallDateInTimeZone(now, timeZone); const { year, month, day } = wallDateInTimeZone(now, timeZone);
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone); return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);

View File

@@ -78,8 +78,8 @@ describe('GET /groups-risk/overview', () => {
const res = await makeApp({ id: userId }).request('/groups-risk/overview'); const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200); expect(res.status).toBe(200);
// `toMatchObject` porque el item ahora arrastra también el resumen por nivel // `toMatchObject` because the item now also carries the per-level summary
// que consume la tarjeta; acá se está probando el semáforo de siempre. // the card consumes; here we are testing the usual status light.
expect(await res.json()).toMatchObject({ expect(await res.json()).toMatchObject({
items: [ items: [
{ {
@@ -117,21 +117,21 @@ describe('GET /groups-risk/overview', () => {
{ id: 's6', groupId: 'group-2', startsAt: at(2) }, { id: 's6', groupId: 'group-2', startsAt: at(2) },
]); ]);
prismaFetchAttendanceFindMany([ 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', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)), attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'PRESENT', at(3)), 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', 's1', 'PRESENT', at(1)),
attendance('a-2', 's2', 'ABSENT', at(2)), attendance('a-2', 's2', 'ABSENT', at(2)),
attendance('a-2', 's3', 'ABSENT', at(3)), attendance('a-2', 's3', 'ABSENT', at(3)),
attendance('a-2', 's4', 'ABSENT', at(4)), attendance('a-2', 's4', 'ABSENT', at(4)),
// Al día. // Ok.
attendance('a-3', 's1', 'PRESENT', at(1)), attendance('a-3', 's1', 'PRESENT', at(1)),
attendance('a-3', 's2', 'PRESENT', at(2)), attendance('a-3', 's2', 'PRESENT', at(2)),
attendance('a-3', 's3', 'PRESENT', at(3)), attendance('a-3', 's3', 'PRESENT', at(3)),
attendance('a-3', 's4', 'PRESENT', at(4)), 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', 's5', 'ABSENT', at(1)),
attendance('b-1', 's6', 'ABSENT', at(2)), 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 /* What the listing card consumes. The status light above already had its
tests; lo que faltaba era fijar el payload nuevo contra el mismo endpoint, tests; what was missing was pinning the new payload against the same
porque es el contrato que el frontend lee. */ 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 () => { it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]); prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
prismaFetchAttendeeFindMany([ 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: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) }, { 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 // The mock ignores `orderBy`, so the rows come most recent first, as Prisma
// más antigua como las devolvería Prisma: de ese orden depende la racha. // would return them: the streak depends on that order.
// `at(n)` son n días hacia atrás; el resumen descarta lo que no ocurrió, así // `at(n)` is n days back; the summary drops what has not happened yet, so
// que las fechas tienen que estar en el pasado y no en el futuro. // the dates have to be in the past, not in the future.
prismaFetchAttendanceFindMany([ prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)), attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)), 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, riesgoAlto: 1,
atencion: 1, atencion: 1,
ok: 1, ok: 1,
// El cupo es de 5 y hay 3 miembros, no 2: los lugares libres se calculan // Capacity is 5 and there are 3 members, not 2: free spots are computed
// contra el cupo y no como "los que no tienen ninguna señal". // against capacity, not as "the ones with no signal at all".
libres: 2, libres: 2,
enEspera: 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, asistencia: 44,
}); });
expect(items[0].urgentes).toEqual([ 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', fullName: 'Diego Soto',
level: 'atencion', level: 'atencion',
consecutiveAbsences: 2, consecutiveAbsences: 2,
// Cuenta desde su última clase con presencia, no desde la más // Counted from their last class they attended, not from the group's
// reciente del grupo: la suya fue hace 3 días. // most recent one: theirs was 3 days ago.
daysSinceLastAttendance: 3, daysSinceLastAttendance: 3,
attendanceRate: 33, 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: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) }, { id: 's3', groupId: 'group-1', startsAt: at(3) },
]); ]);
// Falta, clase sin marcar, falta. Leyendo solo las filas de `Attendance` esto // Absence, unmarked class, absence. Reading only the `Attendance` rows this
// parecería una racha de 2 y el grupo saldría en atención; la clase del medio // would look like a streak of 2 and the group would land in attention; the
// pasó y no tiene registro, así que la racha real es de 1. // middle class happened and has no record, so the real streak is 1.
prismaFetchAttendanceFindMany([ prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)), attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's3', 'ABSENT', at(3)), 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', level: 'ok',
consecutiveAbsences: 1, consecutiveAbsences: 1,
daysSinceLastAttendance: 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, 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: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) }, { id: 's3', groupId: 'group-1', startsAt: at(3) },
]); ]);
// La racha se cuenta hacia atrás desde la clase más reciente, así que llegan // The streak is counted backwards from the most recent class, so they reach
// justo hasta el final: s1 y s2 pegadas, y la de hace 3 días sin registrar, // exactly the end: s1 and s2 back to back, and the one 3 days ago is
// que queda antes de la racha y no la toca. // unmarked, which falls before the streak and does not touch it.
prismaFetchAttendanceFindMany([ prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)), attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)), 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: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) }, { id: 's3', groupId: 'group-1', startsAt: at(3) },
]); ]);
// Mismas dos faltas pegadas del caso anterior, pero la clase más reciente // The same two back-to-back absences as the previous case, but the most
// (s1) es la que no tiene registro. Como la racha se cuenta desde el final y // recent class (s1) is the one with no record. Since the streak is counted
// "sin dato" no es ausencia, no hay racha: se ve la asimetría a propósito, // from the end and "no record" is not an absence, there is no streak: the
// porque es lo mismo que ya pasa con una clase justificada. // asymmetry is there on purpose, because it is the same thing that already
// happens with an excused class.
prismaFetchAttendanceFindMany([ prismaFetchAttendanceFindMany([
attendance('a-1', 's2', 'ABSENT', at(2)), attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)), 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 () => { it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]); 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) }]); prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
prismaFetchClassSessionFindMany([ prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) }, { 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); expect(items[0].absenceStreakCount).toBe(1);
}); });
/* El use-case pide `capacity` y el conteo de lista de espera para poder calcular /* The use-case asks for `capacity` and the waitlist count to compute the
los lugares libres, y `fullName` + `createdAt` de cada alumno para el resumen free spots, and `fullName` + `createdAt` of every attendee for the per-level
por nivel. Los fixtures los dan para que los tests viejos no tengan que summary. The fixtures provide them so the older tests don't have to know
saber de eso. */ about that. */
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) { function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
return { id, name, capacity, _count: { waitlist: waiting } }; return { id, name, capacity, _count: { waitlist: waiting } };
} }
@@ -416,9 +417,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
db.attendance.findMany.mockResolvedValue(rows); db.attendance.findMany.mockResolvedValue(rows);
} }
/* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo /* The `classSessionId` matters: the summary is built by cross-referencing the
con las filas de asistencia, y sin ese cruce toda clase quedaría sin registro group's class sessions with the attendance rows, and without that join every
para todo el mundo. */ class would have no record for everyone. */
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) { function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } }; return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
} }

View File

@@ -8,30 +8,29 @@ import {
summarizeMemberAttendance, summarizeMemberAttendance,
} from '@gruperly/shared'; } from '@gruperly/shared';
/* La regla de riesgo es de negocio, no de pantalla: estos tests la fijan para /* The risk rule is business logic, not a screen concern: these tests pin it so
que cambiar un umbral o refactorizar el filtro de clases no mueva el that changing a threshold or refactoring the class filter doesn't quietly
semáforo de la lista de grupos en silencio. 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 - `dense` puts the classes on consecutive days, so that "how long since we
vemos" quede siempre cerca y el caso aísle la regla que dice probar (una saw them" is always close by and the case isolates the rule it claims to
clase por semana haría saltar el umbral de inactividad en casi todo). test (one class a week would trip the inactivity threshold almost always).
- `series` respeta los offsets que se le pasan, para los casos que sí - `series` honors the offsets it is given, for the cases that do need gaps.
necesitan huecos.
Todas las fechas se cuelgan de un `NOW` fijo: la función recibe el momento All dates hang off a fixed `NOW`: the function takes the moment as an
como argumento justamente para poder testear sin reloj. */ argument precisely so it can be tested without a clock. */
const DAY_MS = 24 * 60 * 60 * 1000; const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = new Date('2026-09-30T20:00:00.000Z'); 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(); const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
type Status = MemberClassSession['status']; 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[] { function dense(statuses: Status[]): MemberClassSession[] {
return statuses.map((status, index) => ({ return statuses.map((status, index) => ({
sessionId: `ses_${statuses.length - 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[] { function series(rows: [Status, number][]): MemberClassSession[] {
return rows.map(([status, offsetDays], index) => ({ return rows.map(([status, offsetDays], index) => ({
sessionId: `ses_${index}`, sessionId: `ses_${index}`,
@@ -69,7 +68,7 @@ describe('getMemberAttendanceRisk', () => {
}); });
it('no cuenta clases que todavía no ocurrieron', () => { 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]])); const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]]));
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok'); expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
}); });
@@ -78,14 +77,15 @@ describe('getMemberAttendanceRisk', () => {
const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'])); const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']));
const señales = summarizeMemberAttendance(alumno, NOW); const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(3); 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.daysSinceLastAttendance).toBe(4);
expect(señales.level).toBe('riesgo_alto'); expect(señales.level).toBe('riesgo_alto');
}); });
it('una racha larguísima sin ninguna clase con presencia igual es 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 // Never attended an eligible class: the reference for "how long since we saw
// vemos" es la última clase, así que no queda en verde para siempre. // them" is the last class, so it doesn't stay green forever.
const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT'])); const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT']));
const señales = summarizeMemberAttendance(alumno, NOW); const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(5); 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', () => { 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 // A single absence, the most recent one: the streak doesn't reach. What drives
// el tiempo sin aparecer. // the level is the time since they last showed up.
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]])); const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
const señales = summarizeMemberAttendance(alumno, NOW); const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(1); 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', () => { it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
const { highInactivityDays } = ATTENDANCE_RISK_RULES; const { highInactivityDays } = ATTENDANCE_RISK_RULES;
// Dos faltas de racha: la atención le llega por la racha, y los 10 días // Two streak absences: attention comes from the streak, and exactly 10 days
// justos no mueven el nivel. // does not move the level.
expect( expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW), getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
).toBe('atencion'); ).toBe('atencion');
@@ -121,9 +121,9 @@ describe('getMemberAttendanceRisk', () => {
}); });
it('una tendencia a la baja da atención', () => { 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 // 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
// más reciente es un PRESENT: racha 0 y asistencia reciente, así que la // most recent is a PRESENT: streak 0 and recent attendance, so the trend is
// tendencia es lo único que puede disparar la alerta. // the only thing that can raise the alert.
const candidato = member(dense([ const candidato = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
@@ -135,8 +135,8 @@ describe('getMemberAttendanceRisk', () => {
}); });
it('perder una sola clase no es tendencia', () => { it('perder una sola clase no es tendencia', () => {
// Mismo caso que el anterior con una clase menos perdida en la ventana // Same case as the previous one with one class fewer missed in the recent
// reciente: 3 de 4 contra 4 de 4. Es ruido, no una caída. // window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
const estable = member(dense([ const estable = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
@@ -145,16 +145,16 @@ describe('getMemberAttendanceRisk', () => {
}); });
it('la tendencia necesita historia para las dos ventanas', () => { it('la tendencia necesita historia para las dos ventanas', () => {
// 5 clases con dato: la ventana anterior quedaría con una sola, así que no // 5 marked classes: the previous window would be left with a single one, so
// hay contra qué comparar. // there is nothing to compare against.
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])); const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok'); expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
}); });
it('la racha manda sobre la tendencia', () => { it('la racha manda sobre la tendencia', () => {
// 16 clases: 4 anteriores al 100%, y las 4 últimas con 3 faltas seguidas // 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
// una clase con presencia. La tendencia sola daría atención; las 3 faltas // absences and one attended class. The trend alone would give attention;
// seguidas de punta dan riesgo alto, que es lo que tiene que ganar. // the 3 trailing absences give high risk, which is what has to win.
const alumno = member(dense([ const alumno = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT', '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', () => { 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 // Absent, the middle one has no record, absent again. The real streak
// es de una, no de dos. // is one, not two.
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]])); const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(conHueco, NOW); const señales = summarizeMemberAttendance(conHueco, NOW);
expect(señales.consecutiveAbsences).toBe(1); expect(señales.consecutiveAbsences).toBe(1);
@@ -177,8 +177,8 @@ describe('getMemberAttendanceRisk', () => {
}); });
it('una clase justificada es la clase que no cuenta', () => { 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 // Absent, notified, absent again: the streak is one, and the average ignores
// clase justificada en vez de contarla como asistencia o como falta. // the excused class instead of counting it as attendance or as an absence.
const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]])); const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(justificada, NOW); const señales = summarizeMemberAttendance(justificada, NOW);
expect(señales.consecutiveAbsences).toBe(1); expect(señales.consecutiveAbsences).toBe(1);
@@ -293,7 +293,7 @@ describe('getGroupAttendanceSummary', () => {
members: [ members: [
conNivel('a', 'ok'), conNivel('a', 'ok'),
{ attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) }, { 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: [] }, { attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
], ],
now: NOW, now: NOW,

View File

@@ -412,7 +412,7 @@ describe('attendee incorporation & invite-token in groups', () => {
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => { describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
it('imports multiple attendees, skipping duplicates and reporting counts', async () => { it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); 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([ prisma.attendee.findMany.mockResolvedValue([
{ phone: '11111111' }, { phone: '11111111' },
] as never); ] as never);
@@ -434,8 +434,8 @@ describe('attendee incorporation & invite-token in groups', () => {
attendees: [ attendees: [
{ firstName: 'Ana', lastName: 'García', phone: '22222222' }, { firstName: 'Ana', lastName: 'García', phone: '22222222' },
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' }, { firstName: 'Pedro', lastName: 'López', phone: '33333333' },
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Ya existe en BD { firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicado dentro del lote { firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
], ],
}), }),
}); });
@@ -484,8 +484,8 @@ describe('attendee incorporation & invite-token in groups', () => {
skip: 0, skip: 0,
take: 10, take: 10,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
// El resumen de la fila se pide en la misma consulta: una petición por // The row summary is requested in the same query: one request per
// miembro sería N+1 sobre un listado de hasta 100. // member would be N+1 over a listing of up to 100.
include: { include: {
attendances: { attendances: {
orderBy: { classSession: { startsAt: 'desc' } }, orderBy: { classSession: { startsAt: 'desc' } },

View File

@@ -2,8 +2,8 @@ import { describe, expect, it } from 'bun:test';
import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers'; import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers';
import { toAttendeeListItemDto } 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 /* The row summary is built in memory: which class counts as recent and
qué cobro se muestra. Son las dos decisiones que la fila leen. */ which payment is shown. Those are the two decisions the row reads. */
function record( function record(
overrides: Partial<AttendeeListItemRecord> = {}, overrides: Partial<AttendeeListItemRecord> = {},
@@ -32,7 +32,7 @@ describe('toAttendeeListItemDto', () => {
it('invierte la asistencia para que la clase más reciente quede a la derecha', () => { it('invierte la asistencia para que la clase más reciente quede a la derecha', () => {
const dto = toAttendeeListItemDto( const dto = toAttendeeListItemDto(
record({ record({
// Llega de más reciente a más antigua. // It arrives from most recent to oldest.
attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }], attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }],
}), }),
); );

View File

@@ -33,7 +33,7 @@ const attendeeRow = {
updatedAt: new Date('2026-08-01T10:00:00.000Z'), 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 = { const attendee = {
...attendeeRow, ...attendeeRow,
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }], attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
@@ -58,8 +58,8 @@ describe('attendees routes', () => {
...attendeeRow, ...attendeeRow,
createdAt: attendeeRow.createdAt.toISOString(), createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(),
// La consulta viene de más reciente a más antigua; la fila los // The query comes most recent first; the row shows them
// muestra al revés, con la clase más reciente a la derecha. // the other way around, with the most recent class on the right.
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'], recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' }, payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
}, },

View File

@@ -77,7 +77,7 @@ function makeSession(overrides: Record<string, unknown> = {}) {
}; };
} }
// Fecha "hoy" a las 19:00 UTC, del día real del runner. // "Today" at 19:00 UTC, on the runner's real day.
function todayAtUtc() { function todayAtUtc() {
const date = new Date(); const date = new Date();
date.setUTCHours(19, 0, 0, 0); date.setUTCHours(19, 0, 0, 0);

View File

@@ -84,8 +84,8 @@ describe('groups routes', () => {
const where = { const where = {
OR: [{ createdById: userId }, { members: { some: { userId } } }], OR: [{ createdById: userId }, { members: { some: { userId } } }],
}; };
// Los contadores de ocupación viajan en la misma consulta; la lista de // The occupancy counters ride along in the same query; the waitlist
// espera cuenta solo los PENDING, los que siguen esperando cupo. // counts only PENDING, the ones still waiting for a spot.
expect(prisma.group.findMany).toHaveBeenCalledWith({ expect(prisma.group.findMany).toHaveBeenCalledWith({
where, where,
include: { 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 // Monday 2026-01-05 at noon in Mexico City: the 18:00 class
// todavía no empieza, así que ese grupo va primero. // hasn't started yet, so that group goes first.
const result = await new ListGroups({ const result = await new ListGroups({
db, db,
now: new Date('2026-01-05T18:00:00.000Z'), now: new Date('2026-01-05T18:00:00.000Z'),
@@ -140,7 +140,7 @@ describe('groups routes', () => {
expect(result.ok).toBe(true); expect(result.ok).toBe(true);
if (!result.ok) return; 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([ expect(result.value.data.map((item) => item.id)).toEqual([
'hoy-tarde', 'hoy-tarde',
'hoy-tarde-viejo', 'hoy-tarde-viejo',
@@ -157,8 +157,8 @@ describe('groups routes', () => {
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' }, { ...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 // Monday at noon: A's 10:00 class already happened, so its
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero. // next occurrence is next Monday and B (Wednesday) goes first.
const result = await new ListGroups({ const result = await new ListGroups({
db, db,
now: new Date('2026-01-05T18:00:00.000Z'), now: new Date('2026-01-05T18:00:00.000Z'),

View File

@@ -5,7 +5,7 @@ const TZ = 'America/Mexico_City';
describe('nextClassOccurrence', () => { describe('nextClassOccurrence', () => {
it('devuelve la próxima clase de hoy cuando aún no arrancó', () => { 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({ const result = nextClassOccurrence({
days: ['WEDNESDAY'], days: ['WEDNESDAY'],
@@ -21,7 +21,7 @@ describe('nextClassOccurrence', () => {
}); });
it('marca en curso si la clase arrancó hace menos de la ventana', () => { 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({ const result = nextClassOccurrence({
days: ['WEDNESDAY'], days: ['WEDNESDAY'],
@@ -37,7 +37,7 @@ describe('nextClassOccurrence', () => {
}); });
it('salta a la próxima semana si la clase ya pasó la ventana', () => { 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({ const result = nextClassOccurrence({
days: ['WEDNESDAY'], days: ['WEDNESDAY'],
@@ -53,7 +53,7 @@ describe('nextClassOccurrence', () => {
}); });
it('elige la ocurrencia más próxima entre varios días', () => { 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({ const result = nextClassOccurrence({
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
@@ -69,7 +69,7 @@ describe('nextClassOccurrence', () => {
}); });
it('cruza de mes sin problema', () => { 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({ const result = nextClassOccurrence({
days: ['THURSDAY'], days: ['THURSDAY'],

View File

@@ -193,7 +193,7 @@ describe('GetHomeSummary', () => {
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' }, { ...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 useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' }); const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' });
@@ -212,7 +212,7 @@ describe('GetHomeSummary', () => {
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' }, { ...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 useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
const result = await useCase.execute(userId); const result = await useCase.execute(userId);

View File

@@ -41,7 +41,7 @@ describe('session auth', () => {
it('classifies absence notification endpoints as public (token-based)', () => { it('classifies absence notification endpoints as public (token-based)', () => {
expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true); expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).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/today')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false); expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false); expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false);

View File

@@ -2,14 +2,14 @@
<html lang="es"> <html lang="es">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<!-- viewport-fit=cover habilita env(safe-area-inset-*) en iOS standalone. --> <!-- viewport-fit=cover enables env(safe-area-inset-*) in iOS standalone. -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<title>Gruperly</title> <title>Gruperly</title>
<meta name="description" content="Gestión de cobros grupales" /> <meta name="description" content="Gestión de cobros grupales" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" />
<!-- iOS standalone: sin esto la app abre en un pestaña de Safari. --> <!-- iOS standalone: without this the app opens in a Safari tab. -->
<meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" /> <meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="Gruperly" /> <meta name="apple-mobile-web-app-title" content="Gruperly" />

View File

@@ -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 * The outputs are versioned in `public/`; the Vite build does not regenerate
* (sharp es una devDependency y no debe entrar en la imagen de Docker). * them (sharp is a devDependency and must not end up in the Docker image).
* Re-correr solo cuando cambia `src/assets/brand/isotipo-y-organica.svg`. * Re-run only when `src/assets/brand/isotipo-y-organica.svg` changes.
*/ */
import { mkdir, readFile, writeFile } from 'node:fs/promises' import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path' 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 source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg')
const publicDir = join(webDir, 'public') 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 BACKGROUND = '#ffffff'
const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const
type IconTarget = { type IconTarget = {
file: string file: string
size: number size: number
/** Rellena el lienzo con `BACKGROUND` en vez de dejar transparencia. */ /** Fills the canvas with `BACKGROUND` instead of leaving it transparent. */
opaque: boolean 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 contentRatio: number
} }
const targets: IconTarget[] = [ const targets: IconTarget[] = [
{ file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 }, { file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 },
{ file: 'pwa-512x512.png', size: 512, 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 // Android crops adaptive icons in a circle: the useful content lives in the
// vive en el 80% central del canvas, así que el logo va over white y escalado. // 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: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 },
{ file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 }, { 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: // The isotype viewBox does not start at 0 and leaves air around the glyph:
// `trim` recorta ese margen para que el encuadre use el área real del dibujo. // `trim` crops that margin so the framing uses the drawing's real area.
const logo = await sharp(await readFile(source), { density: 512 }) const logo = await sharp(await readFile(source), { density: 512 })
.trim({ threshold: 1 }) .trim({ threshold: 1 })
.png() .png()

View File

@@ -20,8 +20,8 @@ export function BottomNav() {
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary', isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
)} )}
> >
{/* Pastilla suave detrás del ícono: el estado activo se lee por {/* Soft pill behind the icon: the active state is read by
color + fondo, no solo por el tono del texto. */} color + background, not only by the text tone. */}
<span <span
className={cn( className={cn(
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150', 'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',

View File

@@ -9,9 +9,9 @@ export function Header() {
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur"> <header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6"> <div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
<div className="flex min-w-0 items-center"> <div className="flex min-w-0 items-center">
{/* `Link` y no `<a>`: en mobile el logo es la única forma de volver al {/* `Link` and not `<a>`: on mobile the logo is the only way back to the
inicio y un anchor recargaría el documento entero, perdiendo el home screen and an anchor would reload the whole document, losing
estado en memoria (cache de React Query, evento de instalación). */} the in-memory state (React Query cache, install event). */}
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio"> <Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
<Logo className="h-8" /> <Logo className="h-8" />
</Link> </Link>

View File

@@ -4,32 +4,33 @@ import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse' import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse'
type LargeTitleProps = { type LargeTitleProps = {
/** Texto del título. Es el mismo en el grande y en el de la barra: el `h1` /** Title text. It's the same in the large title and in the bar's copy: the
* real es el grande, el de la barra es un duplicado visual. */ * real `h1` is the large one, the bar's is a visual duplicate. */
title: string title: string
/** Acción a la izquierda de la barra. En desktop es el link "volver" que /** Action to the left of the bar. On desktop it's the "Volver" link that
* antes vivía en el cuerpo de la pantalla; en mobile se oculta. */ * used to live in the screen body; on mobile it's hidden. */
leading?: ReactNode leading?: ReactNode
/** Contexto que no puede desaparecer al scrollear (ej. el contador de /** Context that can't disappear on scroll (e.g. the present counter). It
* presentes). Viaja a la barra y se funde con el título. */ * travels to the bar and blends with the title. */
barTrailing?: ReactNode 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 children?: ReactNode
} }
/** /**
* Encabezado de pantalla con Large Title (patrón de iOS): el título arranca * Screen header with Large Title (the iOS pattern): the title starts large and
* grande y al scrollear se desliza debajo de la barra, que se opaca y recibe * slides under the bar as you scroll, while the bar goes opaque and takes the
* el título en versión chica. * title in its small version.
* *
* El título grande es un bloque normal en el flujo; la barra vive en una caja * The large title is a normal block in the flow; the bar lives in a sticky box
* sticky que el layout monta arriba de `<main>` (ver `ImmersiveBarHost`), así * that the layout mounts above `<main>` (see `ImmersiveBarHost`), so the content
* el contenido se desliza por debajo sin márgenes negativos ni `fixed` que * slides under it without negative margins or a `fixed` we'd have to compensate
* haya que compensar en desktop. * for on desktop.
* *
* El estado del scroll vive acá adentro a propósito: `children` llega como prop * The scroll state lives in here on purpose: `children` arrives as an already
* ya construido, así React reutiliza los elementos y el subtree de abajo no se * built prop, so React reuses the elements and the subtree below doesn't
* re-renderiza en cada frame de scroll. * re-render on every scroll frame.
*/ */
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) { export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
const { titleRef, progress } = useLargeTitleCollapse() const { titleRef, progress } = useLargeTitleCollapse()
@@ -40,9 +41,9 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle
{barHost {barHost
? createPortal( ? createPortal(
<div className="relative flex h-full items-center gap-3 px-4 lg:px-0"> <div className="relative flex h-full items-center gap-3 px-4 lg:px-0">
{/* El fondo va en una capa propia: se opaca con el scroll mientras {/* The background goes on its own layer: it goes opaque with the
el título entra, y `leading` (el link "volver") no puede scroll while the title slides in, and `leading` (the "Volver"
fundirse con él porque existe siempre. */} link) can't blend with it because it always exists. */}
<div <div
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md" className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
style={{ opacity: progress }} style={{ opacity: progress }}

View File

@@ -12,18 +12,18 @@ export function RootLayout({ children }: { children: ReactNode }) {
return ( return (
<div className="min-h-dvh w-full overflow-x-clip"> <div className="min-h-dvh w-full overflow-x-clip">
{/* En las rutas immersive la pantalla trae su propia barra (LargeTitle), {/* On immersive routes the screen brings its own bar (LargeTitle) with
con el logo y el nombre del grupo: el header global con logo + tema + the logo and the group name: the global header with logo + theme +
avatar sería una segunda barra compitiendo por los mismos píxeles. */} avatar would be a second bar competing for the same pixels. */}
{immersive ? null : <Header />} {immersive ? null : <Header />}
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6"> <div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
<Sidebar immersive={immersive} /> <Sidebar immersive={immersive} />
<ImmersiveBarProvider> <ImmersiveBarProvider>
{/* pt-0 en immersive: el padding superior lo aporta la caja de la {/* pt-0 on immersive: the bar's box provides the top padding,
barra, y si no el título grande arrancaría 16px más abajo de la otherwise the large title would start 16px below the bottom of the
base de la barra y el colapso se mediría corrido. */} bar and the collapse would be measured off. */}
<main <main
className={cn( className={cn(
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8', 'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',

View File

@@ -7,17 +7,17 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
const location = useLocation() const location = useLocation()
return ( return (
// Sin header global no hay nada que esquive arriba: la columna del sidebar // Without the global header there's nothing to clear above: the sidebar
// pasa a ocupar la ventana completa y queda a la altura de la barra de // column takes over the whole window and lines up with the height of the
// LargeTitle. // LargeTitle bar.
<aside <aside
className={cn( className={cn(
'sticky hidden w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex', 'sticky hidden w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex',
immersive ? 'top-0 h-dvh' : 'top-16 h-[calc(100dvh-4rem)]', immersive ? 'top-0 h-dvh' : 'top-16 h-[calc(100dvh-4rem)]',
)} )}
> >
{/* `Link` y no `<a>`: un anchor recargaría el documento y perdería el {/* `Link` and not `<a>`: an anchor would reload the document and lose the
estado en memoria (cache de React Query, evento de instalación). */} in-memory state (React Query cache, install event). */}
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio"> <Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
<Logo className="h-10" /> <Logo className="h-10" />
</Link> </Link>

View File

@@ -13,10 +13,10 @@ export const NAV_ITEMS: NavItem[] = [
{ label: 'Ajustes', to: '/settings', icon: Settings }, { label: 'Ajustes', to: '/settings', icon: Settings },
] ]
/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem /** A section stays active within its subroutes: on `/groups/abc` the active
* activo es "Grupos", no ninguno. El prefijo se corta en el separador para * item is "Grupos", not none. The prefix is cut at the separator so
* que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay * `/groupsomething` isn't taken for "/groups". The root is exact: the home has
* subrutas del home que deban marcarla. */ * no subroutes that should mark it. */
export function isNavItemActive(pathname: string, to: string): boolean { export function isNavItemActive(pathname: string, to: string): boolean {
if (to === '/') return pathname === '/' if (to === '/') return pathname === '/'
return pathname === to || pathname.startsWith(`${to}/`) return pathname === to || pathname.startsWith(`${to}/`)

View File

@@ -12,10 +12,10 @@ const variants: Record<BadgeVariant, string> = {
warning: 'bg-warning-soft text-warning', warning: 'bg-warning-soft text-warning',
danger: 'bg-danger-soft text-danger', danger: 'bg-danger-soft text-danger',
neutral: 'bg-primary-soft text-primary', neutral: 'bg-primary-soft text-primary',
/* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la /* Informational state, not an alert: waitlist, free spots. Uses the legible
tinta de acento legible (`accent-fg` es el azul claro en tema oscuro, accent ink (`accent-fg` is the light blue in the dark theme, 7.1:1 on the
7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1 card) and not the plain `accent`, which in dark scores 2.2:1 and misses the
y no alcanza el mínimo de 3:1 para contenido no textual. */ 3:1 minimum for non-text content. */
info: 'bg-accent-soft text-accent-fg', info: 'bg-accent-soft text-accent-fg',
} }

View File

@@ -28,9 +28,9 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
ref={ref} ref={ref}
type={type} type={type}
className={cn( className={cn(
// `transition-*` explícito en vez de `transition-all`: solo se animan // Explicit `transition-*` instead of `transition-all`: only color,
// color, fondo, borde y transform. El feedback de presión se anula // background, border and transform are animated. Press feedback is
// con `motion-reduce` para respetar prefers-reduced-motion. // 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', '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], variants[variant],
sizes[size], sizes[size],

View File

@@ -11,8 +11,8 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
<input <input
ref={ref} ref={ref}
className={cn( className={cn(
// text-base (16px) en mobile: iOS auto-zoomea al enfocar controles con // text-base (16px) on mobile: iOS auto-zooms when focusing controls
// font-size < 16px y, al cerrar el teclado, no restaura el scale. // with font-size < 16px and doesn't restore the scale on keyboard close.
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50', 'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
invalid && 'border-danger focus:border-danger focus:ring-danger/30', invalid && 'border-danger focus:border-danger focus:ring-danger/30',
className, className,

View File

@@ -2,19 +2,20 @@ import { type ReactNode, useId, useState } from 'react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
export type TooltipProps = { export type TooltipProps = {
/** Texto explicativo que se muestra al hacer hover, foco de teclado o tap. */ /** Explanatory text shown on hover, keyboard focus or tap. */
content: ReactNode content: ReactNode
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */ /** Trigger content. It sits inside a <button> to stay accessible. */
children: ReactNode children: ReactNode
className?: string className?: string
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en sm+). */ /** Alternate positioning for the bubble (default: below, anchored right on sm+). */
tooltipClassName?: string tooltipClassName?: string
} }
/** /**
* Tooltip accesible sin dependencias: hover (ratón), foco (teclado) y tap * Accessible tooltip with no dependencies: hover (mouse), focus (keyboard) and
* (táctil, vía focus). Se cierra con Escape, al salir el puntero o al perder * tap (touch, via focus). It closes on Escape, when the pointer leaves or when
* el foco. El globo se ancla abajo del disparador para no tapar el contenido. * it loses focus. The bubble is anchored below the trigger so it doesn't cover
* the content.
*/ */
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) { export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
@@ -28,8 +29,8 @@ export function Tooltip({ content, children, className, tooltipClassName }: Tool
<button <button
type="button" type="button"
aria-describedby={open ? id : undefined} aria-describedby={open ? id : undefined}
// El hover solo aplica a punteros de ratón: en táctil no hay "hover // Hover only applies to mouse pointers: on touch there is no
// persistente" y el tap se resuelve con focus + click. // "persistent hover" and tap is handled with focus + click.
onPointerEnter={(e) => { onPointerEnter={(e) => {
if (e.pointerType === 'mouse') show() if (e.pointerType === 'mouse') show()
}} }}

View File

@@ -1,14 +1,14 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react' import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'
/* Las pantallas "immersive" (ficha de grupo y asistencia) arman su propia barra /* "Immersive" screens (group detail and attendance) build their own title bar
de título en vez de usar el header global, pero la barra tiene que ser hija instead of using the global header, but the bar has to be a direct child of
directa de `<main>`: un `sticky` solo se pega mientras su caja padre esté en `<main>`: a `sticky` only sticks while its parent box is on screen, and the
pantalla, y el padre natural de la barra (el bloque del feature) es corto, así bar's natural parent (the feature block) is short, so it would detach at
que se despegaría a los ~200px de scroll. around ~200px of scroll.
Este provider expone una caja fija de 56px clavada arriba de `<main>` donde la This provider exposes a fixed 56px box pinned to the top of `<main>` where
pantalla monta su barra. La caja la dibuja el layout (para que ocupe su lugar the screen mounts its bar. The layout draws the box (so it holds its place
desde el primer render) y su contenido lo aporta la pantalla. */ from the first render) and the screen supplies its content. */
type ImmersiveBarValue = { type ImmersiveBarValue = {
host: HTMLElement | null host: HTMLElement | null
@@ -29,14 +29,14 @@ export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
) )
} }
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */ /** The bar's box: first child of `<main>`, on immersive routes. */
export function ImmersiveBarHost() { export function ImmersiveBarHost() {
const { hostRef } = useContext(ImmersiveBarContext) const { hostRef } = useContext(ImmersiveBarContext)
return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" /> return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" />
} }
/** Destino del portal de `LargeTitle`; `null` si la pantalla no es immersive. */ /** Portal target for `LargeTitle`; `null` if the screen is not immersive. */
export function useImmersiveBarHost() { export function useImmersiveBarHost() {
return useContext(ImmersiveBarContext).host return useContext(ImmersiveBarContext).host
} }

View File

@@ -18,7 +18,7 @@ type ThemeContextValue = {
const STORAGE_KEY = 'theme' const STORAGE_KEY = 'theme'
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */ /** Status bar colors in standalone mode. Must match index.css. */
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
const THEME_COLOR_META_ID = 'theme-color' const THEME_COLOR_META_ID = 'theme-color'
@@ -50,8 +50,8 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
setIsDark(dark) setIsDark(dark)
localStorage.setItem(STORAGE_KEY, theme) localStorage.setItem(STORAGE_KEY, theme)
// En standalone la barra de estado se pinta con theme-color; sin esto // In standalone the status bar is painted with theme-color; without this
// queda congelada en el valor que puso el script inline de index.html. // it stays frozen at the value the inline script in index.html set.
document document
.getElementById(THEME_COLOR_META_ID) .getElementById(THEME_COLOR_META_ID)
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light) ?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)

View File

@@ -28,16 +28,16 @@ export function AbsenceLinkSection() {
title="Link de ausencias" title="Link de ausencias"
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }} toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
> >
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y {/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
el texto de "Link copiado" no se pierde al plegar y desplegar. */} the "Link copied" text is not lost on collapse/expand. */}
<div id={panelId} hidden={!isOpen}> <div id={panelId} hidden={!isOpen}>
<p className="px-3 text-sm text-foreground"> <p className="px-3 text-sm text-foreground">
Mandales este link para que avisen cuando no puedan venir. Mandales este link para que avisen cuando no puedan venir.
</p> </p>
{/* Apiladas y a ancho completo: al 50% los rótulos ("Enviar por WhatsApp") {/* Stacked and full width: at 50% the labels ("Enviar por WhatsApp")
se partían en dos líneas y quedaban por debajo del mínimo táctil. wrapped onto two lines and fell below the minimum touch target.
Copiar queda arriba, pegado a su confirmación, y la acción principal Copy stays on top, glued to its confirmation, and the primary action
se distingue por el relleno de acento. */} is told apart by the accent fill. */}
<div className="mt-2.5 flex flex-col gap-2"> <div className="mt-2.5 flex flex-col gap-2">
<button <button
type="button" type="button"

View File

@@ -6,21 +6,21 @@ import { useAttendeeDetail } from './AttendeeDetailProvider'
const ITEM_CLASS = const ITEM_CLASS =
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent' 'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Menú "⋯" de la ficha del miembro. /** "⋯" menu on the attendee detail page.
* *
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de * For now it only holds "Quitar del grupo": the backend has no way to
* regenerar el token de ausencias, así que la opción no se muestra antes que * regenerate the absence token, so the option is not shown before that
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo * endpoint exists (see `apps/backend/prisma/models/domain.prisma`, field
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la * `notifyToken`). Once it does, it is one more `<button role="menuitem">` in
* lista de abajo. * the list below.
* *
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo * The label goes in `text-primary` and the icon carries the `text-danger`: the
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */ * `danger` red on white sits at 3.7:1 and does not reach AA for normal text. */
export function AttendeeActionsMenu({ export function AttendeeActionsMenu({
triggerRef, triggerRef,
}: { }: {
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el /** The screen passes it in so the confirmation dialog can give focus back
* foco cuando se cierra. */ * when it closes. */
triggerRef: RefObject<HTMLButtonElement | null> triggerRef: RefObject<HTMLButtonElement | null>
}) { }) {
const { openRemoveDialog } = useAttendeeDetail() const { openRemoveDialog } = useAttendeeDetail()

View File

@@ -96,8 +96,8 @@ export function AttendeeAttendanceSection() {
})} })}
</ul> </ul>
{/* Las clases sin registro no son ausencias: se avisa aparte y en voz baja {/* Classes with no record are not absences: they are reported separately
para que el "1 de 1" de arriba no se lea como un fallo. */} and quietly so the "1 de 1" above does not read as a failure. */}
{summary.unmarkedLabel ? ( {summary.unmarkedLabel ? (
<p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p> <p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
) : null} ) : null}

View File

@@ -10,15 +10,15 @@ export function AttendeeContactActions() {
const phone = attendee?.phone const phone = attendee?.phone
if (!phone) return null if (!phone) return null
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos. // The links use the raw digits: wa.me and tel: do not understand formats.
const digits = phone.replace(/\D/g, '') const digits = phone.replace(/\D/g, '')
const label = formatPhoneDisplay(phone) ?? phone const label = formatPhoneDisplay(phone) ?? phone
return ( return (
<div className="flex gap-2.5"> <div className="flex gap-2.5">
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es {/* The icons go with `accent-fg` and not with `accent`: the `accent` blue is
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1. the same in both themes and on dark `primary-soft` it sits at 2.2:1.
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */} `accent-fg` gives 6.2:1 in light and 7.1:1 in dark. */}
<a <a
href={`https://wa.me/${digits}`} href={`https://wa.me/${digits}`}
target="_blank" target="_blank"

View File

@@ -2,19 +2,20 @@ import { Mail } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section' import { Section } from './Section'
/* `px-3` interno: la banda de hover sigue a sangre hasta el borde de la sección /* Inner `px-3`: the hover band bleeds all the way to the section edge
(la separa del texto, no al revés) y las notas de abajo suman el mismo para (it separates from the text, not the other way around) and the notes below
que el email y ellas caigan en la misma columna. */ add the same so the email and they land in the same column. */
const ROW_CLASS = const ROW_CLASS =
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent' 'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Email y notas del miembro. El teléfono no va acá: ya está en el subtítulo y /** The attendee's email and notes. The phone does not go here: it is already in
* detrás de los botones de WhatsApp y Llamar, y repetirlo llenaba la pantalla * the subtitle, behind the WhatsApp and Llamar buttons, and repeating it filled
* de un dato que ya estaba a la vista. * the screen with a value that was already in view.
* *
* Sin datos no se dibuja la sección: no hay filas con "Sin email"/"Sin notas". * With no data the section is not drawn: there are no "Sin email"/"Sin notas"
* Aparece sola en cuanto el miembro tenga alguno (hoy el email puede llegar al * rows. It shows up on its own as soon as the attendee has one of them (today
* aprobar una preinscripción; las notas, cuando exista la edición). */ * the email can arrive when approving a pre-registration; the notes, once
* editing exists). */
export function AttendeeContactSection() { export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail() const { attendee } = useAttendeeDetail()

View File

@@ -51,16 +51,16 @@ export function AttendeeDetailProvider({
enabled: Boolean(groupId && attendeeId), enabled: Boolean(groupId && attendeeId),
}) })
// Misma clave que usa la pantalla de estadísticas: las dos leen el mismo // Same key the analytics screen uses: both read the same history and do not
// historial y no se pisan la caché. // clobber each other's cache.
const historyQuery = useQuery({ const historyQuery = useQuery({
queryKey: ['attendee-history', groupId, attendeeId], queryKey: ['attendee-history', groupId, attendeeId],
queryFn: () => getAttendeeHistory(groupId, attendeeId), queryFn: () => getAttendeeHistory(groupId, attendeeId),
enabled: Boolean(groupId && attendeeId), enabled: Boolean(groupId && attendeeId),
}) })
// La lista de espera solo hace falta para el diálogo de quitar, así que no se // The waitlist is only needed for the remove dialog, so it is not fetched
// pide hasta que el usuario lo abre. // until the user opens it.
const waitlistQuery = useQuery({ const waitlistQuery = useQuery({
queryKey: ['group-waitlist', groupId], queryKey: ['group-waitlist', groupId],
queryFn: () => getGroupWaitlist(groupId, 1, 100), queryFn: () => getGroupWaitlist(groupId, 1, 100),

View File

@@ -28,9 +28,9 @@ export function AttendeeDetailView() {
if (attendeeFailed || !attendee) { if (attendeeFailed || !attendee) {
return ( return (
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6"> <div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a {/* The title carries the red (at 18px it already counts as large text and
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no reaches 3:1) and the body uses `text-primary`: on `danger-soft` the red
pasa los 4.5:1 que necesita un `text-sm`. */} does not pass the 4.5:1 a `text-sm` needs. */}
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1> <h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
<p className="mt-2 text-sm text-primary"> <p className="mt-2 text-sm text-primary">
No se pudo cargar la información de este miembro. No se pudo cargar la información de este miembro.
@@ -75,9 +75,9 @@ export function AttendeeDetailView() {
<AttendeeContactActions /> <AttendeeContactActions />
</div> </div>
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más {/* Ordered by how often they are used. Adding Pagos means inserting one
arriba de Asistencia; cada sección lleva su propio aire, así que el more block above Asistencia; each section brings its own spacing, so
layout no se toca. */} the layout does not need to change. */}
<div className="mt-5"> <div className="mt-5">
<AttendeeAttendanceSection /> <AttendeeAttendanceSection />
<AttendeeContactSection /> <AttendeeContactSection />

View File

@@ -3,12 +3,12 @@ import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useCopyToClipboard } from './useCopyToClipboard' import { useCopyToClipboard } from './useCopyToClipboard'
/** Teléfono como segunda línea del subtítulo. /** The phone as the subtitle's second line.
* *
* Vivía en una sección "Contacto" con una sola fila que repetía el número que * It used to live in a "Contacto" section with a single row that repeated the
* ya está a la vista detrás de los botones de WhatsApp y Llamar. Acá acompaña * number already visible behind the WhatsApp and Llamar buttons. Here it sits
* al "Miembro desde…", se copia con un toque y tiene 44px de alto aunque el * next to "Miembro desde…", copies on one tap and is 44px tall even though the
* texto sea de 14px: es un control, no un dato decorativo. */ * text is 14px: it is a control, not decorative data. */
export function AttendeePhoneLine() { export function AttendeePhoneLine() {
const { attendee } = useAttendeeDetail() const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard() const { copied, copy } = useCopyToClipboard()
@@ -25,8 +25,8 @@ export function AttendeePhoneLine() {
className="flex min-h-11 max-w-fit items-center gap-2 rounded-lg text-left transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent" className="flex min-h-11 max-w-fit items-center gap-2 rounded-lg text-left transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
> >
<span className="truncate text-sm text-foreground">{label}</span> <span className="truncate text-sm text-foreground">{label}</span>
{/* `aria-hidden`: la confirmación se anuncia desde la región viva de {/* `aria-hidden`: the confirmation is announced from the live region
abajo, así no se cuela en el nombre del botón. */} below, so it does not sneak into the button's name. */}
{copied ? ( {copied ? (
<span <span
aria-hidden="true" aria-hidden="true"

View File

@@ -10,7 +10,7 @@ type Consequence = { key: string; icon: LucideIcon; text: string }
export function ConfirmRemoveAttendeeDialog({ export function ConfirmRemoveAttendeeDialog({
returnFocusRef, returnFocusRef,
}: { }: {
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */ /** The element focus returns to when it closes (the "⋯" button). */
returnFocusRef: RefObject<HTMLButtonElement | null> returnFocusRef: RefObject<HTMLButtonElement | null>
}) { }) {
const { const {
@@ -117,9 +117,9 @@ export function ConfirmRemoveAttendeeDialog({
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus> <Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
Cancelar Cancelar
</Button> </Button>
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de {/* Label in black on the `danger` fill: it is the only way to reach AA
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro, with the same red in both themes (4.9:1 light, 6.7:1 dark); in white
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */} they are 3.7:1 and 2.7:1. */}
<Button <Button
onClick={() => confirmRemoveAttendee(false)} onClick={() => confirmRemoveAttendee(false)}
disabled={isSubmittingRemoval} disabled={isSubmittingRemoval}
@@ -138,10 +138,10 @@ export function ConfirmRemoveAttendeeDialog({
) )
} }
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no /** The app's `Modal` does not trap focus; this dialog does, so Tab does not walk
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si * behind the overlay. It only cycles between the content's controls: if focus is
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con * somewhere else (the `Modal`'s X, which still closes on Escape) it lets it
* Escape) lo deja seguir su curso normal. */ * follow its normal course. */
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) { function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
const handleKeyDown = (event: KeyboardEvent) => { const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return if (event.key !== 'Tab') return

View File

@@ -3,18 +3,18 @@ import type { ReactNode } from 'react'
import { ChevronDown } from 'lucide-react' import { ChevronDown } from 'lucide-react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a /* The grey has no opacity modifier: on the dark background `text-foreground/50`
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */ drops to ~2.7:1 and `/80` to ~4.2:1, both below AA. The full token passes. */
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground' export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
/* La fila que despliega la sección es un botón, no un título: por eso lleva /* The row that expands the section is a button, not a heading: that is why it
superficie de hover y presión, se pinta en `primary` para que se lea gets hover and press surfaces, it is painted in `primary` so it reads
distinta de los títulos fijos, y el chevron cae al borde derecho de la fila different from the fixed titles, and the chevron lands on the row's right edge
en vez de pegado al texto. instead of hugging the text.
El `px-3` es interno: la banda de hover sigue a sangre hasta el borde de la The `px-3` is internal: the hover band bleeds all the way to the section edge
sección y lo que se separa del borde es el contenido (el `px-3` del `h2` y and it is the content that is set off from the edge (the `px-3` on the `h2`
del `trailing` de abajo alinea rótulo y resumen con esta fila). */ and on the `trailing` below align the label and the summary with this row). */
const TOGGLE_ROW_CLASS = cn( const TOGGLE_ROW_CLASS = cn(
SECTION_TITLE_CLASS, SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary', 'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary',
@@ -23,24 +23,24 @@ const TOGGLE_ROW_CLASS = cn(
) )
type SectionProps = { type SectionProps = {
/** Título de la sección. Un string por lo general. */ /** The section title. Usually a string. */
title: ReactNode title: ReactNode
/** A la derecha del título: el resumen de asistencia, por ejemplo. */ /** To the right of the title: the attendance summary, for example. */
trailing?: ReactNode trailing?: ReactNode
/** Cuando está, el título entero es el disparador del contenido y `title` es /** When present, the whole title is the content's trigger and `title` is just
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el * its label: the `<h2>` is still the section heading and the button takes the
* botón ocupa la fila completa. */ * full row. */
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void } toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
children: ReactNode children: ReactNode
} }
/** Bloque de sección: separador fino sobre el fondo, título chico en /** Section block: thin separator over the background, small uppercase title and
* mayúsculas y contenido sin padding propio (el de la pantalla). * content with no padding of its own (the screen's).
* *
* El aire vive acá y no en la pantalla: cada sección cierra con su propio * The spacing lives here and not in the screen: every section closes with its
* padding, así que el separador queda siempre a la misma distancia del * own padding, so the separator always sits the same distance from the content
* contenido de arriba. Sumar otra sección (Pagos, por ejemplo) es insertar * above. Adding another section (Pagos, say) means inserting one more block and
* otro bloque y nada más. */ * nothing else. */
export function Section({ title, trailing, toggle, children }: SectionProps) { export function Section({ title, trailing, toggle, children }: SectionProps) {
const headingId = useId() const headingId = useId()
@@ -48,9 +48,9 @@ export function Section({ title, trailing, toggle, children }: SectionProps) {
<section aria-labelledby={headingId} className="border-t border-border/70 py-4"> <section aria-labelledby={headingId} className="border-t border-border/70 py-4">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
{toggle ? ( {toggle ? (
// El botón vive dentro del `<h2>`: el encabezado no se pierde y el // The button lives inside the `<h2>`: the heading is not lost and the
// disparador sigue siendo un control de verdad (Enter, Espacio y foco // trigger is still a real control (Enter, Space and keyboard-visible
// visible por teclado). // focus).
<h2 id={headingId} className="min-w-0 flex-1"> <h2 id={headingId} className="min-w-0 flex-1">
<button <button
type="button" type="button"

View File

@@ -1,15 +1,15 @@
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link). /** The screen's action button (WhatsApp, Llamar, Copiar link).
* *
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle * `primary-soft` fill, which is the same filled surface the group detail uses:
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque * a thin border over `surface` is invisible in the light theme because
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y * `surface` and `background` are both white. 44px tall for the finger, and the
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */ * same focus ring and press feedback as the app's `Button`. */
export const ACTION_BUTTON_CLASS = export const ACTION_BUTTON_CLASS =
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent' 'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el /** A panel's primary action (Enviar por WhatsApp). Same surface as the app's
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que * `primary` `Button` —`accent` fill with `on-accent` text, which gives 6.8:1 in
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna: * both themes— but full width because it is alone in the column: next to the
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */ * secondary one at 50% the long labels wrap onto two lines. */
export const PRIMARY_ACTION_CLASS = export const PRIMARY_ACTION_CLASS =
'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent' 'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'

View File

@@ -1,8 +1,8 @@
import type { AttendanceHistoryItem } from '@gruperly/shared' import type { AttendanceHistoryItem } from '@gruperly/shared'
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el /* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
backend). Es el techo real de lo que esta pantalla puede mostrar, así que backend). It is the real ceiling on what this screen can show, so "Ver todas"
"Ver todas" no promete más de lo que hay. */ does not promise more than there is. */
export const HISTORY_PREVIEW = 5 export const HISTORY_PREVIEW = 5
export const HISTORY_LIMIT = 20 export const HISTORY_LIMIT = 20
@@ -29,9 +29,9 @@ export function attendanceStatusLabel(status: AttendanceSession['status']): stri
} }
} }
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado /* The status is read through text and icon, not color alone: the status tokens
están pensados como texto sobre superficies oscuras y el verde sobre blanco are meant as text over dark surfaces and the green on white sits just below
queda justo por debajo de AA, así que la fila lleva las tres señales. */ AA, so the row carries all three signals. */
export function attendanceStatusClass(status: AttendanceSession['status']): string { export function attendanceStatusClass(status: AttendanceSession['status']): string {
switch (status) { switch (status) {
case 'PRESENT': case 'PRESENT':
@@ -45,7 +45,7 @@ export function attendanceStatusClass(status: AttendanceSession['status']): stri
} }
} }
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */ /** "28 sep 2026". It is the usual short date: it fits on one line on mobile. */
export function formatMemberSince(iso: string): string { export function formatMemberSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-MX', { return new Date(iso).toLocaleDateString('es-MX', {
day: 'numeric', day: 'numeric',
@@ -59,9 +59,9 @@ export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases` return count === 1 ? '1 clase' : `${count} clases`
} }
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas /** What is displayed: from the most recent to the oldest, with the last
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden * `HISTORY_PREVIEW` as the preview. The endpoint returns the opposite order
* contrario (más antigua → más reciente). */ * (oldest → most recent). */
export function visibleSessions( export function visibleSessions(
sessions: AttendanceSession[], sessions: AttendanceSession[],
showAll: boolean, showAll: boolean,
@@ -70,26 +70,27 @@ export function visibleSessions(
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW) return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
} }
/** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las /** Classes with a recorded attendance: attended, was absent or was absent with
* "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y * notice. The "Sin registrar" ones do not count: without a record there is
* meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */ * neither attendance nor absence, and putting them in the denominator made
* "1 de 3" read as two absences. */
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] { function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
return sessions.filter((session) => session.status != null) return sessions.filter((session) => session.status != null)
} }
export type AttendanceSummary = { export type AttendanceSummary = {
/** "1 de 1 clase", o "Sin clases registradas" si no hay ninguna con dato. */ /** "1 de 1 clase", or "Sin clases registradas" if there is none with a record. */
label: string label: string
/** "2 sin registrar", o `null` si no hay clases sin registro. */ /** "2 sin registrar", or `null` if there are no classes without a record. */
unmarkedLabel: string | null unmarkedLabel: string | null
} }
/** Resumen de las filas que se están mostrando: cuántas clases registró la /** Summary of the rows being shown: how many classes the person recorded out of
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar. * how many have a record, and how many were left unmarked.
* *
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase * The "sin registrar" text is dimmed when there is no marked class: the summary
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo * already says there is no data and the two texts would say the same thing
* mismo dos veces. */ * twice. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary { export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
const marked = markedSessions(sessions) const marked = markedSessions(sessions)
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null } if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }

View File

@@ -2,8 +2,9 @@ import { useEffect, useRef, useState } from 'react'
const FEEDBACK_MS = 1800 const FEEDBACK_MS = 1800
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es /** Copies to the clipboard and confirms in the same spot where it was pressed,
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */ * which is where the eye already is: a toast on top forces the view to hunt for
* the control again. */
export function useCopyToClipboard() { export function useCopyToClipboard() {
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null) const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -24,8 +25,8 @@ export function useCopyToClipboard() {
if (timeoutRef.current) clearTimeout(timeoutRef.current) if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS) timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
}) })
// Si el navegador rechaza la escritura no hay nada que confirmar: se // If the browser rejects the write there is nothing to confirm: the control
// deja el control como estaba en vez de dejar la promesa sin manejar. // is left as it was instead of leaving the promise unhandled.
.catch(() => setCopied(false)) .catch(() => setCopied(false))
} }

View File

@@ -44,7 +44,8 @@ export function SignupPage() {
return return
} }
if (data?.token) { if (data?.token) {
// Con email verification activo, la sesión no se crea hasta verificar. // With email verification on, the session is not created until it is
// verified.
navigate({ to: '/verify-email', search: { email } }) navigate({ to: '/verify-email', search: { email } })
} }
}) })

View File

@@ -21,9 +21,9 @@ export function ClassAttendanceView() {
return ( return (
<section> <section>
{/* El título grande va siempre, incluso mientras carga la sesión: es lo {/* The large title always renders, even while the session loads: it is what
que orienta y da altura de anclaje a la barra. El contador de orients and gives the bar its anchor height. The present counter, on the
presentes, en cambio, solo aparece cuando ya hay alumnos en pantalla. */} other hand, only shows once there are students on screen. */}
<LargeTitle <LargeTitle
title={sessionInfo?.groupName ?? 'Asistencia'} title={sessionInfo?.groupName ?? 'Asistencia'}
leading={ leading={

View File

@@ -2,74 +2,73 @@ import type { CapacityCounts, RiskTone } from './card'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
/** /**
* Indicador único de cupo y asistencia: una barra que junta "cuánta gente hay" * Single capacity and attendance indicator: one bar that joins "how many people
* con "cómo viene esa gente". Reemplaza al badge de baja asistencia y a la * there are" with "how those people are doing". It replaces the low attendance
* barrita de ocupación, que contaban dos cosas distintas y competían por el * badge and the occupancy bar, which counted two different things and competed
* mismo lugar en la tarjeta. * for the same spot on the card.
* *
* ── Qué se está midiendo ─────────────────────────────────────────────────── * ── What is being measured ──────────────────────────────────────────────────
* `capacity` es el total contra el que se reparten los bloques, y `places` dice * `capacity` is the total the blocks are split against, and `places` says whether
* si ese total son lugares del cupo o la matrícula. Sin cupo declarado el * that total is spots of the capacity or the roster. With no declared capacity the
* grupo no tiene lugares, pero sí tiene gente en riesgo, así que la barra * group has no spots, but it does have people at risk, so the bar measures the
* mide a los miembros (`places: false`) en vez de desaparecer. * members (`places: false`) instead of disappearing.
* *
* ── Dos modos ────────────────────────────────────────────────────────────── * ── Two modes ───────────────────────────────────────────────────────────────
* Con total chico (<= `SEGMENTED_CAPACITY_MAX`) hay un segmento por unidad y se * With a small total (<= `SEGMENTED_CAPACITY_MAX`) there is one segment per unit
* ve exactamente qué posiciones están ocupadas y de qué color. Con total grande * and you see exactly which positions are occupied and in what color. With a large
* eso ya no se distingue, así que se pasa a bloques proporcionales. Ambos modos * total that is no longer distinguishable, so it switches to proportional blocks.
* conservan la misma medida visual para que la lista se pueda escanear en * Both modes keep the same visual measure so the list can be scanned vertically;
* vertical; importa la proporción, no que los grupos chicos queden diminutos. * the proportion is what matters, not that small groups end up tiny.
* *
* ── Ancho ────────────────────────────────────────────────────────────────── * ── Width ───────────────────────────────────────────────────────────────────
* La barra se reparte el ancho disponible y nunca lo excede: es la regla que * The bar splits the available width and never exceeds it: that is the rule that
* impide que la tarjeta desborde la pantalla en un teléfono. Por eso el * stops the card from overflowing the screen on a phone. That is why the segment
* segmento va `flex-1 max-w-[50px]` y no con un ancho fijo. Un `w-[50px] * goes `flex-1 max-w-[50px]` and not with a fixed width. A `w-[50px] shrink-0`
* shrink-0` parece inocuo, pero a 10 segmentos son 554px (más los gaps) contra * looks harmless, but at 10 segments it is 554px (plus the gaps) against the
* los ~288px que deja la tarjeta en un viewport de 402px: los hijos `shrink-0` * ~288px the card leaves on a 402px viewport: the `shrink-0` children spill out
* se salen de la caja ya encogida y, sin nada que los recorte, empujan el * of the already-shrunk box and, with nothing clipping them, push the document
* documento a un scroll horizontal. Con `flex-1` cada segmento toma la parte * into a horizontal scroll. With `flex-1` each segment takes its share of the real
* que le toca del espacio real, y el `max-w` mantiene el ancho de escritorio * space, and the `max-w` keeps the desktop width (50px). The container's
* (50px). El `overflow-hidden` del contenedor es la red de seguridad: recorta * `overflow-hidden` is the safety net: it clips instead of overflowing if one day
* en vez de desbordar si algún día vuelve a pasar algo más grande que el * something bigger than the space shows up again.
* espacio.
* *
* Ojo: repartirse el ancho no alcanza por sí solo. Un segmento muy angosto * Note: splitting the width is not enough on its own. A very narrow segment
* deja de distinguir su color del vecino y la barra se vuelve una línea de * stops telling its color apart from its neighbor and the bar becomes a line of
* puntos. Por eso el ancho que se le cede a la barra importa tanto como el * dots. That is why the width ceded to the bar matters as much as the split: the
* reparto: el label de la card dice "4/5" en móvil en vez de "4/5 miembros" * card's label says "4/5" on mobile instead of "4/5 miembros" precisely so that
* justamente para que al cupo 10 le queden ~24px por píldora en vez de ~19px. * capacity 10 is left with ~24px per pill instead of ~19px.
* Ver `SEGMENTED_CAPACITY_MAX` para el resto del reparto de cuentas. * See `SEGMENTED_CAPACITY_MAX` for the rest of the accounting.
* *
* ── Lectura ──────────────────────────────────────────────────────────────── * ── Reading ─────────────────────────────────────────────────────────────────
* El color solo no alcanza. El bloque va con `role="img"` y un `aria-label` que * Color alone is not enough. The block carries `role="img"` and an `aria-label`
* dice todo ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención"), que es * that says everything ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en
* lo que lee el lector de pantalla; y la tarjeta repite lo esencial en texto * atención"), which is what the screen reader reads; and the card repeats the
* ("3 en riesgo alto · 4 en atención") abajo. Los tres niveles van siempre en el * essentials in text ("3 en riesgo alto · 4 en atención") below. The three levels
* mismo orden, de peor a mejor, para que la barra se lea igual en todas las * always go in the same order, worst to best, so the bar reads the same on every
* tarjetas y el ojo aprenda a escanearlas. * card and the eye learns to scan them.
* *
* ── Contraste ────────────────────────────────────────────────────────────── * ── Contrast ────────────────────────────────────────────────────────────────
* Todo sale de tokens, nada hardcodeado. Los rellenos miden 5.74:1 (rojo), * Everything comes from tokens, nothing hardcoded. The fills measure 5.74:1 (red),
* 4.58:1 (ámbar) y 6.20:1 (azul) contra la tarjeta en tema claro, y 5.44, 10.15 * 4.58:1 (amber) and 6.20:1 (blue) against the card in the light theme, and 5.44,
* y 7.10:1 en oscuro: los tres pasan el 3:1 que pide WCAG para contenido no * 10.15 and 7.10:1 in dark: all three pass the 3:1 WCAG asks of non-text content
* textual y el 4.5:1 que necesita la línea de texto que los acompaña. El rojo * and the 4.5:1 the accompanying text line needs. The red uses `danger-fg` and not
* usa `danger-fg` y no `danger` justamente por eso: `danger` en tema claro da * `danger` precisely for that: `danger` in the light theme gives 3.35:1 and would
* 3.35:1 y no alcanzaría como texto. * not do as text.
* *
* El contorno de los lugares libres NO puede usar `border`, que en tema oscuro * The outline of the free spots can NOT use `border`, which in the dark theme is
* vale lo mismo que la tarjeta (1.00:1 y no se ve); usa `foreground` al 70%, * the same as the card (1.00:1 and invisible); it uses `foreground` at 70%, which
* que da 3.42:1 en claro y 3.55:1 en oscuro. * gives 3.42:1 in light and 3.55:1 in dark.
*/ */
type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'> type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'>
/* De peor a mejor. Es el orden fijo de la barra: si mañana se agrega un nivel /* Worst to best. This is the bar's fixed order: if a level is ever added it goes
entra en esta lista y no hay que tocar el componente. */ in this list and the component does not have to change. */
const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres'] const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres']
const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok'] const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok']
/* El lugar libre no es un estado de la persona: es ausencia de gente. Por eso /* The free spot is not a state of the person: it is the absence of people. That
es el único que no lleva relleno. */ is why it is the only one with no fill. */
const FILL: Record<Level, string> = { const FILL: Record<Level, string> = {
riesgoAlto: 'bg-attendance-high', riesgoAlto: 'bg-attendance-high',
atencion: 'bg-attendance-attention', atencion: 'bg-attendance-attention',
@@ -79,7 +78,7 @@ const FILL: Record<Level, string> = {
const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50' const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50'
/** Frase larga del `aria-label`: toda la información del bloque en una línea. */ /** The `aria-label`'s long phrase: all of the block's information in one line. */
export function capacityIndicatorLabel( export function capacityIndicatorLabel(
counts: CapacityCounts, counts: CapacityCounts,
capacity: number, capacity: number,
@@ -99,9 +98,9 @@ export function capacityIndicatorLabel(
const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : '' const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : ''
/* Sin cupo declarado no hay lugares que ocupar ni libres que contar: la /* With no declared capacity there are no spots to fill and no free ones to
barra es un reparto de la matrícula y decirlo con esas palabras sería count: the bar is a split of the roster, and saying it with those words
inventar un cupo que el grupo no tiene. */ would invent a capacity the group does not have. */
if (!places) { if (!places) {
return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}` return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}`
} }
@@ -119,12 +118,12 @@ export function AttendanceCapacityIndicator({
className, className,
}: { }: {
counts: CapacityCounts counts: CapacityCounts
/** Total contra el que se reparte la barra: el cupo, o la matrícula si el /** The total the bar is split against: the capacity, or the roster if the
* grupo no tiene cupo declarado. */ * group has no declared capacity. */
capacity: number capacity: number
/** `true` cuando el total es chico y va un segmento por unidad. */ /** `true` when the total is small and goes one segment per unit. */
segmented: boolean segmented: boolean
/** `false` cuando `capacity` son miembros y no lugares del cupo. */ /** `false` when `capacity` is members and not spots of the capacity. */
places?: boolean places?: boolean
className?: string className?: string
}) { }) {
@@ -181,13 +180,13 @@ export function capacitySegmentWidth(count: number, capacity: number): string {
return `${((count / capacity) * 100).toFixed(4)}%` return `${((count / capacity) * 100).toFixed(4)}%`
} }
/** Un segmento es una persona: el color es el del nivel de ese lugar. */ /** A segment is a person: the color is that of the level of this spot. */
function LevelSegment({ level, className }: { level: Level; className?: string }) { function LevelSegment({ level, className }: { level: Level; className?: string }) {
if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} /> if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} />
return <span className={cn('rounded-full', FILL[level], className)} /> return <span className={cn('rounded-full', FILL[level], className)} />
} }
/** El lugar `index` lo ocupa la persona de peor nivel que todavía entra. */ /** The person of the worst level that still fits occupies the `index` spot. */
function levelAt(counts: CapacityCounts, index: number): Level { function levelAt(counts: CapacityCounts, index: number): Level {
let restante = index let restante = index
for (const level of LEVELS) { for (const level of LEVELS) {
@@ -197,10 +196,9 @@ function levelAt(counts: CapacityCounts, index: number): Level {
return 'libres' return 'libres'
} }
/** Color del texto según el peor nivel: la línea de estado no puede quedar /** Text color by worst level: the status line cannot end up misaligned with the
* desalineada con la barra. `danger-fg` y no `danger` porque el primero es la * bar. `danger-fg` and not `danger` because the first is the legible version
* versión legible (5.7:1 en claro, 5.4:1 en oscuro) y el segundo se queda en * (5.7:1 in light, 5.4:1 in dark) and the second stays at 3.35:1 as text. */
* 3.35:1 como texto. */
export const TONE_TEXT: Record<RiskTone, string> = { export const TONE_TEXT: Record<RiskTone, string> = {
riesgo_alto: 'text-danger-fg', riesgo_alto: 'text-danger-fg',
atencion: 'text-warning', atencion: 'text-warning',

View File

@@ -74,10 +74,10 @@ export function GroupCardContent(props: GroupCardProps) {
places={true} places={true}
/> />
{/* La palabra "miembros" se lleva ~60px que la barra necesita en un {/* The word "miembros" takes ~60px that the bar needs on a phone. On
teléfono. En móvil va solo el "4/5", que ya se entiende en una mobile only the "4/5" goes, which already reads on a capacity card
tarjeta de cupos y no pierde nada: el `aria-label` del indicador and loses nothing: the indicator's `aria-label` still counts
sigue contando todo ("4 de 5 lugares ocupados: 2 en riesgo alto..."). */} everything ("4 de 5 lugares ocupados: 2 en riesgo alto..."). */}
<span className="shrink-0 whitespace-nowrap text-base tabular-nums text-secondary"> <span className="shrink-0 whitespace-nowrap text-base tabular-nums text-secondary">
{members.length}/{capacity} {members.length}/{capacity}
<span className="hidden sm:inline"> <span className="hidden sm:inline">

View File

@@ -82,8 +82,8 @@ export function GroupsView() {
) : null} ) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? ( {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
/* Un ícono solo, con un punto focal, y el texto en secundario: la /* A single icon, one focal point, and the text in secondary: the empty
pantalla vacía compite con la acción y no puede ganar. */ state competes with the action and must not win. */
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center"> <div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg"> <span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<CalendarPlus className="size-7" aria-hidden="true" /> <CalendarPlus className="size-7" aria-hidden="true" />

View File

@@ -83,8 +83,8 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
const [isParsingFile, setIsParsingFile] = useState(false) const [isParsingFile, setIsParsingFile] = useState(false)
const [isDragging, setIsDragging] = useState(false) const [isDragging, setIsDragging] = useState(false)
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar, // Same query keys as the group detail: the data is already in cache on
// así que la página se monta sin spinner ni fetch duplicado. // navigation, so the page mounts with no spinner and no duplicated fetch.
const groupQuery = useQuery({ const groupQuery = useQuery({
queryKey: ['group', groupId], queryKey: ['group', groupId],
queryFn: () => getGroup(groupId), queryFn: () => getGroup(groupId),

View File

@@ -73,13 +73,14 @@ export function AnalyticsView() {
await navigator.clipboard.writeText(message) await navigator.clipboard.writeText(message)
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.') toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
} catch { } catch {
// Si clipboard falla, igual abrimos WhatsApp con el mensaje. // If clipboard fails, we still open WhatsApp with the message.
} }
window.open(waUrl, '_blank', 'noopener,noreferrer') window.open(waUrl, '_blank', 'noopener,noreferrer')
} }
// El nombre suele estar en caché porque se llega desde la ficha del grupo: así // The group name is usually cached because the user comes from the group detail
// el título grande aparece de entrada y no hay salto cuando cargan las queries. // page: that way the large title shows right away and there is no jump when
// the queries load.
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
const groupName = riskQuery.data?.groupName ?? cachedGroupName const groupName = riskQuery.data?.groupName ?? cachedGroupName
const analytics = analyticsQuery.data const analytics = analyticsQuery.data
@@ -87,14 +88,15 @@ export function AnalyticsView() {
const isPending = analyticsQuery.isPending || riskQuery.isPending const isPending = analyticsQuery.isPending || riskQuery.isPending
const hasFailed = analyticsQuery.isError || riskQuery.isError const hasFailed = analyticsQuery.isError || riskQuery.isError
// El contenido necesita los dos queries: sin `riskQuery` no hay ni el nombre // The content needs both queries: without `riskQuery` there is neither the
// del grupo ni la lista de alumnos en riesgo. // group name nor the list of attendees at risk.
const showContent = !isPending && !hasFailed && Boolean(analytics) const showContent = !isPending && !hasFailed && Boolean(analytics)
return ( return (
<section className="mx-auto w-full max-w-md lg:max-w-6xl"> <section className="mx-auto w-full max-w-md lg:max-w-6xl">
{/* El título grande va siempre, incluso cargando: es lo que da altura a {/* The large title always renders, even while loading: it is what gives
la barra y evita que el layout salte cuando llegan los datos. */} the bar its height and stops the layout from jumping when the data
arrives. */}
<LargeTitle <LargeTitle
title={groupName ?? 'Grupo'} title={groupName ?? 'Grupo'}
leading={ leading={
@@ -108,9 +110,9 @@ export function AnalyticsView() {
</Link> </Link>
} }
> >
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el {/* "Estadísticas" is the screen's subtitle, not its title: the large
título grande identifica el grupo y la barra colapsada lo muestra title identifies the group and the collapsed bar keeps showing it so
para saber siempre sobre qué se está mirando. */} you always know what you are looking at. */}
<div className="mt-2 flex flex-wrap items-center justify-between gap-3"> <div className="mt-2 flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
<p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70"> <p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70">

View File

@@ -1,34 +1,34 @@
import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared' import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
/* Derivaciones de la tarjeta del listado de grupos. La tarjeta no consulta /* Derivations for the group listing card. The card queries nothing: it decides
nada: decide acá qué se ve, con qué tono y con qué peso visual, para que el here what is shown, with what tone and with what visual weight, so the JSX only
JSX solo arme el layout y las reglas se puedan testear sueltas. builds the layout and the rules can be tested on their own.
Los conteos por nivel y los miembros urgentes no se calculan en el cliente: The per-level counts and the urgent attendees are not computed on the client:
los trae `GET /groups-risk/overview`, que corre la misma función de dominio they come from `GET /groups-risk/overview`, which runs the same domain function
(`getGroupAttendanceSummary` en packages/shared) que va a usar la sección de (`getGroupAttendanceSummary` in packages/shared) that the follow-up section on
seguimiento del Inicio. Acá solo se adapta esa respuesta a lo que la Home will use. Here we only adapt that response to what the card needs to paint,
tarjeta necesita pintar, y se decide cómo se lee. */ and we decide how it reads. */
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'> export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
/** A partir de este cupo el indicador deja de ser un segmento por lugar y pasa /** From this capacity on, the indicator stops being one segment per spot and
* a bloques proporcionales. * switches to proportional blocks.
* *
* El umbral lo fija el ancho, no una ronda. La barra tiene que entrar en la * The threshold is set by the width, not by a round number. The bar has to fit
* tarjeta de un teléfono: ~291px en un viewport de 402px, ya descontando el * in a phone's card: ~291px on a 402px viewport, after discounting `<main>`'s
* padding de `<main>`, el de la card y el label de ocupación. Con el gap de * padding, the card's and the occupancy label. With the 6px gap, ten segments
* 6px, diez segmentos salen de ~24px cada uno: angosto pero todavía una * come out at ~24px each: narrow but still a pill with its own color. That number
* píldora con su color. Ese número depende de dos decisiones de la card que no * depends on two card decisions that are not obvious: the label says "4/5" on
* son obvio: el label dice "4/5" en móvil y no "4/5 miembros" (la palabra se * mobile and not "4/5 miembros" (the word took ~60px), and the segment splits
* llevaba ~60px), y el segmento reparte el ancho en vez de medir 50px fijos. * the width instead of measuring a fixed 50px. With either of the two the other
* Con cualquiera de las dos al revés, el cupo 10 vuelve a ser ilegible. * way, capacity 10 becomes unreadable again.
* *
* A partir del séptimo la píldora se angosta de a poco, y en un viewport de * From the seventh on the pill narrows gradually, and on a 320px viewport
* 320px el cupo 10 cae a ~15px, que ya se lee más como punto que como color. * capacity 10 drops to ~15px, which already reads more like a dot than a color.
* Se prefiere igual: ver qué lugar está libre y de qué nivel es cada uno sigue * We prefer it anyway: seeing which spot is free and what level each one is still
* informando más que una barra proporcional, y el reparto flexible más el * says more than a proportional bar, and the flexible split plus `overflow-hidden`
* `overflow-hidden` garantizan que nunca se desborde la pantalla. */ * guarantee it never overflows the screen. */
export const SEGMENTED_CAPACITY_MAX = 10 export const SEGMENTED_CAPACITY_MAX = 10
export type MemberStatus = 'high_risk' | 'attention' | 'ok' export type MemberStatus = 'high_risk' | 'attention' | 'ok'
@@ -48,7 +48,7 @@ export type CapacityCounts = {
} }
/** /**
* Conteos derivados directamente de una lista de miembros y el cupo. * Counts derived directly from a member list and the capacity.
*/ */
export function capacityCountsFromMembers( export function capacityCountsFromMembers(
members: GroupMember[], members: GroupMember[],
@@ -75,11 +75,11 @@ export function capacityCountsFromMembers(
} }
/** /**
* Reglas de texto de alerta a partir de los miembros: * Alert text rules derived from the members:
* - 1 en riesgo alto: "{Nombre}: {N} faltas" + (si hay atención > 0) " · {K} en atención" * - 1 at high risk: "{Nombre}: {N} faltas" + (if attention > 0) " · {K} en atención"
* - 2 o más en riesgo alto: "{N} en riesgo alto" + (si hay atención > 0) " · {K} en atención" * - 2 or more at high risk: "{N} en riesgo alto" + (if attention > 0) " · {K} en atención"
* - 0 en riesgo alto pero atención > 0: "{K} en atención" * - 0 at high risk but attention > 0: "{K} en atención"
* - Ninguno: null * - None: null
*/ */
export function alertTextFromMembers(members: GroupMember[]): string | null { export function alertTextFromMembers(members: GroupMember[]): string | null {
const highRisk = members.filter((m) => m.status === 'high_risk') const highRisk = members.filter((m) => m.status === 'high_risk')
@@ -106,8 +106,8 @@ export function alertTextFromMembers(members: GroupMember[]): string | null {
} }
/** /**
* Convierte un GroupListItem y GroupRiskSummary en una lista de GroupMember * Turns a GroupListItem and GroupRiskSummary into a list of GroupMember to unify
* para unificar la representación interna. * the internal representation.
*/ */
export function membersFromGroupAndRisk( export function membersFromGroupAndRisk(
group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>, group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>,
@@ -170,16 +170,16 @@ export function membersFromGroupAndRisk(
} }
/** /**
* Conteos que consume el indicador de cupo y asistencia. * Counts consumed by the capacity and attendance indicator.
* *
* `ok` es la diferencia, no un número de la API: el resumen de riesgo solo * `ok` is the remainder, not a number from the API: the risk summary only names
* nombra a los que hay que mirar, y el resto de la matrícula es lo que queda * the ones worth watching, and the rest of the roster is what is doing fine. It
* bien. Se acota a 0 porque el resumen cuenta los miembros activos y la tarjeta * is clamped to 0 because the summary counts active members while the card shows
* muestra todos. * all of them.
* *
* Sin resumen todavía (o si la consulta falla) todos los miembros caen en `ok`. * With no summary yet (or if the query fails) every member falls into `ok`. It is
* Es el estado en calma: el resumen puede seguir cargando y la tarjeta tiene * the calm state: the summary can still be loading and the card has to be able
* que poder pintar igual. * to paint anyway.
*/ */
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts { export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
const riesgoAlto = risk?.riesgoAlto ?? 0 const riesgoAlto = risk?.riesgoAlto ?? 0
@@ -194,7 +194,7 @@ export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefi
} }
} }
/** Tono de la línea de estado y del indicador: el peor nivel presente. */ /** Tone of the status line and of the indicator: the worst level present. */
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok' export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
export function riskTone(counts: CapacityCounts): RiskTone { export function riskTone(counts: CapacityCounts): RiskTone {
@@ -209,11 +209,11 @@ export type StatusLine = {
} }
/** /**
* La cuarta fila de la tarjeta: qué está pasando con la asistencia. * The card's fourth row: what is going on with attendance.
* *
* Con una sola persona en riesgo alto se muestra su nombre y cantidad de * With a single person at high risk it shows their name and absence count. With
* faltas. Con dos o más se resume por nivel. Cuando no hay nada que reportar, * two or more it summarizes by level. When there is nothing to report, the
* el componente omite esta línea por completo. * component leaves this line out entirely.
*/ */
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine { export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
const counts = capacityCounts(group, risk) const counts = capacityCounts(group, risk)
@@ -230,31 +230,31 @@ export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined)
} }
/** /**
* El total con el que se mide el indicador. * The total the indicator is measured against.
* *
* Cuando el grupo no tiene cupo declarado la barra no desaparece: pasa a * When the group has no declared capacity the bar does not disappear: it goes on
* medir a la matrícula, un segmento (o bloque) por miembro, con los lugares * measuring the roster, one segment (or block) per member, with the free spots
* libres en cero. Un grupo sin cupo no tiene "lugares libres" que mostrar, pero * at zero. A group with no capacity has no "free spots" to show, but it does have
* sí tiene gente en riesgo, y esa es justo la señal que la barra existe para * people at risk, and that is exactly the signal the bar exists to communicate.
* comunicar. Lo que sí desaparece es la barra de un grupo vacío: sin miembros no * What does disappear is the bar of an empty group: with no members there is
* hay nada que repartir. * nothing to split.
*/ */
export function barCapacity(group: GroupLike): number { export function barCapacity(group: GroupLike): number {
return group.capacity ?? group.attendeesCount return group.capacity ?? group.attendeesCount
} }
/** ¿El indicador va con un segmento por lugar, o con bloques proporcionales? */ /** Does the indicator go with one segment per spot, or with proportional blocks? */
export function isSegmentedCapacity(capacity: number): boolean { export function isSegmentedCapacity(capacity: number): boolean {
return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX
} }
/** "5/10 miembros", o "5 miembros" cuando el grupo no tiene cupo definido. */ /** "5/10 miembros", or "5 miembros" when the group has no defined capacity. */
export function occupancyLabel(group: GroupLike): string { export function occupancyLabel(group: GroupLike): string {
if (group.capacity === null) return membersLabel(group.attendeesCount) if (group.capacity === null) return membersLabel(group.attendeesCount)
return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}` return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}`
} }
/** Nombra a la única persona en riesgo alto y agrega el total en atención. */ /** Names the single person at high risk and adds the attention total. */
function namedHighRiskMember( function namedHighRiskMember(
urgentes: UrgentMemberSummary[], urgentes: UrgentMemberSummary[],
counts: CapacityCounts, counts: CapacityCounts,
@@ -269,7 +269,7 @@ function namedHighRiskMember(
return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre
} }
/** Grupo grande: los conteos por nivel, y solo de los que hay algo que decir. */ /** Big group: the per-level counts, and only for the ones with something to say. */
function countedLevels(counts: CapacityCounts): string { function countedLevels(counts: CapacityCounts): string {
const partes: string[] = [] const partes: string[] = []
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`) if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
@@ -277,10 +277,11 @@ function countedLevels(counts: CapacityCounts): string {
return partes.join(' · ') return partes.join(' · ')
} }
/* El motivo que mejor explica por qué alguien está en la línea de estado, en el /* The reason that best explains why someone is on the status line, in the order
orden en que la regla los considera: primero la racha de faltas (algo que se the rule considers them: first the streak of absences (something that is
está yendo), después el tiempo sin aparecer, y por último la asistencia. Con going away), then the time since last showing up, and last the attendance
una sola falta y al día se devuelve null: no alcanza para nombrar a nadie. */ rate. With a single absence and ok it returns null: not enough to name
anyone. */
function absenceReason(miembro: UrgentMemberSummary): string | null { function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
@@ -290,8 +291,8 @@ function absenceReason(miembro: UrgentMemberSummary): string | null {
return null return null
} }
/* Solo el primer nombre: en una línea de 360px "Sofía Ramírez: 4 faltas" no /* First name only: on a 360px line "Sofía Ramírez: 4 faltas" does not fit, and
entra, y entre dos personas con el mismo nombre la ficha las distingue. */ between two people with the same name the detail page tells them apart. */
function firstName(fullName: string): string { function firstName(fullName: string): string {
return fullName.trim().split(/\s+/)[0] || fullName return fullName.trim().split(/\s+/)[0] || fullName
} }
@@ -301,7 +302,7 @@ function membersLabel(count: number): string {
} }
/** /**
* Casos de prueba solicitados para verificación contra la imagen de referencia. * Test cases requested for verification against the reference image.
*/ */
export const MOCK_TEST_CASES = [ export const MOCK_TEST_CASES = [
{ {

View File

@@ -5,11 +5,11 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
MEDIUM: 'Riesgo moderado', MEDIUM: 'Riesgo moderado',
} }
/* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla /* The badge only says "Riesgo moderado"; this sentence explains what it is about
(abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */ (an attendee dropping out, not fraud or collections) and lives in the tooltip. */
export const RISK_HINT = export const RISK_HINT =
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.' 'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
/* El motivo concreto ("4 miembros con faltas seguidas") ya no se calcula acá: /* The concrete reason ("4 members with consecutive absences") is not computed
vive en `card.ts`, que además decide el peso visual del badge. Esto quedó here anymore: it lives in `card.ts`, which also decides the badge's visual
con la copia estática de la ficha del grupo. */ weight. What is left here is the static copy of the group detail. */

View File

@@ -30,7 +30,7 @@ export type ListSection = 'members' | 'pending'
type GroupDetailContextValue = { type GroupDetailContextValue = {
groupId: string groupId: string
group: GroupDto | undefined group: GroupDto | undefined
/** Nombre para el título grande: dato real, caché o "Grupo" mientras carga. */ /** Name for the large title: real data, cache or "Grupo" while loading. */
groupTitle: string groupTitle: string
groupQueryPending: boolean groupQueryPending: boolean
riskLevel: GroupRiskLevel riskLevel: GroupRiskLevel
@@ -50,7 +50,7 @@ type GroupDetailContextValue = {
whatsappMessage: string whatsappMessage: string
searchFilter: string searchFilter: string
setSearchFilter: (value: string) => void setSearchFilter: (value: string) => void
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */ /** The member list narrows down to those whose charge is overdue. */
overdueOnly: boolean overdueOnly: boolean
setOverdueOnly: (value: boolean) => void setOverdueOnly: (value: boolean) => void
listSection: ListSection listSection: ListSection
@@ -96,8 +96,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
const [searchFilter, setSearchFilter] = useState('') const [searchFilter, setSearchFilter] = useState('')
const [overdueOnly, setOverdueOnly] = useState(false) const [overdueOnly, setOverdueOnly] = useState(false)
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de // The list's controls belong to the view that opened them: on a tab change
// pestaña se limpian para no heredar un filtro sin coincidencias. // they are cleared so as not to inherit a filter with no matches.
const setListSection = (value: ListSection) => { const setListSection = (value: ListSection) => {
setListSectionState(value) setListSectionState(value)
setSearchFilter('') setSearchFilter('')
@@ -286,14 +286,15 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.') toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
} }
} catch { } catch {
// Si el portapapeles falla, igual abrimos WhatsApp con el mensaje. // If the clipboard fails, we still open WhatsApp with the message.
} }
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer') window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
} }
// El título grande va siempre, incluso cargando: es lo que da altura a la // The large title always renders, even while loading: it is what gives the
// barra immersive y evita que el layout salte. Al llegar desde la ficha del // immersive bar its height and stops the layout from jumping. Arriving from
// grupo el nombre ya está en caché; en la primera carga cae a "Grupo". // the group detail page the name is already cached; on the first load it falls
// back to "Grupo".
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo' const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'

View File

@@ -25,8 +25,9 @@ export function GroupDetailView() {
return ( return (
<section className="animate-fade-in space-y-5 sm:space-y-6"> <section className="animate-fade-in space-y-5 sm:space-y-6">
{/* El título grande va siempre, incluso cargando: es lo que da altura a {/* The large title always renders, even while loading: it is what gives
la barra immersive y evita que el layout salte cuando llegan los datos. */} the immersive bar its height and stops the layout from jumping when
the data arrives. */}
<GroupHeader /> <GroupHeader />
{groupQueryPending ? ( {groupQueryPending ? (

View File

@@ -23,15 +23,16 @@ export function GroupHeader() {
const navigate = useNavigate() const navigate = useNavigate()
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
// Grupo recién creado (sin miembros ni pendientes): los empty states de cada // Brand new group (no members, nothing pending): each tab's empty state
// pestaña ya ofrecen "Compartir" y "Agregar" con su primario explicado, así // already offers "Compartir" and "Agregar" with its primary explained, so the
// que el header no repite las mismas acciones una segunda vez. // header does not repeat the same actions a second time.
const listLoading = attendeesPending || preRegistrationsPending || waitlistPending const listLoading = attendeesPending || preRegistrationsPending || waitlistPending
const isEmptyGroup = const isEmptyGroup =
!listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0 !listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0
// Sin grupo todavía solo se pinta el título: los badges, la descripción y las // With no group yet only the title is painted: the badges, the description and
// acciones necesitan datos, y mostrarlos a medias daría un header parpadeante. // the actions need data, and showing them halfway would give a flickering
// header.
const hasGroup = Boolean(group) const hasGroup = Boolean(group)
return ( return (
@@ -48,8 +49,8 @@ export function GroupHeader() {
</Link> </Link>
} }
> >
{/* Los estados cuelgan del título y no de la barra: en la barra {/* The states hang off the title and not off the bar: in the collapsed
colapsada solo va el nombre, que es lo que se usa para orientarse. */} bar only the name goes, which is what you use to orient yourself. */}
{hasGroup ? ( {hasGroup ? (
<div className="mt-3 flex flex-wrap items-center gap-2"> <div className="mt-3 flex flex-wrap items-center gap-2">
<Badge variant="success" className="gap-1.5 text-[11px]"> <Badge variant="success" className="gap-1.5 text-[11px]">
@@ -57,8 +58,9 @@ export function GroupHeader() {
Activo Activo
</Badge> </Badge>
{hasRisk ? ( {hasRisk ? (
// El badge no puede llevar texto largo sin ensuciar el header: la // The badge cannot carry long text without cluttering the header:
// explicación (riesgo de abandono, no de cobranza) vive en el tooltip. // the explanation (dropout risk, not collections risk) lives in the
// tooltip.
<Tooltip content={RISK_HINT}> <Tooltip content={RISK_HINT}>
<Badge <Badge
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
@@ -86,13 +88,14 @@ export function GroupHeader() {
</LargeTitle> </LargeTitle>
{hasGroup ? ( {hasGroup ? (
// Una sola fila en mobile: el primario toma el ancho que sobra y las dos // A single row on mobile: the primary takes the leftover width and the two
// acciones de apoyo se pliegan a iconos de 44px. En sm+ recuperan el // supporting actions collapse into 44px icons. At sm+ they get their text
// texto porque hay ancho de sobra y el rótulo hace más claro el destino. // back because there is plenty of width and the label makes the
// destination clearer.
<div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end"> <div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end">
{!isEmptyGroup ? ( {!isEmptyGroup ? (
// Un solo primario por pantalla: "Agregar" encabeza la jerarquía y // One primary per screen: "Agregar" heads the hierarchy and the
// las acciones de apoyo quedan al lado, en outline. // supporting actions sit beside it, in outline.
<Button <Button
variant="primary" variant="primary"
onClick={() => onClick={() =>
@@ -110,7 +113,8 @@ export function GroupHeader() {
aria-label="Estadísticas" aria-label="Estadísticas"
className={cn( className={cn(
'h-11 shrink-0 justify-center border-border', 'h-11 shrink-0 justify-center border-border',
// En grupo vacío es la única acción del header: ocupa la fila entera. // On an empty group it is the header's only action: it takes the
// whole row.
isEmptyGroup && 'w-full sm:w-auto', isEmptyGroup && 'w-full sm:w-auto',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4', !isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)} )}

View File

@@ -7,10 +7,10 @@ import {
import { cn } from '../../../lib/utils' import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider' import { useGroupDetail } from './GroupDetailProvider'
/* Escala de la tarjeta: label 11 (etiqueta) · valor 16 (dato) · hero 24 /* The card's scale: label 11 (label) · value 16 (data) · hero 24 (capacity). The
(cupo). El cupo es lo único que se escanea de un vistazo, por eso es el capacity is the only thing you scan at a glance, which is why it is the only
único que sube de nivel; el resto se lee en línea. El ritmo vertical está one that goes up a level; the rest is read inline. The vertical rhythm is
apretado a propósito (~24px menos que antes) sin bajar la legibilidad. */ deliberately tight (~24px less than before) without hurting legibility. */
const LABEL_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground/70' const LABEL_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground/70'
const CELL_CLASS = 'flex items-start gap-3 py-2.5 first:pt-0 last:pb-0 md:py-0' const CELL_CLASS = 'flex items-start gap-3 py-2.5 first:pt-0 last:pb-0 md:py-0'

View File

@@ -11,9 +11,9 @@ import {
summarizeAttendance, summarizeAttendance,
} from './member-row' } from './member-row'
/* Solo lo excepcional se pinta. "Al día" queda en el tono base y con un check /* Only the exceptional is painted. "Ok" stays in the base tone and with a check
para que el estado se lea sin depender del color; vencido es el único que so the state reads without depending on color; overdue is the only one that
sube de peso. */ gains weight. */
const PAYMENT_TONE: Record<PaymentState['kind'], string> = { const PAYMENT_TONE: Record<PaymentState['kind'], string> = {
settled: 'text-foreground', settled: 'text-foreground',
dueSoon: 'font-medium text-warning', dueSoon: 'font-medium text-warning',
@@ -40,8 +40,8 @@ function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) {
return ( return (
<div className="mt-0.5 flex items-center gap-2"> <div className="mt-0.5 flex items-center gap-2">
{/* Cada punto lleva su propio nombre accesible: el color solo es el {/* Every dot carries its own accessible name: color is only the visual
refuerzo visual, no la única forma de saber qué pasó. */} reinforcement, not the only way to know what happened. */}
<span className="flex items-center gap-1"> <span className="flex items-center gap-1">
{summary.dots.map((status, index) => ( {summary.dots.map((status, index) => (
<span <span
@@ -70,9 +70,10 @@ function MemberRow({
<Link <Link
to="/groups/$groupId/attendees/$attendeeId" to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId, attendeeId: attendee.id }} params={{ groupId, attendeeId: attendee.id }}
// `min-h-14` (56px) es el piso táctil cómodo. La fila entera es el link, así // `min-h-14` (56px) is the comfortable touch floor. The whole row is the
// que no hace falta chevron ni fila con tabIndex: hereda el rol y el // link, so there is no need for a chevron or a row with tabIndex: it
// teclado del <a>, y además sirve el href real al abrir en otra pestaña. // inherits the role and keyboard of the <a>, and it also serves the real
// href when opened in another tab.
className={cn( className={cn(
'flex min-h-14 items-center border-b border-foreground/10 px-3 py-2.5', 'flex min-h-14 items-center border-b border-foreground/10 px-3 py-2.5',
'transition-colors duration-150 hover:bg-surface/60 active:bg-surface', 'transition-colors duration-150 hover:bg-surface/60 active:bg-surface',
@@ -93,8 +94,8 @@ function MemberRow({
} }
export function MembersList({ attendees }: { attendees: AttendeeListItem[] }) { export function MembersList({ attendees }: { attendees: AttendeeListItem[] }) {
// El groupId se lee una vez y se pasa: suscribir cada fila al contexto entero // groupId is read once and passed down: subscribing every row to the whole
// hace que un cambio de estado del provider re-renderice N filas sin motivo. // context makes a provider state change re-render N rows for no reason.
const { groupId } = useGroupDetail() const { groupId } = useGroupDetail()
return ( return (

View File

@@ -16,7 +16,7 @@ function OverdueFilter({ count }: { count: number }) {
aria-pressed={overdueOnly} aria-pressed={overdueOnly}
onClick={() => setOverdueOnly(!overdueOnly)} onClick={() => setOverdueOnly(!overdueOnly)}
className={cn( className={cn(
// min-h-11 (44px): objetivo táctil mínimo, igual que los chips de sección. // min-h-11 (44px): minimum touch target, same as the section chips.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold', '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', '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', 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',
@@ -25,8 +25,8 @@ function OverdueFilter({ count }: { count: number }) {
: 'border-border bg-surface text-foreground hover:border-danger/40 hover:text-danger', : 'border-border bg-surface text-foreground hover:border-danger/40 hover:text-danger',
)} )}
> >
{/* La ✕ solo aparece con el filtro puesto: es la señal de que tocarlo {/* The ✕ only shows with the filter on: it is the signal that tapping it
lo saca, sin tener que decirlo. */} takes the filter off, without having to say so. */}
{overdueOnly ? <X className="size-3.5 shrink-0" aria-hidden="true" /> : null} {overdueOnly ? <X className="size-3.5 shrink-0" aria-hidden="true" /> : null}
<span className="whitespace-nowrap">{count} con pago vencido</span> <span className="whitespace-nowrap">{count} con pago vencido</span>
</button> </button>
@@ -46,8 +46,8 @@ export function MembersView() {
const navigate = useNavigate() const navigate = useNavigate()
const query = searchFilter.trim().toLowerCase() const query = searchFilter.trim().toLowerCase()
// El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda: // The phone is not shown on the row but is still a search path: it is how most
// es como la mayoría conoce a los alumnos del grupo. // people know the group's attendees.
const matchesQuery = (attendee: (typeof attendees)[number]) => const matchesQuery = (attendee: (typeof attendees)[number]) =>
!query || !query ||
attendee.fullName.toLowerCase().includes(query) || attendee.fullName.toLowerCase().includes(query) ||
@@ -61,9 +61,9 @@ export function MembersView() {
const visible = attendees const visible = attendees
.filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment))) .filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment)))
.filter(matchesQuery) .filter(matchesQuery)
// Orden alfabético fijo: si se ordenara por cobro o asistencia las filas // Fixed alphabetical order: if it were sorted by charge or attendance the
// saltarían de lugar cada vez que alguien paga o falta, y el nombre es la // rows would jump around every time someone pays or misses, and the name is
// única columna estable de la lista. // the only stable column in the list.
.sort(byFullName) .sort(byFullName)
if (attendeesPending) { if (attendeesPending) {
@@ -108,8 +108,8 @@ export function MembersView() {
const filterBar = overdueCount > 0 ? <OverdueFilter count={overdueCount} /> : null const filterBar = overdueCount > 0 ? <OverdueFilter count={overdueCount} /> : null
if (visible.length === 0) { if (visible.length === 0) {
// El filtro de vencidos nunca queda vacío por sí solo (el chip no se muestra // The overdue filter never ends up empty on its own (the chip is not shown
// si no hay vencidos), así que un vacío acá es siempre la búsqueda. // if there are none overdue), so an empty list here is always the search.
return ( return (
<> <>
{filterBar} {filterBar}

View File

@@ -9,19 +9,19 @@ import { SectionChips } from './SectionChips'
export function MembersWaitlistSection() { export function MembersWaitlistSection() {
const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail() const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail()
// Con pocos miembros el buscador es ruido: se alcanza con recorrer la lista. // With few attendees the search is noise: scrolling the list is enough. It is
// Se quita del árbol en vez de esconderse, para no dejar un hueco en la fila. // removed from the tree instead of hidden, so as not to leave a gap in the
// En Pendientes no cambia nada: ahí el volumen es el que es. // row. In Pendientes nothing changes: there the volume is what it is.
const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN
return ( return (
// Una sola superficie: la lista va directo sobre el lavado, como la info // A single surface: the list sits directly on the wash, like the info card
// card de arriba, en vez de anidarse en una caja más clara. La separación // above, instead of nesting inside a lighter box. The separation between
// entre controles y datos la dan los propios divisores de fila, el tono // controls and data comes from the row dividers themselves, the input's own
// propio del input y el borde de los chips; una caja intermedia solo // tone and the chips' border; an intermediate box only added a level of
// sumaba un nivel de contención y padding horizontal. // containment and horizontal padding.
// `overflow-hidden` recorta el hover de las filas y el borde inferior // `overflow-hidden` clips the rows' hover and the bottom border against the
// contra el radio del panel: las filas son full-bleed. // panel's radius: the rows are full-bleed.
<div className="overflow-hidden rounded-2xl bg-primary-soft"> <div className="overflow-hidden rounded-2xl bg-primary-soft">
<div className="space-y-2 p-3"> <div className="space-y-2 p-3">
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between"> <div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
@@ -41,9 +41,9 @@ export function MembersWaitlistSection() {
) : null} ) : null}
</div> </div>
{/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre {/* Only Pendientes has supporting copy: it explains the difference
pre-inscripción y lista de espera, que no se deduce de los nombres. between pre-registration and waitlist, which cannot be deduced from
En Miembros los rótulos de columna ya dicen todo. */} the names. In Miembros the column labels already say everything. */}
{listSection === 'pending' ? ( {listSection === 'pending' ? (
<p className="max-w-2xl text-xs leading-snug text-foreground/80"> <p className="max-w-2xl text-xs leading-snug text-foreground/80">
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo

View File

@@ -37,9 +37,9 @@ export function PendingView() {
if (!hasAnyEntry && !query) { if (!hasAnyEntry && !query) {
return ( return (
// Full-bleed y sin radio propio: el `overflow-hidden` del panel lo recorta // Full-bleed and with no radius of its own: the panel's `overflow-hidden`
// contra la silueta redondeada. `surface` sobre `primary-soft` hunde el // clips it against the rounded silhouette. `surface` over `primary-soft`
// bloque; con el lavado anterior se camuflaba. // sinks the block; with the previous wash it camouflaged.
<div className="bg-surface px-4 py-10 text-center"> <div className="bg-surface px-4 py-10 text-center">
<Inbox className="mx-auto mb-2 size-10 text-foreground/40" /> <Inbox className="mx-auto mb-2 size-10 text-foreground/40" />
<p className="text-sm font-semibold text-primary">No hay pendientes</p> <p className="text-sm font-semibold text-primary">No hay pendientes</p>
@@ -92,7 +92,7 @@ export function PendingView() {
const Icon = section.icon const Icon = section.icon
const hasRows = section.count > 0 const hasRows = section.count > 0
const titleId = `pending-${section.title.replace(/\s+/g, '-').toLowerCase()}` 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 if (!hasRows && query) return null
return ( return (

View File

@@ -9,12 +9,13 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
return ( return (
<table className="w-full table-fixed text-left text-sm"> <table className="w-full table-fixed text-left text-sm">
<thead> <thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a {/* `border-foreground/10` and not `border`: in dark `--border` is the same
`primary-soft`, el fondo de la fila, y el separador desaparecería. */} as `primary-soft`, the row's background, and the separator would
disappear. */}
<tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80"> <tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th> <th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th> <th scope="col" className="px-3 pb-1.5">Teléfono</th>
{/* En móvil el teléfono manda: la fecha vive en el detalle. */} {/* On mobile the phone leads: the date lives in the detail. */}
<th scope="col" className="hidden px-3 pb-1.5 sm:table-cell">Solicitado</th> <th scope="col" className="hidden px-3 pb-1.5 sm:table-cell">Solicitado</th>
<th scope="col" className="w-8 px-1 pb-1.5"> <th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span> <span className="sr-only">Detalle</span>
@@ -26,7 +27,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
<tr <tr
key={entry.id} key={entry.id}
tabIndex={0} tabIndex={0}
// El hover va a `surface` porque la fila ya vive sobre `primary-soft`. // The hover goes to `surface` because the row already lives on
// `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent" className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedPreRegistration(entry)} onClick={() => setSelectedPreRegistration(entry)}
onKeyDown={(e) => { 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 {/* `px-3` aligns the text with the chips and the search above: it is
mismo eje izquierdo de 12px en toda la sección. */} the same 12px left axis across the whole section. */}
<td className="px-3 py-2"> <td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent"> <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">

View File

@@ -34,7 +34,8 @@ export function SectionChips() {
{SECTIONS.map((section) => { {SECTIONS.map((section) => {
const isActive = listSection === section.id const isActive = listSection === section.id
const count = counts[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 isAttention = section.id === 'pending' && preRegistrationsTotal > 0
const Icon = section.icon const Icon = section.icon
@@ -45,7 +46,7 @@ export function SectionChips() {
aria-pressed={isActive} aria-pressed={isActive}
onClick={() => setListSection(section.id)} onClick={() => setListSection(section.id)}
className={cn( 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', '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', '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', 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',

View File

@@ -9,8 +9,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
return ( return (
<table className="w-full table-fixed text-left text-sm"> <table className="w-full table-fixed text-left text-sm">
<thead> <thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a {/* `border-foreground/10` and not `border`: in dark `--border` is the same
`primary-soft`, el fondo de la fila, y el separador desaparecería. */} as `primary-soft`, the row's background, and the separator would
disappear. */}
<tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80"> <tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th> <th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th> <th scope="col" className="px-3 pb-1.5">Teléfono</th>
@@ -24,7 +25,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
<tr <tr
key={entry.id} key={entry.id}
tabIndex={0} tabIndex={0}
// El hover va a `surface` porque la fila ya vive sobre `primary-soft`. // The hover goes to `surface` because the row already lives on
// `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent" className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedWaitlistEntry(entry)} onClick={() => setSelectedWaitlistEntry(entry)}
onKeyDown={(e) => { 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 {/* `px-3` aligns the text with the chips and the search above: it is
mismo eje izquierdo de 12px en toda la sección. */} the same 12px left axis across the whole section. */}
<td className="px-3 py-2"> <td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent"> <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">

View File

@@ -1,11 +1,12 @@
/* Ajustes de la lista de miembros de la ficha de grupo. Viven acá y no /* Tuning of the group detail's member list. It lives here and not embedded in
incrustados en el componente porque son decisiones de producto, no de estilo: the component because these are product decisions, not style: changing them
cambiarlas no debería obligar a tocar la fila. */ 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 /* From how many days to the due date does the charge turn yellow and the row
avisa. Más atrás ya no es "pronto": o se pagó o quedó en el pasado. */ 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 export const PAYMENT_DUE_SOON_DAYS = 3
/* El buscador se muestra a partir de cierta cantidad de miembros. Con pocos, es /* The search shows from a certain number of attendees. With few of them it is
más ruido que ayuda: alcanza con mirar la lista. */ more noise than help: looking at the list is enough. */
export const MEMBER_SEARCH_MIN = 8 export const MEMBER_SEARCH_MIN = 8

View File

@@ -2,12 +2,13 @@ import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared' import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'
import { PAYMENT_DUE_SOON_DAYS } from './constants' import { PAYMENT_DUE_SOON_DAYS } from './constants'
/* La fila del listado no pide al backend juicios de presentación: pide los /* The listing's row does not ask the backend for presentation verdicts: it asks
datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los for the raw data (recent classes, current charge) and the text comes from
días que faltan cambian según cuándo se mira, así que no pueden venir here. The days remaining change depending on when you look, so they cannot
guardados desde el servidor. */ 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 { function calendarDaysBetween(from: Date, to: Date): number {
const startOf = (date: Date) => const startOf = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
@@ -20,15 +21,15 @@ export type PaymentState =
| { kind: 'overdue'; days: number } | { 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 * Returns `null` when there is nothing to warn about: either the attendee has no
* cobro registrado, o el que tiene vence más adelante que la ventana de aviso y * recorded charge, or the one they have is due later than the warning window and
* todavía no venció. No es lo mismo que "al día", que es un pago cerrado. * 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 * A `PENDING` whose due date has already passed counts as overdue, same as an
* `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo * `OVERDUE`: the stored state often stays at PENDING until someone updates it by
* actualiza a mano y la fila no puede depender de esa disciplina. * hand, and the row cannot depend on that discipline.
*/ */
export function resolvePaymentState( export function resolvePaymentState(
payment: AttendeeListItem['payment'], payment: AttendeeListItem['payment'],
@@ -57,7 +58,7 @@ export function paymentStateLabel(state: PaymentState): string {
case 'settled': case 'settled':
return 'Al día' return 'Al día'
case 'dueSoon': 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 === 0) return 'Vence hoy'
if (state.days === 1) return 'Vence mañana' if (state.days === 1) return 'Vence mañana'
return `Vence en ${state.days} d` return `Vence en ${state.days} d`
@@ -67,20 +68,20 @@ export function paymentStateLabel(state: PaymentState): string {
} }
export type AttendanceSummary = { 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[] dots: AttendanceStatus[]
attended: number attended: number
recorded: number recorded: number
/** "Sin clases aún" cuando no hay nada registrado. */ /** "Sin clases aún" when nothing is recorded. */
label: string 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( export function summarizeAttendance(
recentAttendance: AttendanceStatus[], recentAttendance: AttendanceStatus[],
): AttendanceSummary { ): AttendanceSummary {
// La ventana la fija el backend; el corte final evita que una fila se alargue // The window is set by the backend; the final cut prevents a row from getting
// si el contrato llegara con más clases de las previstas. // longer if the contract ever delivers more classes than expected.
const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT) const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT)
const recorded = dots.length 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 { export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number {
return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' }) return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' })
} }

View File

@@ -17,7 +17,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)
const { refresh } = useAuth() const { refresh } = useAuth()
const goToDashboard = () => { 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 queryClient.invalidateQueries()
void refresh() void refresh()
void navigate({ to: '/' }) void navigate({ to: '/' })

View File

@@ -35,7 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
const status = statusQuery.data const status = statusQuery.data
if (!status) return 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') { if (status.step === 'PAYMENT_CONNECTED') {
setStep((current) => (current === 0 ? 2 : current)) setStep((current) => (current === 0 ? 2 : current))
} }

View File

@@ -3,8 +3,8 @@ import { InstallBanner } from './InstallBanner'
import { IosInstallHint } from './IosInstallHint' import { IosInstallHint } from './IosInstallHint'
/** /**
* Presenta el aviso de instalación. Cuándo mostrarse lo decide `PwaProvider` * Renders the install prompt. `PwaProvider` decides when it should show (signed
* (sesión iniciada + dwell cumplido); acá solo se dibuja lo que corresponda. * in + dwell satisfied); here we only draw whatever applies.
*/ */
export function InstallPrompt() { export function InstallPrompt() {
const { canPrompt, canShowIosHint, promptInstall, dismiss } = usePwa() const { canPrompt, canShowIosHint, promptInstall, dismiss } = usePwa()

View File

@@ -5,9 +5,9 @@ type IosInstallHintProps = {
} }
/** /**
* Safari en iOS no expone `beforeinstallprompt`: no hay forma de disparar la * Safari on iOS does not expose `beforeinstallprompt`: there is no way to trigger
* instalación desde la web, hay que instruir al usuario. Solo informa, sin * the install from the web, the user has to be instructed. It only informs, with
* botón de acción. * no action button.
*/ */
export function IosInstallHint({ onDismiss }: IosInstallHintProps) { export function IosInstallHint({ onDismiss }: IosInstallHintProps) {
return ( return (

View File

@@ -13,16 +13,16 @@ import { useAuth } from '../../context/AuthProvider'
import { useToast } from '../../components/ui' import { useToast } from '../../components/ui'
import { InstallPrompt } from './InstallPrompt' 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 & { type BeforeInstallPromptEvent = Event & {
prompt: () => Promise<void> prompt: () => Promise<void>
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
} }
type PwaContextValue = { 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 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 canShowIosHint: boolean
promptInstall: () => Promise<void> promptInstall: () => Promise<void>
dismiss: () => void dismiss: () => void
@@ -31,19 +31,19 @@ type PwaContextValue = {
const PwaContext = createContext<PwaContextValue | null>(null) const PwaContext = createContext<PwaContextValue | null>(null)
/** /**
* El descarte es definitivo: una vez que el usuario dice "ahora no" no se vuelve * The dismissal is final: once the user says "not now" we never ask again. It
* a preguntar. Comparte clave con la pista de iOS porque el motivo es el mismo. * shares a key with the iOS hint because the reason is the same.
*/ */
const DISMISSED_KEY = 'pwa-install-dismissed' const DISMISSED_KEY = 'pwa-install-dismissed'
/** /**
* Cuánto hay que quedarse en la misma ruta antes de ofrecer instalar. El evento * How long you have to stay on the same route before we offer to install. The
* `beforeinstallprompt` llega a los segundos, así que sin este margen el banner * `beforeinstallprompt` event arrives within seconds, so without this margin the
* cae en medio de la primera tarea de la visita. * banner lands in the middle of the visit's first task.
*/ */
const DWELL_MS = 20_000 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() { function isStandalone() {
return ( return (
window.matchMedia('(display-mode: standalone)').matches || 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 * Real iOS, real Safari. Excludes Chrome/Firefox/Edge/Opera on iOS: they use
* pero también los instala desde Safari, así que la instrucción de compartir * WebKit but also install from Safari, so the share instruction does not apply.
* no aplica. El iPad de iPadOS 13+ se reporta como MacIntel con touch points. * iPadOS 13+ iPads report as MacIntel with touch points.
*/ */
function detectIos() { function detectIos() {
if (isStandalone()) return false if (isStandalone()) return false
@@ -69,11 +69,12 @@ function detectIos() {
} }
/** /**
* El registro se hace desde el provider y no con `injectRegister: 'auto'` para * Registration is done from the provider and not with `injectRegister: 'auto'` so
* poder avisar cuando el shell quedó cacheado. El flag es de módulo porque * we can tell the user when the shell has been cached. The flag is a module
* StrictMode monta dos veces en dev y `onOfflineReady` dispararía dos toasts. * variable because StrictMode mounts twice in dev and `onOfflineReady` would fire
* No se limpia en el unmount: StrictMode lo resetea en el mismo ciclo de montaje * two toasts. It is not cleared on unmount: StrictMode resets it in the same
* y volvería a registrar. Con HMR el módulo se re-evalua y arranca en false. * mount cycle and we would register again. With HMR the module is re-evaluated
* and starts at false.
*/ */
let registered = false let registered = false
@@ -103,7 +104,7 @@ export function PwaProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
const onBeforeInstallPrompt = (event: Event) => { const onBeforeInstallPrompt = (event: Event) => {
// Sin preventDefault el navegador muestra su propio mini-infobar. // Without preventDefault the browser shows its own mini-infobar.
event.preventDefault() event.preventDefault()
setInstallEvent(event as BeforeInstallPromptEvent) setInstallEvent(event as BeforeInstallPromptEvent)
} }
@@ -120,25 +121,25 @@ export function PwaProvider({ children }: { children: ReactNode }) {
} }
}, []) }, [])
// `PwaProvider` monta fuera del `RouterProvider`, así que no puede usar // `PwaProvider` mounts outside the `RouterProvider`, so it cannot use
// `useRouterState`: se suscribe al singleton. Conviene tener la ruta acá y no // `useRouterState`: it subscribes to the singleton. The route is kept here and
// en el componente que muestra el banner, porque `AppLayoutGuard` desmonta // not in the component that shows the banner, because `AppLayoutGuard`
// `RootLayout` cada vez que su query de onboarding vuelve a `pending` y un // unmounts `RootLayout` every time its onboarding query goes back to `pending`,
// timer de dwell en el hijo se perdería en cada navegación. // and a dwell timer in the child would be lost on every navigation.
useEffect( useEffect(
() => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)), () => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)),
[], [],
) )
// Durante el alta inicial no se ofrece instalar: la persona todavía no // During the initial sign-up we do not offer to install: the person does not
// conoce la app. El timer ni siquiera corre, así que al salir arranca de cero // know the app yet. The timer does not even run, so leaving the flow starts it
// en la primera pantalla real. // from scratch on the first real screen.
const inOnboarding = pathname.startsWith('/onboarding') const inOnboarding = pathname.startsWith('/onboarding')
useEffect(() => { useEffect(() => {
// Navegar antes de que se cumpla el tiempo reinicia la cuenta: tampoco // Navigating before the time is up restarts the count: we are not asking
// estamos pidiendo instalar a alguien que está peleando con la app. Una // someone who is busy fighting the app to install it either. Once it is
// vez cumplido queda armed y no se oculta más al navegar. // settled it stays armed and no longer hides on navigation.
if (settled || inOnboarding) return if (settled || inOnboarding) return
const timer = setTimeout(() => setSettled(true), DWELL_MS) const timer = setTimeout(() => setSettled(true), DWELL_MS)
return () => clearTimeout(timer) return () => clearTimeout(timer)
@@ -163,12 +164,12 @@ export function PwaProvider({ children }: { children: ReactNode }) {
}, [info]) }, [info])
/** /**
* Sin sesión no hay nada que instalar todavía: la primera vez que alguien * Without a session there is nothing to install yet: the first time someone
* conoce la app es instalándola, no pidiéndole que la instale. * 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 * WATCH OUT: `_authenticated` is NOT a session guard. `AppLayoutGuard` renders
* `RootLayout` aunque no haya usuario, así que el gate se chequea acá y no * `RootLayout` even when there is no user, so the gate is checked here and
* se puede inferir de dónde se monte el prompt. * cannot be inferred from where the prompt is mounted.
*/ */
const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding

View File

@@ -1,8 +1,8 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
/* Alto de la barra de navegación donde entra el título chico. Tiene que /* Height of the navigation bar where the small title slides in. It has to
coincidir con el `h-14` de `LargeTitle`: la barra es sticky contra el borde match the `h-14` of `LargeTitle`: the bar is sticky to the top edge of the
superior de la ventana y el título grande se mide contra este valor. */ window and the large title is measured against this value. */
const BAR_HEIGHT = 56 const BAR_HEIGHT = 56
function clamp01(value: number) { 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, * Collapse progress of a Large Title: 0 with the large title fully shown,
* 1 cuando quedó por completo tapado detrás de la barra. * 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 * The progress comes from the title's position, not from time: it is
* cada frame mientras se scrollea. Por eso el gesto se siente pegado al dedo * recalculated on every frame while scrolling. That's why the gesture feels
* en vez de "animado", y por eso `requestAnimationFrame` sirve para agrupar * stuck to the finger instead of "animated", and why `requestAnimationFrame`
* eventos de scroll, no para interpolar la animación. * is there to batch scroll events, not to interpolate the animation.
*/ */
export function useLargeTitleCollapse() { export function useLargeTitleCollapse() {
const titleRef = useRef<HTMLHeadingElement>(null) const titleRef = useRef<HTMLHeadingElement>(null)
@@ -32,11 +32,11 @@ export function useLargeTitleCollapse() {
const measure = () => { const measure = () => {
frame = 0 frame = 0
const { top, height } = title.getBoundingClientRect() const { top, height } = title.getBoundingClientRect()
// 0 cuando el borde superior del título llega a la base de la barra, 1 // 0 when the title's top edge reaches the bottom of the bar, 1 when its
// cuando su borde inferior también llegó (quedó enteramente debajo). // bottom edge got there too (it ended up entirely underneath).
const next = clamp01((BAR_HEIGHT - top) / (height || BAR_HEIGHT)) const next = clamp01((BAR_HEIGHT - top) / (height || BAR_HEIGHT))
// Los títulos de grupo llegan asíncrono y pueden cambiar de alto entre // Group titles arrive asynchronously and can change height between
// renders: sin este umbral se re-renderiza en cada frame de scroll. // renders: without this threshold it re-renders on every scroll frame.
setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next)) 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('scroll', schedule, { passive: true })
window.addEventListener('resize', schedule) window.addEventListener('resize', schedule)
// El nombre del grupo se carga después del primer render y la webfont puede // The group name loads after the first render and the webfont can change
// cambiar el alto del título: el rango de colapso depende de esa medida. // the title's height: the collapse range depends on that measurement.
const observer = new ResizeObserver(schedule) const observer = new ResizeObserver(schedule)
observer.observe(title) observer.observe(title)

View File

@@ -1,9 +1,10 @@
@import "tailwindcss"; @import "tailwindcss";
/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en /* Self-hosted Inter variable. We declare only latin and latin-ext by hand
lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el instead of importing @fontsource's wght.css: that one brings all 7 subsets
service worker precachea todo lo emitido, casi 1 MB que nunca se descarga. and the service worker precaches everything emitted, almost 1 MB that never
El archivo .woff2 sí viene del paquete, con hash y cache immutable. */ gets downloaded. The .woff2 file does come from the package, hashed with an
immutable cache. */
@font-face { @font-face {
font-family: "Inter Variable"; font-family: "Inter Variable";
font-style: normal; font-style: normal;
@@ -25,7 +26,7 @@
@custom-variant dark (&:where(.dark, .dark *)); @custom-variant dark (&:where(.dark, .dark *));
@theme inline { @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-50: var(--brand-50);
--color-brand-100: var(--brand-100); --color-brand-100: var(--brand-100);
--color-brand-200: var(--brand-200); --color-brand-200: var(--brand-200);
@@ -38,12 +39,12 @@
--color-brand-900: var(--brand-900); --color-brand-900: var(--brand-900);
--color-brand-950: var(--brand-950); --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-night: var(--brand-night);
--color-brand-celeste: var(--brand-celeste); --color-brand-celeste: var(--brand-celeste);
--color-brand-cloud: var(--brand-cloud); --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-background: var(--background);
--color-surface: var(--surface); --color-surface: var(--surface);
--color-primary: var(--primary); --color-primary: var(--primary);
@@ -70,14 +71,14 @@
--color-attendance-attention: var(--attendance-attention); --color-attendance-attention: var(--attendance-attention);
--color-attendance-ok: var(--attendance-ok); --color-attendance-ok: var(--attendance-ok);
/* Border radius por defecto */ /* Default border radius */
--radius-xl: 0.75rem; --radius-xl: 0.75rem;
/* Tipografía (igual que la landing) */ /* Typography (same as the landing) */
/* @fontsource-variable/inter registra la familia como "Inter Variable" */ /* @fontsource-variable/inter registers the family as "Inter Variable" */
--font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif; --font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
/* Animaciones */ /* Animations */
--animate-fade-in: fade-in 0.2s ease-out; --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; --animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both;
@@ -101,7 +102,7 @@
:root { :root {
color-scheme: light; color-scheme: light;
/* Escala de marca */ /* Brand scale */
--brand-50: #eef4ff; --brand-50: #eef4ff;
--brand-100: #dbe6fe; --brand-100: #dbe6fe;
--brand-200: #bfd3fe; --brand-200: #bfd3fe;
@@ -117,17 +118,17 @@
--brand-celeste: #93b4fd; --brand-celeste: #93b4fd;
--brand-cloud: #eef4ff; --brand-cloud: #eef4ff;
/* Tema claro */ /* Light theme */
--background: #ffffff; --background: #ffffff;
--surface: #ffffff; --surface: #ffffff;
--primary: #0f172a; --primary: #0f172a;
--primary-soft: #f1f5f9; --primary-soft: #f1f5f9;
--foreground: #475569; --foreground: #475569;
/* Texto secundario sobre superficies suaves (tarjetas). En tema claro el /* Secondary text on soft surfaces (cards). In the light theme the
gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre `foreground` gray already scores 6.9:1 on `primary-soft` and 7.6:1 on
`background`, así que acá no hay que mover nada: mismo valor, mismo `background`, so there's nothing to move here: same value, same contract.
contrato. El token existe igual para que "secundario" sea un nombre y no The token exists anyway so "secondary" is a name and not a color
una coincidencia de color. */ coincidence. */
--secondary: #475569; --secondary: #475569;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
@@ -140,18 +141,18 @@
--success-soft: #ecfdf5; --success-soft: #ecfdf5;
--warning: #b45309; --warning: #b45309;
--warning-soft: #fffbeb; --warning-soft: #fffbeb;
/* naranja: escalón de severidad para la misma familia de alertas (aviso por /* Orange: severity step for the same alert family (attendance and capacity
asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la warnings). It scores 4.9:1 on `warning-strong-soft` and 4.4:1 on the card,
tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */ so it works for text and for a subtle border. */
--warning-strong: #c2410c; --warning-strong: #c2410c;
--warning-strong-soft: #fff7ed; --warning-strong-soft: #fff7ed;
--danger: #f43f5e; --danger: #f43f5e;
--danger-soft: #fff1f2; --danger-soft: #fff1f2;
/* Rojo legible como TEXTO. `--danger` da 3.35:1 sobre la tarjeta en tema /* Red legible as TEXT. In the light theme `--danger` scores 3.35:1 on the
claro, así que como texto no llega al 4.5:1 de AA (sí sirve como relleno, card, so as text it misses AA's 4.5:1 (it does work as a fill, where the
donde el mínimo es 3:1). Es el mismo patrón que `accent` / `accent-fg`: un minimum is 3:1). Same pattern as `accent` / `accent-fg`: one color for
color para superficies grandes y su versión legible para rotular. Este large surfaces and a legible version of it for labels. This #be123c scores
#be123c da 5.74:1 sobre la tarjeta y 5.72:1 sobre `danger-soft`. */ 5.74:1 on the card and 5.72:1 on `danger-soft`. */
--danger-fg: #be123c; --danger-fg: #be123c;
--attendance-high: #d63b3b; --attendance-high: #d63b3b;
--attendance-attention: #f5a623; --attendance-attention: #f5a623;
@@ -161,16 +162,16 @@
.dark { .dark {
color-scheme: dark; color-scheme: dark;
/* Tema oscuro (paleta slate/brand de la landing) */ /* Dark theme (slate/brand palette from the landing) */
--background: #020617; --background: #020617;
--surface: #0f172a; --surface: #0f172a;
--primary: #f1f5f9; --primary: #f1f5f9;
--primary-soft: #1e293b; --primary-soft: #1e293b;
--foreground: #94a3b8; --foreground: #94a3b8;
/* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la /* Secondary goes one step up from `foreground`: 7.1:1 on the card (#1e293b)
tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior. and 9.8:1 on the background, against 5.7:1 for the previous gray. The step
El salto importa en las superficies suaves, que son las que dominan las matters on soft surfaces, which are what dominates list cards: supporting
tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */ text there is what gets lost the most. */
--secondary: #a8b6c8; --secondary: #a8b6c8;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
@@ -183,15 +184,15 @@
--success-soft: color-mix(in srgb, var(--success) 15%, transparent); --success-soft: color-mix(in srgb, var(--success) 15%, transparent);
--warning: #fcd34d; --warning: #fcd34d;
--warning-soft: color-mix(in srgb, var(--warning) 15%, transparent); --warning-soft: color-mix(in srgb, var(--warning) 15%, transparent);
/* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el /* In dark the "orange" has to gain lightness to reach the same contrast as
mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo its light version: #fb923c scores 4.7:1 on the badge's translucent
translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */ background, against 4.1:1 for the #f97316 of the standard palette. */
--warning-strong: #fb923c; --warning-strong: #fb923c;
--warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent); --warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent);
--danger: #fb7185; --danger: #fb7185;
--danger-soft: color-mix(in srgb, var(--danger) 15%, transparent); --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 /* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
sobra como relleno, así que acá no hay que mover nada. */ more than enough as a fill, so there's nothing to move here. */
--danger-fg: var(--danger); --danger-fg: var(--danger);
} }
@@ -205,14 +206,14 @@
min-height: 100dvh; min-height: 100dvh;
} }
/* iOS (Safari y standalone) hace auto-zoom al enfocar un control de /* iOS (Safari and standalone) auto-zooms when a form control with font-size
formulario con font-size < 16px, y al cerrar el teclado no restaura el < 16px is focused, and on keyboard close it doesn't restore the scale:
scale: la app queda con zoom. El `Input` ya sube a 16px en mobile the app is left zoomed in. `Input` already goes to 16px on mobile
(`text-base sm:text-sm`); esto es la red de seguridad para textareas, (`text-base sm:text-sm`); this is the safety net for textareas, selects or
selects o inputs crudos que se agreguen más adelante. raw inputs added later.
El 639px calza con el breakpoint `sm` de Tailwind. El `!important` es The 639px matches Tailwind's `sm` breakpoint. The `!important` is on
a propósito: sin él, una clase `text-sm` en un input futuro ganaría por purpose: without it a `text-sm` class on a future input would win on
especificidad y reintroduciría el bug sin avisar. */ specificity and reintroduce the bug without warning. */
@media (max-width: 639px) { @media (max-width: 639px) {
input, input,
textarea, textarea,

View File

@@ -80,7 +80,7 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
problem = body as ProblemDetails problem = body as ProblemDetails
} }
} catch { } catch {
// Sin cuerpo JSON: usamos el error genérico. // No JSON body: we use the generic error.
} }
throw new ApiError(res.status, problem) throw new ApiError(res.status, problem)
} }
@@ -108,9 +108,9 @@ export const createGroup = (payload: CreateFirstGroup) =>
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
/* La pantalla de grupos no tiene paginación: se pide el máximo permitido para /* The groups screen has no pagination: we ask for the maximum allowed so no
que ningún grupo quede fuera de la lista, y la zona horaria del browser para group is left out of the listing, and for the browser time zone so the
que el backend ordene por la próxima clase en la hora local de la persona. */ backend sorts by the next class in the person's local time. */
const GROUPS_PAGE_SIZE = 100 const GROUPS_PAGE_SIZE = 100
export const getGroups = () => { 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 = () => export const getClassesToday = () =>
apiFetch<ClassTodayList>(`/api/v1/classes/today${timeZoneParam()}`) apiFetch<ClassTodayList>(`/api/v1/classes/today${timeZoneParam()}`)
@@ -251,7 +251,7 @@ export const publicNotifyAbsence = (payload: PublicNotifyAbsence) =>
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
// — Analíticas y gestión de riesgo — // — Analytics and risk management —
export const getGroupAnalytics = (groupId: string) => export const getGroupAnalytics = (groupId: string) =>
apiFetch<GroupAnalytics>(`/api/v1/groups/${groupId}/analytics`) apiFetch<GroupAnalytics>(`/api/v1/groups/${groupId}/analytics`)

View File

@@ -18,11 +18,11 @@ export function normalizePhone(rawPhone: string): string {
} }
/** /**
* Parsea texto CSV con soporte para: * Parses CSV text with support for:
* - Delimitadores automáticos (coma, punto y coma, tabulador) * - Automatic delimiters (comma, semicolon, tab)
* - Comillas y comillas escapadas ("") * - Quotes and escaped quotes ("")
* - UTF-8 BOM * - UTF-8 BOM
* - Saltos de línea CRLF o LF * - CRLF or LF line breaks
*/ */
export function parseCsvContent(content: string): string[][] { export function parseCsvContent(content: string): string[][] {
const cleanContent = content.replace(/^\uFEFF/, ''); const cleanContent = content.replace(/^\uFEFF/, '');
@@ -30,7 +30,7 @@ export function parseCsvContent(content: string): string[][] {
if (lines.length === 0) return []; 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 firstLine = lines[0];
const commaCount = (firstLine.match(/,/g) || []).length; const commaCount = (firstLine.match(/,/g) || []).length;
const semicolonCount = (firstLine.match(/;/g) || []).length; const semicolonCount = (firstLine.match(/;/g) || []).length;
@@ -56,7 +56,7 @@ export function parseCsvContent(content: string): string[][] {
if (char === '"') { if (char === '"') {
if (insideQuote && line[i + 1] === '"') { if (insideQuote && line[i + 1] === '"') {
currentCell += '"'; currentCell += '"';
i++; // Saltear comilla escapada i++; // Skip the escaped quote
} else { } else {
insideQuote = !insideQuote; insideQuote = !insideQuote;
} }
@@ -75,8 +75,8 @@ export function parseCsvContent(content: string): string[][] {
} }
/** /**
* Parsea un archivo XLSX de Excel extrayendo sharedStrings y sheet1.xml * Parses an Excel XLSX file by extracting sharedStrings and sheet1.xml with
* utilizando DecompressionStream nativo del navegador sin dependencias externas. * the browser's native DecompressionStream, without external dependencies.
*/ */
export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]> { export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]> {
const view = new DataView(buffer); const view = new DataView(buffer);
@@ -112,7 +112,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
entries.set(fileName, new Uint8Array(decompressed)); entries.set(fileName, new Uint8Array(decompressed));
} }
} catch { } 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<string[][]>
offset = dataStart + compressedSize; offset = dataStart + compressedSize;
} }
// Parsear strings compartidos // Parse the shared strings
const sharedStringsData = entries.get('xl/sharedStrings.xml'); const sharedStringsData = entries.get('xl/sharedStrings.xml');
const sharedStrings: string[] = []; const sharedStrings: string[] = [];
if (sharedStringsData) { if (sharedStringsData) {
@@ -138,7 +138,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
} }
} }
// Parsear sheet1.xml // Parse sheet1.xml
const sheetData = entries.get('xl/worksheets/sheet1.xml'); const sheetData = entries.get('xl/worksheets/sheet1.xml');
if (!sheetData) { if (!sheetData) {
throw new Error('No se pudo encontrar la hoja de cálculo principal en el archivo Excel.'); 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<string[][]>
} }
/** /**
* 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[] { export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] {
if (rawRows.length === 0) return []; 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) { if (!hasHeader) {
firstNameCol = 0; firstNameCol = 0;
lastNameCol = 1; lastNameCol = 1;
@@ -230,7 +230,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
} }
if (phoneCol === -1) { 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++) { for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) {
const sample = rawRows[1][c]; const sample = rawRows[1][c];
if (/^[\d\s+\-()]{6,}$/.test(sample)) { 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() { export function downloadAttendeeTemplateCsv() {
const csvContent = const csvContent =

View File

@@ -51,18 +51,18 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ') return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
} }
/* Un importe se escribe con el país de la persona: su moneda y su regional /* An amount is written with the person's country: its currency and its regional
(separadores, posición del símbolo), sin conversión — el importe lo fija format (separators, symbol position), with no conversion — the amount is set
quien creó el grupo y no se toca. El país sale de la zona horaria del by whoever created the group and is never touched. The country comes from the
sistema y, si no se conoce, del idioma del browser (ver countryOf). Sin system time zone and, when it's unknown, from the browser language (see
país conocido se pinta con el símbolo $ genérico, nunca con un código countryOf). With no known country we fall back to the generic $ symbol,
inventado. La firma acepta moneda y locale para forzarlas (tests, print) never to an invented code. The signature takes a currency and a locale to
sin tocar los call sites. */ force them (tests, print) without touching the call sites. */
/* La configuración regional del browser manda en cómo se pintan los datos. /* The browser's regional settings decide how the data is rendered. It's read
Se lee en cada llamada (es un accessor barato) para que un cambio de idioma on every call (it's a cheap accessor) so a system language change shows up
del sistema se refleje sin recargar; lo caro es construir el formatter, así without a reload; building the formatter is the expensive part, so those are
que esos se memorizan por locale/moneda. */ memoized per locale/currency. */
type BrowserNavigator = { language?: string; languages?: readonly string[] } type BrowserNavigator = { language?: string; languages?: readonly string[] }
function browserLocale(): string | undefined { function browserLocale(): string | undefined {
@@ -78,14 +78,14 @@ export function formatPrice(
locale?: string, locale?: string,
): string { ): string {
if (price == null) return '—' 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 hasCents = !Number.isInteger(price)
const browser = locale ?? browserLocale() const browser = locale ?? browserLocale()
const country = countryOf(browser) const country = countryOf(browser)
const resolvedCurrency = currency ?? currencyForRegion(country) const resolvedCurrency = currency ?? currencyForRegion(country)
// Los separadores y la posición del símbolo siguen al país: un browser en // Separators and symbol position follow the country: an English browser in
// inglés en Argentina tiene que ver $50.000, no ARS 50,000. Con la locale // Argentina has to see $50.000, not ARS 50,000. When the locale is passed
// pasada explícita no se toca nada (tests, print). // explicitly nothing is touched (tests, print).
const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser
const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}` const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}`
@@ -103,27 +103,28 @@ export function formatPrice(
return tidyCurrencySpacing(formatter.format(price)) return tidyCurrencySpacing(formatter.format(price))
} }
/* Intl separa el símbolo de la moneda con un espacio duro: "$ 50.000" se lee /* Intl separates the currency symbol with a hard space: "$ 50.000" reads as two
como dos tokens sueltos. Lo quitamos solo cuando separa símbolo de número; loose tokens. We strip it only when it separates symbol from number; between
entre dígitos y código ("50.000 ARS") el no-break space evita el corte. */ digits and the code ("50.000 ARS") the non-breaking space prevents the
break. */
const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu
function tidyCurrencySpacing(value: string): string { function tidyCurrencySpacing(value: string): string {
return value.replace(SYMBOL_GAP, '$1') return value.replace(SYMBOL_GAP, '$1')
} }
/* ── Teléfonos ────────────────────────────────────────────────────────────── /* ── Phones ─────────────────────────────────────────────────────────────────
Presentación, nunca persistencia: los links wa.me siguen usando los dígitos Presentation, never persistence: the wa.me links still use the raw digits.
crudos. El formato sale de la región del propio número cuando su prefijo de The format comes from the region of the number itself when its country
país es reconocible; si el número es nacional, manda la región del browser prefix is recognizable; if the number is national, the browser's region wins
(y si esa región no la conocemos, la de la app: AR). Si nada encaja se cae (and if we don't know that region, the app's: AR). If nothing matches we fall
a E.164 (+331234567890) o al valor original, siempre preferible a un número back to E.164 (+331234567890) or to the original value, always preferable to
inventado. */ an invented number. */
type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX' 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 }[] = [ const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [
{ region: 'AR', code: '54' }, { region: 'AR', code: '54' },
{ region: 'ES', code: '34' }, { region: 'ES', code: '34' },
@@ -141,15 +142,15 @@ export function formatPhoneDisplay(
const hasPlus = raw.startsWith('+') const hasPlus = raw.startsWith('+')
let digits = raw.replace(/\D/g, '') 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') const hasDoubleZero = !hasPlus && raw.startsWith('00')
if (hasDoubleZero) digits = digits.slice(2) if (hasDoubleZero) digits = digits.slice(2)
if (digits.length < 6) return raw if (digits.length < 6) return raw
const withCallingCode = formatWithCallingCode(digits) const withCallingCode = formatWithCallingCode(digits)
if (withCallingCode) return withCallingCode if (withCallingCode) return withCallingCode
// Número de una región que no agrupamos: al menos se separa en bloques de a // Number from a region we don't group: at least it's split into groups of 3
// 3 para que no se lea como un muro de dígitos. El `+` se conserva si lo había. // so it doesn't read like a wall of digits. The `+` is kept if there was one.
if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}` if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}`
return ( 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 { function groupByThrees(digits: string): string {
const groups: string[] = [] const groups: string[] = []
let rest = digits let rest = digits
@@ -170,7 +171,7 @@ function groupByThrees(digits: string): string {
return groups.join(' ') 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 { function formatWithCallingCode(digits: string): string | null {
for (const { region, code } of COUNTRY_CALLING_CODES) { for (const { region, code } of COUNTRY_CALLING_CODES) {
if (!digits.startsWith(code)) continue if (!digits.startsWith(code)) continue
@@ -180,12 +181,12 @@ function formatWithCallingCode(digits: string): string | null {
return 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 { function appRegion(region: string | undefined): PhoneRegion {
if (region === 'US' || region === 'CA') return 'US' if (region === 'US' || region === 'CA') return 'US'
if (region === 'ES') return 'ES' if (region === 'ES') return 'ES'
if (region === 'MX') return 'MX' 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' return 'AR'
} }
@@ -210,12 +211,12 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
let national = digits let national = digits
let isMobile = false let isMobile = false
// Móvil argentino: 9 + 10 dígitos nacionales. // Argentine mobile: 9 + 10 national digits.
if (national.length === 11 && national.startsWith('9')) { if (national.length === 11 && national.startsWith('9')) {
national = national.slice(1) national = national.slice(1)
isMobile = true 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) { if (national.startsWith('0') && national.length >= 9) {
national = national.slice(1) national = national.slice(1)
withCountry = true withCountry = true
@@ -229,8 +230,8 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
function groupArNational(digits: string): string { function groupArNational(digits: string): string {
if (digits.length === 10) { if (digits.length === 10) {
// 11 es el único área de 2 dígitos (Gran Buenos Aires); el resto se // 11 is the only 2-digit area code (Gran Buenos Aires); the rest group
// agrupa 4-2-4, que es el patrón de las áreas de 4 dígitos. // 4-2-4, which is the pattern for 4-digit area codes.
return digits.startsWith('11') return digits.startsWith('11')
? `${digits.slice(0, 2)} ${digits.slice(2, 6)}-${digits.slice(6)}` ? `${digits.slice(0, 2)} ${digits.slice(2, 6)}-${digits.slice(6)}`
: `${digits.slice(0, 4)} ${digits.slice(4, 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 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 { function formatUsNational(digits: string): string | null {
if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1) if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1)
if (digits.length !== 10) return null if (digits.length !== 10) return null
if (digits[0] === '0' || digits[0] === '1' || digits[3] === '0' || digits[3] === '1') 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)}` 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 { function formatEsNational(digits: string, withCountry: boolean): string | null {
if (digits.length !== 9 || !'6789'.includes(digits[0])) return 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)}` const local = `${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 7)} ${digits.slice(7)}`
return withCountry ? `+34 ${local}` : local 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 { function formatMxNational(digits: string, withCountry: boolean): string | null {
if (digits.length !== 10 || digits[0] === '0' || digits[0] === '1') return 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)}` const local = `${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`
return withCountry ? `+52 ${local}` : local return withCountry ? `+52 ${local}` : local
} }
// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez // The due date is worded as a phrase ("Vence el día 10 de cada mes") instead of
// de "Vence día 10": se lee como una promesa, no como un dato suelto. // "Vence día 10": it reads as a promise, not as a bare fact.
export function formatBillingMeta( export function formatBillingMeta(
billingType: BillingType | null, billingType: BillingType | null,
dueDay: number | null, dueDay: number | null,

View File

@@ -1,11 +1,11 @@
/* Rutas "immersive": las que arman su propia barra de navegación con /* "Immersive" routes: the ones that build their own navigation bar with
`LargeTitle` (título grande que colapsa) y por eso no muestran el header `LargeTitle` (a large title that collapses) and therefore don't show the
global con logo + toggle de tema + avatar. global header with logo + theme toggle + avatar.
El patrón se resuelve a mano y no con `matchRoute` porque las dos rutas The pattern is resolved by hand and not with `matchRoute` because the two
llevan parámetros (`matchRoute` los exige) y porque las rutas hijas NO son routes carry params (`matchRoute` requires them) and because child routes are
immersive aunque compartan prefijo: `/groups/:id/attendees/new` sigue usando NOT immersive even when they share a prefix: `/groups/:id/attendees/new`
el header global. */ still uses the global header. */
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
['groups', ':id'], ['groups', ':id'],
@@ -13,9 +13,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
['class', ':id', 'attendance'], ['class', ':id', 'attendance'],
] ]
/* Rutas estáticas que ocupan el lugar de un parámetro. Sin esta lista /* Static routes that sit where a param would go. Without this list
`/groups/new` (crear grupo) se tomaría por una ficha de grupo y perdería el `/groups/new` (create group) would be taken for a group detail page and would
header global. */ lose the global header. */
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new']) const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
export function isImmersiveRoute(pathname: string) { export function isImmersiveRoute(pathname: string) {

View File

@@ -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á: The browser language says what language you're in, not what country you're
con "en-US" a alguien en Argentina lo trata como estadounidense, y con in: with "en-US" it treats someone in Argentina as American, and with
"es-419" no dice ningún país. La zona horaria —que sí expone el sistema— "es-419" it says no country at all. The time zone — which the system does
es la señal del país real; el idioma solo define cuando la zona no se expose — is the signal for the real country; the language only decides when
conoce. Con el país resuelto salen la moneda (REGION_CURRENCY) y la the time zone is unknown. With the country resolved you get the currency
regional con la que se formatea (REGION_LOCALE), para que un browser en (REGION_CURRENCY) and the locale it's formatted with (REGION_LOCALE), so an
inglés en Argentina vea $50.000 y no ARS 50,000. 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 → These maps are hand-written data (Intl exposes neither region → currency nor
locale). Solo definen cómo se PINTA un importe: el valor persistido no region → locale). They only define how an amount is RENDERED: the persisted
cambia ni se convierte. Si el país no está en ninguno, formatPrice cae al value doesn't change and isn't converted. If the country is in neither map,
símbolo $ genérico. */ formatPrice falls back to the generic $ symbol. */
export const REGION_CURRENCY: Record<string, string> = { export const REGION_CURRENCY: Record<string, string> = {
// Norteamérica // North America
CA: 'CAD', CA: 'CAD',
US: 'USD', US: 'USD',
// Latinoamérica y Caribe // Latin America and the Caribbean
AR: 'ARS', AR: 'ARS',
BO: 'BOB', BO: 'BOB',
BR: 'BRL', BR: 'BRL',
@@ -40,7 +40,7 @@ export const REGION_CURRENCY: Record<string, string> = {
UY: 'UYU', UY: 'UYU',
VE: 'VES', VE: 'VES',
// Zona euro // Eurozone
AT: 'EUR', AT: 'EUR',
BE: 'EUR', BE: 'EUR',
HR: 'EUR', HR: 'EUR',
@@ -62,7 +62,7 @@ export const REGION_CURRENCY: Record<string, string> = {
SI: 'EUR', SI: 'EUR',
ES: 'EUR', ES: 'EUR',
// Fuera de la zona euro // Outside the eurozone
CH: 'CHF', CH: 'CHF',
GB: 'GBP', GB: 'GBP',
CZ: 'CZK', CZ: 'CZK',
@@ -75,15 +75,15 @@ export const REGION_CURRENCY: Record<string, string> = {
UA: 'UAH', UA: 'UAH',
} }
/** Regional con la que se formatea para cada país. México y Argentina usan /** Locale each country is formatted with. Mexico and Argentina use different
separadores distintos (1,234.56 vs 1.234,56), así que el locale va con el separators (1,234.56 vs 1.234,56), so the locale follows the country and not
país y no solo con el idioma. */ just the language. */
export const REGION_LOCALE: Record<string, string> = { export const REGION_LOCALE: Record<string, string> = {
// Norteamérica // North America
CA: 'en-CA', CA: 'en-CA',
US: 'en-US', US: 'en-US',
// Latinoamérica y Caribe // Latin America and the Caribbean
AR: 'es-AR', AR: 'es-AR',
BO: 'es-BO', BO: 'es-BO',
BR: 'pt-BR', BR: 'pt-BR',
@@ -105,7 +105,7 @@ export const REGION_LOCALE: Record<string, string> = {
UY: 'es-UY', UY: 'es-UY',
VE: 'es-VE', VE: 'es-VE',
// Zona euro // Eurozone
AT: 'de-AT', AT: 'de-AT',
BE: 'nl-BE', BE: 'nl-BE',
HR: 'hr-HR', HR: 'hr-HR',
@@ -127,7 +127,7 @@ export const REGION_LOCALE: Record<string, string> = {
SI: 'sl-SI', SI: 'sl-SI',
ES: 'es-ES', ES: 'es-ES',
// Fuera de la zona euro // Outside the eurozone
CH: 'de-CH', CH: 'de-CH',
GB: 'en-GB', GB: 'en-GB',
CZ: 'cs-CZ', CZ: 'cs-CZ',
@@ -140,16 +140,16 @@ export const REGION_LOCALE: Record<string, string> = {
UA: 'uk-UA', 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 Coverage: the time zones of the countries above, grouped by prefix
(America/Argentina/*) o por la ciudad en la zona (Sao_Paulo). Cubre las (America/Argentina/*) or by the city in the zone (Sao_Paulo). It covers the
zonas principales; una zona desconocida cae al país del idioma. */ main zones; an unknown zone falls back to the country of the language. */
export const TIMEZONE_REGION: Record<string, string> = { export const TIMEZONE_REGION: Record<string, string> = {
// ── Latinoamérica ───────────────────────────────────────────────────────── // ── Latin America ─────────────────────────────────────────────────────────
'America/Argentina/': 'AR', 'America/Argentina/': 'AR',
// Chromium/ICU reporta en la forma legacy (sin el prefijo "Argentina/") las // Chromium/ICU reports the most common Argentine zones in the legacy form
// zonas argentinas más comunes: America/Argentina/Buenos_Aires → America/Buenos_Aires. // (without the "Argentina/" prefix): America/Argentina/Buenos_Aires → America/Buenos_Aires.
'America/Buenos_Aires': 'AR', 'America/Buenos_Aires': 'AR',
'America/Catamarca': 'AR', 'America/Catamarca': 'AR',
'America/Cordoba': 'AR', 'America/Cordoba': 'AR',
@@ -182,7 +182,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
'America/Santo_Domingo': 'DO', 'America/Santo_Domingo': 'DO',
'America/Puerto_Rico': 'PR', 'America/Puerto_Rico': 'PR',
// ── Norteamérica ───────────────────────────────────────────────────────── // ── North America ─────────────────────────────────────────────────────────
'America/New_York': 'US', 'America/New_York': 'US',
'America/Detroit': 'US', 'America/Detroit': 'US',
'America/Chicago': 'US', 'America/Chicago': 'US',
@@ -199,7 +199,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
'America/Regina': 'CA', 'America/Regina': 'CA',
'America/St_Johns': 'CA', 'America/St_Johns': 'CA',
// ── Europa ─────────────────────────────────────────────────────────────── // ── Europe ───────────────────────────────────────────────────────────────
'Europe/Madrid': 'ES', 'Europe/Madrid': 'ES',
'Atlantic/Canary': 'ES', 'Atlantic/Canary': 'ES',
'Atlantic/Faeroe': 'ES', 'Atlantic/Faeroe': 'ES',
@@ -244,8 +244,8 @@ export function regionForTimezone(timezone: string | undefined): string | undefi
return prefix ? TIMEZONE_REGION[prefix] : undefined return prefix ? TIMEZONE_REGION[prefix] : undefined
} }
/** Región del locale (es-MX → MX). Un locale sin país se maximiza, pero solo /** Region of the locale (es-MX → MX). A locale without a country is
como último recurso: countryOf prefiere la zona horaria. */ maximized, but only as a last resort: countryOf prefers the time zone. */
export function regionOf(locale: string | undefined): string | undefined { export function regionOf(locale: string | undefined): string | undefined {
if (!locale || typeof Intl.Locale === 'undefined') return undefined if (!locale || typeof Intl.Locale === 'undefined') return undefined
try { 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 /** The person's country: the one from the time zone and, when unknown, the one
idioma. `en` sin país no se maximiza a US a propósito: un usuario en from the language. A bare `en` is deliberately not maximized to US: a user in
México con el browser en inglés caería en dólares. */ Mexico with an English browser would end up in dollars. */
export function countryOf(locale: string | undefined): string | undefined { export function countryOf(locale: string | undefined): string | undefined {
return regionForTimezone(browserTimezone()) ?? regionOf(locale) return regionForTimezone(browserTimezone()) ?? regionOf(locale)
} }

View File

@@ -10,14 +10,14 @@ export default defineConfig({
react(), react(),
tailwindcss(), tailwindcss(),
VitePWA({ VitePWA({
// `autoUpdate` activa skipWaiting + clientsClaim: el SW nuevo toma el // `autoUpdate` turns on skipWaiting + clientsClaim: the new SW takes
// control en el próximo load sin pedirle nada al usuario. // control on the next load without asking the user for anything.
registerType: 'autoUpdate', registerType: 'autoUpdate',
// El registro se hace desde PwaProvider para poder avisar cuando la app // Registration is done from PwaProvider so we can tell the user when the
// ya está lista para operar sin conexión. // app is ready to work offline.
injectRegister: null, injectRegister: null,
// Los iconos ya entran por `workbox.globPatterns`; con // The icons already come in through `workbox.globPatterns`; with
// `includeManifestIcons` se listarían dos veces en el precache. // `includeManifestIcons` they would be listed twice in the precache.
includeManifestIcons: false, includeManifestIcons: false,
manifest: { manifest: {
name: 'Gruperly', name: 'Gruperly',
@@ -48,24 +48,26 @@ export default defineConfig({
], ],
}, },
workbox: { workbox: {
// El woff2 de Inter se importa desde node_modules: Vite lo emite a // Inter's woff2 is imported from node_modules: Vite emits it to
// assets/ con hash y entra al precache para que la app abra offline. // assets/ with a hash and it goes into the precache so the app opens
// offline.
globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'], globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'],
// Solo el script del SW queda fuera: precachearlo cachearía la versión // Only the SW script is left out: precaching it would cache the old
// vieja. El runtime `workbox-<hash>.js` sí se precachea a propósito, así // version. The `workbox-<hash>.js` runtime *is* precached on purpose, so
// el SW puede arrancar sin red. No usar `**/workbox-*.js`: ese patrón // the SW can boot without network. Do not use `**/workbox-*.js`: that
// también matchea `workbox-window.*.js`, que es el módulo cliente que // pattern also matches `workbox-window.*.js`, which is the client module
// importa `virtual:pwa-register` y sin él falla el registro. // that imports `virtual:pwa-register` and without it registration fails.
globIgnores: ['**/sw.js'], globIgnores: ['**/sw.js'],
// App shell para toda navegación, incluidas las rutas profundas // App shell for every navigation, including the deep routes
// /join/$token y /report-absence/$token. // /join/$token and /report-absence/$token.
navigateFallback: '/index.html', navigateFallback: '/index.html',
navigateFallbackDenylist: [/^\/api\//], navigateFallbackDenylist: [/^\/api\//],
cleanupOutdatedCaches: true, cleanupOutdatedCaches: true,
runtimeCaching: [ runtimeCaching: [
{ {
// La API nunca se cachea: son datos de cobros y una respuesta // The API is never cached: it holds payment data and a stale
// vieja sería peor que un error. Offline carga el shell, no los datos. // response is worse than an error. Offline loads the shell, not
// the data.
urlPattern: ({ url, request }) => request.method !== 'GET' || url.pathname.startsWith('/api/'), urlPattern: ({ url, request }) => request.method !== 'GET' || url.pathname.startsWith('/api/'),
handler: 'NetworkOnly', handler: 'NetworkOnly',
}, },

View File

@@ -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 # The public domain is exposed once, on `web`: nginx serves the Vite bundle and
# Vite y hace de proxy de /api hacia el contenedor `api`. Eso deja la cookie de # proxies /api to the `api` container. That keeps the session cookie
# sesión first-party (no hace falta SameSite=None) y vuelve innecesario el # first-party (no SameSite=None needed) and makes the CORS preflight
# preflight CORS. Si preferís subdominio aparte para la API, quitá el bloque # unnecessary. If you rather have the API on its own subdomain, drop the
# `location /api/` de apps/web/nginx.conf y seteá VITE_API_URL al construir web. # `location /api/` block from apps/web/nginx.conf and set VITE_API_URL when
# building web.
x-backend-env: &backend-env x-backend-env: &backend-env
NODE_ENV: production 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}" DATABASE_URL: "${DATABASE_URL:?falta DATABASE_URL}"
WEB_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" 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}" BETTER_AUTH_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}"
@@ -42,26 +43,26 @@ services:
dockerfile: Dockerfile.web dockerfile: Dockerfile.web
target: web target: web
args: 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:-} VITE_API_URL: ${VITE_API_URL:-}
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:
- api - api
ports: ports:
# Publicación en el host, solo para probar en local. En Dokploy el dominio # Host publishing, only for local testing. On Dokploy the domain goes to
# va al puerto 80 del contenedor: Traefik no pasa por el mapeo. # port 80 of the container: Traefik does not go through the mapping.
- "8080:80" - "8080:80"
networks: networks:
- default - default
# Dokploy agrega dokploy-network solo al servicio con dominio, así que hay # Dokploy adds dokploy-network only to the service with a domain, so it has
# que declararla explícitamente para que Traefik llegue a este contenedor. # to be declared explicitly for Traefik to reach this container.
- dokploy-network - dokploy-network
# Red compartida de Dokploy: es donde viven las bases de datos que administra # Dokploy shared network: that is where the databases Dokploy manages live.
# Dokploy. Sin esto, el contenedor api no resuelve ni alcanza a la base y Prisma # Without it, the api container neither resolves nor reaches the database and
# falla con P1001 "Can't reach database server". # 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 # docker network create dokploy-network
networks: networks:
dokploy-network: dokploy-network:

View File

@@ -1,99 +1,102 @@
import type { AttendanceRiskLevelDto, AttendanceStatus } from '../schemas/attendance.js'; import type { AttendanceRiskLevelDto, AttendanceStatus } from '../schemas/attendance.js';
/* Riesgo de abandono de un alumno, derivado del historial de asistencia. /* Dropout risk of an attendee, derived from the attendance history.
Vive en `shared` y no importa nada de UI: lo usan el resumen por grupo del It lives in `shared` and imports nothing from the UI: the backend's
backend, la tarjeta del listado y la sección de seguimiento del Inicio. 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 All the thresholds live here, in a single object. The rule is a business
("3 faltas seguidas = alguien se está yendo"), no de pantalla, así que un rule ("3 consecutive absences = someone is leaving"), not a screen rule, so
componente nunca debería escribir el número crudo. a component should never write the raw number.
── Qué clase se considera ──────────────────────────────────────────────── ── Which classes count ───────────────────────────────────────────────────
El modelo actual guarda la asistencia como `Attendance` (una fila por alumno The current model stores attendance as `Attendance` (one row per attendee
y clase, con `PRESENT` / `ABSENT` / `EXCUSED`) colgando de un `ClassSession` and class, with `PRESENT` / `ABSENT` / `EXCUSED`) hanging off a `ClassSession`
que tiene `startsAt`. No existe columna de "clase cancelada", así que las that has `startsAt`. There is no "class cancelled" column, so the two signals
dos señales de que una clase no computa son: that a class does not count are:
- `status: null` — la clase pasó y nadie registró asistencia. Sin dato no hay - `status: null` — the class happened and nobody recorded attendance. With
ni asistencia ni ausencia: no entra en el promedio y **corta** la racha (si no record there is neither attendance nor absence: it does not enter the
no, un alumno con una clase sin registrar entre dos faltas tendría una average and it **breaks** the streak (otherwise, an attendee with an
racha que nunca ocurrió). unrecorded class between two absences would have a streak that never
- `status: 'EXCUSED'` — el alumno avisó la ausencia con anticipación y le happened).
liberaron el lugar (`SlotRelease`). Es la clase que "no cuenta": corta la - `status: 'EXCUSED'` — the attendee gave notice ahead of time and the spot
racha igual que `PRESENT` y tampoco entra en el promedio. 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 Only the classes that (a) already happened, `startsAt <= now`, and (b) come
(b) son posteriores al alta del alumno, `startsAt >= enrolledAt`. Un alumno after the attendee's enrollment, `startsAt >= enrolledAt`, enter the
recién incorporado no es penalizado por clases en las que todavía no estaba computation. A newly enrolled attendee is not penalized for classes they
inscripto. */ were not enrolled in yet. */
/** El mismo tipo que valida `attendanceRiskLevelSchema` cuando el nivel viaja /** The same type `attendanceRiskLevelSchema` validates when the level travels
* por la API: una sola definición para el dominio y el transporte. */ * over the API: a single definition for both domain and transport. */
export type AttendanceRiskLevel = AttendanceRiskLevelDto; export type AttendanceRiskLevel = AttendanceRiskLevelDto;
/** /**
* Umbrales de la regla de riesgo. Mover estos números cambia el semáforo de * Thresholds of the risk rule. Moving these numbers changes the status light
* toda la app, así que son la única fuente: nada más los hardcodea. * across the whole app, so this is the only source: nothing else hardcodes
* them.
*/ */
export const ATTENDANCE_RISK_RULES = { 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, highAbsenceStreak: 3,
/** Faltas consecutivas sin justificar desde las cuales hay que mirar. */ /** Unexcused absences in a streak from which attention is needed. */
attentionAbsenceStreak: 2, 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, 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, trendWindowSize: 4,
/** Clases con dato necesarias para evaluar la tendencia. Con menos que esto /** Marked classes needed to evaluate the trend. With fewer than this
* (6 = 4 + 2) cualquier movimiento es ruido, no tendencia. */ * (6 = 4 + 2) any movement is noise, not a trend. */
trendMinClasses: 6, trendMinClasses: 6,
/** Cuántas clases hay que haber perdido entre una ventana y la otra para que /** How many classes have to be lost between one window and the other for
* la tendencia cuente como "claramente" a la baja. Se cuenta en clases y no * the trend to count as "clearly" dropping. Counted in classes and not in
* en puntos porcentuales a propósito: con ventana de 4 el salto más chico * percentage points on purpose: with a window of 4 the smallest possible
* posible ya es de 25 puntos, así que un umbral en puntos no distinguiría * jump is already 25 points, so a threshold in points would not tell
* "se le cayó una clase" de "se está yendo". Dos clases sí lo distingue. */ * "they missed a class" apart from "they are leaving". Two classes do. */
trendDropClasses: 2, trendDropClasses: 2,
} as const; } as const;
/** Una clase del grupo, vista desde un alumno. */ /** A class of the group, seen from one attendee. */
export type MemberClassSession = { export type MemberClassSession = {
sessionId: string; sessionId: string;
/** Instante real de la clase (ISO). */ /** Actual moment of the class (ISO). */
startsAt: string; 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; status: AttendanceStatus | null;
}; };
export type MemberAttendance = { export type MemberAttendance = {
attendeeId: string; attendeeId: string;
fullName: string; fullName: string;
/** Momento del alta en el grupo (`Attendee.createdAt`), ISO. */ /** Moment of enrollment in the group (`Attendee.createdAt`), ISO. */
enrolledAt: string; 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[]; sessions: MemberClassSession[];
}; };
export type GroupAttendanceInput = { export type GroupAttendanceInput = {
groupId: string; groupId: string;
/** `null` cuando el grupo no tiene cupo definido. */ /** `null` when the group has no capacity defined. */
capacity: number | null; capacity: number | null;
/** Miembros esperando cupo (`GroupWaitlistEntry` en PENDING). */ /** Members waiting for a spot (`GroupWaitlistEntry` in PENDING). */
waitlistCount: number; waitlistCount: number;
members: MemberAttendance[]; members: MemberAttendance[];
/** Momento de referencia. Por defecto `new Date()`. */ /** Reference moment. Defaults to `new Date()`. */
now?: Date; now?: Date;
}; };
export type MemberRiskSignals = { export type MemberRiskSignals = {
level: AttendanceRiskLevel; 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; consecutiveAbsences: number;
/** Días desde la última clase con presencia, o `null` si nunca asistió a /** Days since the last class with presence, or `null` if they never attended
* ninguna clase elegible. */ * any eligible class. */
daysSinceLastAttendance: number | null; 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; attendanceRate: number | null;
/** Clase con dato sobre las cuales se puede emitir un juicio. */ /** Marked classes a verdict can be based on. */
markedClasses: number; markedClasses: number;
}; };
@@ -106,23 +109,23 @@ export type GroupAttendanceSummary = {
riesgoAlto: number; riesgoAlto: number;
atencion: number; atencion: number;
ok: 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; libres: number;
/** Miembros esperando cupo. */ /** Members waiting for a spot. */
enEspera: number; enEspera: number;
/** Miembros que hay que mirar primero, ordenados de peor a mejor. */ /** Members to look at first, ordered worst to best. */
urgentes: UrgentMember[]; 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; 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; asistencia: number | null;
}; };
const DAY_MS = 24 * 60 * 60 * 1000; const DAY_MS = 24 * 60 * 60 * 1000;
/** /**
* Nivel de riesgo de un alumno. Es el atajo a `summarizeMemberAttendance` para * Risk level of an attendee. Shortcut to `summarizeMemberAttendance` for when
* cuando solo hace falta el semáforo. * only the status light is needed.
*/ */
export function getMemberAttendanceRisk( export function getMemberAttendanceRisk(
member: MemberAttendance, member: MemberAttendance,
@@ -131,31 +134,31 @@ export function getMemberAttendanceRisk(
return summarizeMemberAttendance(member, now).level; 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( export function summarizeMemberAttendance(
member: MemberAttendance, member: MemberAttendance,
now: Date = new Date(), now: Date = new Date(),
): MemberRiskSignals { ): MemberRiskSignals {
const sessions = eligibleSessions(member, now); const sessions = eligibleSessions(member, now);
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que la // `eligibleSessions` returns oldest to newest, so the streak is counted from
// racha se cuenta desde el final. PRESENT, EXCUSED y las clases sin registro // the end. PRESENT, EXCUSED and classes with no record break the chain: an
// cortan la cadena: una clase justificada o sin dato no es una falta más. // excused class or one with no record is not one more absence.
let consecutiveAbsences = 0; let consecutiveAbsences = 0;
for (let index = sessions.length - 1; index >= 0; index -= 1) { for (let index = sessions.length - 1; index >= 0; index -= 1) {
if (sessions[index].status !== 'ABSENT') break; if (sessions[index].status !== 'ABSENT') break;
consecutiveAbsences += 1; consecutiveAbsences += 1;
} }
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que // `eligibleSessions` returns oldest to newest, so "the last class with
// "la última clase con presencia" es la primera que aparece yendo desde el // presence" is the first one found walking from the end. (It walks backwards
// final. (Se recorre al revés y no con `findLast` porque el target del repo es // instead of using `findLast` because the repo targets ES2022 and that
// ES2022 y ese método es ES2023.) // method is ES2023.)
const lastAttendedAt = lastPresentAt(sessions); const lastAttendedAt = lastPresentAt(sessions);
// Si nunca asistió a ninguna clase elegible, la referencia es la última clase // If they never attended any eligible class, the reference is the last class
// que tuvo: "hace cuánto no lo vemos" sigue siendo cierto, y evita que un // they had: "how long have we not seen them" still holds, and it keeps an
// alumno con dos faltas de hace dos meses quede en verde para siempre. // attendee with two absences from two months ago from staying green forever.
const reference = lastAttendedAt ?? sessions.at(-1)?.startsAt; const reference = lastAttendedAt ?? sessions.at(-1)?.startsAt;
const daysSinceLastAttendance = reference const daysSinceLastAttendance = reference
? Math.floor((now.getTime() - new Date(reference).getTime()) / DAY_MS) ? 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( function classify(
consecutiveAbsences: number, consecutiveAbsences: number,
daysSinceLastAttendance: number | null, 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 * `libres` is clamped to 0 because the detail page counts every member, with
* filtro de estado: un grupo con más miembros que lugares (o con el cupo sin * no status filter: a group with more members than spots (or with no capacity
* definir) tiene 0 libres, nunca negativos. Un grupo vacío tiene los tres * defined) has 0 free, never negative ones. An empty group has all three counts
* conteos en 0, `libres` igual al cupo y `peorNivel` en `null`. * at 0, `libres` equal to the capacity and `peorNivel` at `null`.
*/ */
export function getGroupAttendanceSummary( export function getGroupAttendanceSummary(
group: GroupAttendanceInput, group: GroupAttendanceInput,
@@ -216,8 +219,8 @@ export function getGroupAttendanceSummary(
const riesgoAlto = urgentes.filter((member) => member.level === 'riesgo_alto').length; const riesgoAlto = urgentes.filter((member) => member.level === 'riesgo_alto').length;
const atencion = urgentes.filter((member) => member.level === 'atencion').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í // Part of the members already have a signal: the average is over the ones
// tienen. Los alumnos sin ninguna clase registrada no mueven la aguja. // that do. Attendees with no recorded class do not move the needle.
const rates = urgentes const rates = urgentes
.map((member) => member.attendanceRate) .map((member) => member.attendanceRate)
.filter((rate): rate is number => rate !== null); .filter((rate): rate is number => rate !== null);
@@ -237,10 +240,10 @@ export function getGroupAttendanceSummary(
asistencia, asistencia,
}; };
/* Orden de urgencia: peor nivel primero; dentro del mismo nivel, quien /* Urgency order: worst level first; within the same level, whoever has more
tiene más faltas seguidas, después quien hace más que no aparece, después consecutive absences, then whoever has gone the longest without showing
quien tiene menos asistencia. El nombre nunca desempata: dos personas con up, then whoever has the lower attendance. The name never breaks the tie:
la misma señal mantienen el orden en que llegaron. */ two people with the same signal keep the order they arrived in. */
function byUrgency(a: UrgentMember, b: UrgentMember): number { function byUrgency(a: UrgentMember, b: UrgentMember): number {
const level = levelWeight(b.level) - levelWeight(a.level); const level = levelWeight(b.level) - levelWeight(a.level);
if (level !== 0) return 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 * Attendance over the last 4 marked classes against the 4 before them. The
* declara la caída cuando hay historia para las dos ventanas: con una sola no * drop-off is only declared when there is history for both windows: with one
* hay contra qué comparar, y adivinar sería marcar alumnos que recién empiezan. * 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: * With a window of 4, the smallest non-zero difference is one class, which is
* por eso el umbral es de `trendDropClasses` clases perdidas y no de "cualquier * noise: that is why the threshold is `trendDropClasses` lost classes and not
* descenso". * "any decrease".
*/ */
function isDeclining(sessions: MemberClassSession[]): boolean { function isDeclining(sessions: MemberClassSession[]): boolean {
const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } = const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } =
ATTENDANCE_RISK_RULES; ATTENDANCE_RISK_RULES;
if (sessions.length < minClasses) return false; if (sessions.length < minClasses) return false;
// `sessions` viene de más antigua a más reciente, así que la ventana // `sessions` comes oldest to newest, so the recent window is the tail.
// reciente es la cola.
const recent = sessions.slice(-size); const recent = sessions.slice(-size);
const previous = sessions.slice(-size * 2, -size); const previous = sessions.slice(-size * 2, -size);
if (previous.length === 0 || recent.length === 0) return false; 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 { function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
for (let index = sessions.length - 1; index >= 0; index -= 1) { for (let index = sessions.length - 1; index >= 0; index -= 1) {
if (sessions[index].status === 'PRESENT') return sessions[index].startsAt; if (sessions[index].status === 'PRESENT') return sessions[index].startsAt;
@@ -288,7 +291,7 @@ function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
return 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[] { function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSession[] {
const enrolledAt = new Date(member.enrolledAt).getTime(); const enrolledAt = new Date(member.enrolledAt).getTime();
const nowMs = now.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()); .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 { function isMarked(session: MemberClassSession): boolean {
return session.status === 'PRESENT' || session.status === 'ABSENT'; return session.status === 'PRESENT' || session.status === 'ABSENT';
} }

View File

@@ -69,10 +69,10 @@ export type UpdateStudentStatusResult = z.output<typeof UpdateStudentStatusResul
export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']); export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']);
export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>; export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>;
/** Cuántos miembros van en la lista de urgentes del resumen. La tarjeta del /** How many members go in the summary's urgent list. The listing card only
* listado solo nombra al primero o dos; el detalle tiene su propia pantalla * names the first one or two; the detail page has its own at-risk students
* de alumnos en riesgo, así que el resumen no necesita arrastrar al grupo * screen, so the summary does not need to drag the whole group over the
* entero por la red. */ * network. */
export const URGENT_MEMBERS_LIMIT = 5; export const URGENT_MEMBERS_LIMIT = 5;
export const UrgentMemberSummarySchema = z.object({ export const UrgentMemberSummarySchema = z.object({
@@ -85,21 +85,22 @@ export const UrgentMemberSummarySchema = z.object({
}); });
export type UrgentMemberSummary = z.output<typeof UrgentMemberSummarySchema>; export type UrgentMemberSummary = z.output<typeof UrgentMemberSummarySchema>;
/* El nivel es el peor alumno del grupo; los dos contadores dicen por qué se /* The level is the worst attendee in the group; the two counters say why it
dispara, para que la lista pueda nombrar el motivo en vez de un "riesgo". fires, so the list can name the reason instead of a bare "risk". They are
Son disjuntos: un miembro con racha de faltas va solo en el primero, y el disjoint: a member with an absence streak lands only in the first, and the
segundo agrupa a los que solo cruzan por asistencia baja. */ second groups those who only cross over for low attendance. */
export const GroupRiskSummarySchema = z.object({ export const GroupRiskSummarySchema = z.object({
groupId: z.string(), groupId: z.string(),
groupName: z.string(), groupName: z.string(),
riskLevel: groupRiskLevelSchema, riskLevel: groupRiskLevelSchema,
absenceStreakCount: z.number().int().min(0), absenceStreakCount: z.number().int().min(0),
lowAttendanceCount: 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. /* What the listing card and the Home follow-up section consume. It comes
Sale de `getGroupAttendanceSummary` (packages/shared/src/lib/attendance-risk.ts), from `getGroupAttendanceSummary` (packages/shared/src/lib/attendance-risk.ts),
que ya recibe todo el historial en memoria: el resumen por nivel no se puede which already receives the whole history in memory: the per-level summary
derivar de los dos contadores de arriba, porque "ok" es la diferencia y los cannot be derived from the two counters above, because "ok" is the
lugares libres salen del cupo, no de la asistencia. */ difference and the free spots come from the capacity, not from
attendance. */
riesgoAlto: z.number().int().min(0), riesgoAlto: z.number().int().min(0),
atencion: z.number().int().min(0), atencion: z.number().int().min(0),
ok: z.number().int().min(0), ok: z.number().int().min(0),

View File

@@ -6,9 +6,9 @@ const isoDateTimeSchema = z.string().datetime();
export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']); export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']);
export type AttendanceStatus = z.output<typeof attendanceStatusSchema>; export type AttendanceStatus = z.output<typeof attendanceStatusSchema>;
/* Los tres niveles del semáforo de asistencia, en el orden de la regla (de /* The three levels of the attendance status light, in rule order (best to
mejor a peor). El dominio los usa como tipo y este schema los valida cuando worst). The domain uses them as a type and this schema validates them when
viajan por la API, así que hay una sola definición. */ they travel over the API, so there is a single definition. */
export const attendanceRiskLevelSchema = z.enum(['ok', 'atencion', 'riesgo_alto']); export const attendanceRiskLevelSchema = z.enum(['ok', 'atencion', 'riesgo_alto']);
export type AttendanceRiskLevelDto = z.output<typeof attendanceRiskLevelSchema>; export type AttendanceRiskLevelDto = z.output<typeof attendanceRiskLevelSchema>;

View File

@@ -9,9 +9,9 @@ const pageSchema = createPageSchema();
const pageSizeSchema = createPageSizeSchema(10); const pageSizeSchema = createPageSizeSchema(10);
const paginationSchema = createPaginationSchema(); const paginationSchema = createPaginationSchema();
/* Cuántas clases recientes viajan por miembro en el listado. Es el tamaño de la /* How many recent class sessions travel per member in the listing. This is the
tira de puntos del roster, no una ventana de análisis: la analítica pide size of the roster's dot strip, not an analysis window: analytics asks for
HISTORY_SESSIONS_LIMIT clases aparte. */ HISTORY_SESSIONS_LIMIT classes separately. */
export const RECENT_ATTENDANCE_LIMIT = 5; export const RECENT_ATTENDANCE_LIMIT = 5;
export const AttendeeDtoSchema = z.object({ export const AttendeeDtoSchema = z.object({
@@ -49,9 +49,9 @@ export const AttendeeQuerySchema = z.object({
export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>; export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>;
/** /**
* Cobro del período vigente, tal como está en la base: sin columna * Charge for the current period, as stored in the database: no denormalized
* desnormalizada y sin veredicto calculado. El backend devuelve el pago * column and no computed verdict. The backend returns the most recent unpaid
* impago más reciente; el cliente decide cómo presentarlo. * payment; the client decides how to present it.
*/ */
export const AttendeePaymentSummarySchema = z.object({ export const AttendeePaymentSummarySchema = z.object({
status: paymentStatusSchema, status: paymentStatusSchema,
@@ -60,15 +60,14 @@ export const AttendeePaymentSummarySchema = z.object({
export type AttendeePaymentSummary = z.output<typeof AttendeePaymentSummarySchema>; export type AttendeePaymentSummary = z.output<typeof AttendeePaymentSummarySchema>;
/** /**
* Item del listado de miembros: `AttendeeDto` más el resumen que la fila * Member listing item: `AttendeeDto` plus the summary the row needs so it does
* necesita para no vaciarse de datos. Es un superconjunto, así que todo * not run dry of data. It is a superset, so every consumer of the plain DTO
* consumidor del DTO plano sigue sirviéndose sin cambios; solo los listados * keeps working unchanged; only the listings see these two extra fields.
* verían estos dos campos extra.
*/ */
export const AttendeeListItemSchema = AttendeeDtoSchema.extend({ 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), 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(), payment: AttendeePaymentSummarySchema.nullable(),
}); });
export type AttendeeListItem = z.output<typeof AttendeeListItemSchema>; export type AttendeeListItem = z.output<typeof AttendeeListItemSchema>;

View File

@@ -1,6 +1,6 @@
import { z } from 'zod'; 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([ export const weekdaySchema = z.enum([
'MONDAY', 'MONDAY',
'TUESDAY', 'TUESDAY',
@@ -12,10 +12,10 @@ export const weekdaySchema = z.enum([
]); ]);
export type WeekDay = z.output<typeof weekdaySchema>; export type WeekDay = z.output<typeof weekdaySchema>;
// Procesadores de pago soportados. // Supported payment processors.
export const paymentProviderSchema = z.enum(['MERCADO_PAGO', 'STRIPE']); export const paymentProviderSchema = z.enum(['MERCADO_PAGO', 'STRIPE']);
export type PaymentProvider = z.output<typeof paymentProviderSchema>; export type PaymentProvider = z.output<typeof paymentProviderSchema>;
// Frecuencia de cobro de un grupo. // Billing frequency of a group.
export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']); export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']);
export type BillingType = z.output<typeof billingTypeSchema>; export type BillingType = z.output<typeof billingTypeSchema>;

View File

@@ -15,7 +15,7 @@ export const GroupDtoSchema = z.object({
createdById: z.string(), createdById: z.string(),
createdAt: isoDateTimeSchema, createdAt: isoDateTimeSchema,
updatedAt: 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(), days: z.array(weekdaySchema).nullable(),
time: z.string().nullable(), time: z.string().nullable(),
capacity: z.number().int().min(1).nullable(), capacity: z.number().int().min(1).nullable(),
@@ -45,11 +45,11 @@ export const InviteTokenResultSchema = z.object({
}); });
export type InviteTokenResult = z.output<typeof InviteTokenResultSchema>; export type InviteTokenResult = z.output<typeof InviteTokenResultSchema>;
/* En el listado cada grupo viaja con sus dos contadores de ocupación porque la /* In the listing every group travels with its two occupancy counters because
card los muestra: `attendeesCount` son los miembros del grupo (todos, igual the card shows them: `attendeesCount` are the group's members (all of them,
que cuenta el detalle) y `waitlistCount` los que están en lista de espera same as the detail page counts) and `waitlistCount` those on the waitlist
esperando cupo (PENDING). La lista de pre-inscriptos es otra cosa y no waiting for a spot (PENDING). The pre-registrations list is a different
entra acá. */ thing and does not belong here. */
export const GroupListItemSchema = GroupDtoSchema.extend({ export const GroupListItemSchema = GroupDtoSchema.extend({
attendeesCount: z.number().int().min(0), attendeesCount: z.number().int().min(0),
waitlistCount: z.number().int().min(0), waitlistCount: z.number().int().min(0),
@@ -59,7 +59,7 @@ export type GroupListItem = z.output<typeof GroupListItemSchema>;
export const GroupQuerySchema = z.object({ export const GroupQuerySchema = z.object({
page: pageSchema, page: pageSchema,
pageSize: pageSizeSchema, 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(), timeZone: timeZoneSchema.optional(),
}); });
export type GroupQuery = z.output<typeof GroupQuerySchema>; export type GroupQuery = z.output<typeof GroupQuerySchema>;

View File

@@ -5,10 +5,10 @@ import { GroupDtoSchema } from './groups.js';
export type { BillingType, PaymentProvider, WeekDay } from './enums.js'; export type { BillingType, PaymentProvider, WeekDay } from './enums.js';
export { billingTypeSchema, paymentProviderSchema, weekdaySchema } 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({ export const ConnectPaymentSchema = z.strictObject({
provider: paymentProviderSchema, 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), sandbox: z.boolean().default(true),
accessToken: z.string().optional(), accessToken: z.string().optional(),
}); });
@@ -21,7 +21,7 @@ export const ConnectPaymentResultSchema = z.object({
}); });
export type ConnectPaymentResult = z.output<typeof ConnectPaymentResultSchema>; export type ConnectPaymentResult = z.output<typeof ConnectPaymentResultSchema>;
// Paso 3: crea el primer grupo del profesor. // Step 3: create the teacher's first group.
export const CreateFirstGroupSchema = z.strictObject({ export const CreateFirstGroupSchema = z.strictObject({
name: z name: z
.string() .string()
@@ -64,7 +64,7 @@ export const CreateFirstGroupResultSchema = z.object({
}); });
export type CreateFirstGroupResult = z.output<typeof CreateFirstGroupResultSchema>; export type CreateFirstGroupResult = z.output<typeof CreateFirstGroupResultSchema>;
// 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 const onboardingStepSchema = z.enum(['NOT_STARTED', 'PAYMENT_CONNECTED', 'COMPLETED']);
export type OnboardingStep = z.output<typeof onboardingStepSchema>; export type OnboardingStep = z.output<typeof onboardingStepSchema>;