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

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

View File

@@ -6,21 +6,21 @@ import { useAttendeeDetail } from './AttendeeDetailProvider'
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'
/** 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
* regenerar el token de ausencias, así que la opción no se muestra antes que
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
* lista de abajo.
* For now it only holds "Quitar del grupo": the backend has no way to
* regenerate the absence token, so the option is not shown before that
* endpoint exists (see `apps/backend/prisma/models/domain.prisma`, field
* `notifyToken`). Once it does, it is one more `<button role="menuitem">` in
* the list below.
*
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
* The label goes in `text-primary` and the icon carries the `text-danger`: the
* `danger` red on white sits at 3.7:1 and does not reach AA for normal text. */
export function AttendeeActionsMenu({
triggerRef,
}: {
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
* foco cuando se cierra. */
/** The screen passes it in so the confirmation dialog can give focus back
* when it closes. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { openRemoveDialog } = useAttendeeDetail()

View File

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

View File

@@ -10,15 +10,15 @@ export function AttendeeContactActions() {
const phone = attendee?.phone
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 label = formatPhoneDisplay(phone) ?? phone
return (
<div className="flex gap-2.5">
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1.
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */}
{/* The icons go with `accent-fg` and not with `accent`: the `accent` blue is
the same in both themes and on dark `primary-soft` it sits at 2.2:1.
`accent-fg` gives 6.2:1 in light and 7.1:1 in dark. */}
<a
href={`https://wa.me/${digits}`}
target="_blank"

View File

@@ -2,19 +2,20 @@ import { Mail } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
/* `px-3` interno: la banda de hover sigue a sangre hasta el borde de la sección
(la separa del texto, no al revés) y las notas de abajo suman el mismo para
que el email y ellas caigan en la misma columna. */
/* Inner `px-3`: the hover band bleeds all the way to the section edge
(it separates from the text, not the other way around) and the notes below
add the same so the email and they land in the same column. */
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'
/** Email y notas del miembro. El teléfono no va acá: ya está en el subtítulo y
* detrás de los botones de WhatsApp y Llamar, y repetirlo llenaba la pantalla
* de un dato que ya estaba a la vista.
/** The attendee's email and notes. The phone does not go here: it is already in
* the subtitle, behind the WhatsApp and Llamar buttons, and repeating it filled
* 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".
* Aparece sola en cuanto el miembro tenga alguno (hoy el email puede llegar al
* aprobar una preinscripción; las notas, cuando exista la edición). */
* With no data the section is not drawn: there are no "Sin email"/"Sin notas"
* rows. It shows up on its own as soon as the attendee has one of them (today
* the email can arrive when approving a pre-registration; the notes, once
* editing exists). */
export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail()

View File

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

View File

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

View File

@@ -3,12 +3,12 @@ import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider'
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
* ya está a la vista detrás de los botones de WhatsApp y Llamar. Acá acompaña
* al "Miembro desde…", se copia con un toque y tiene 44px de alto aunque el
* texto sea de 14px: es un control, no un dato decorativo. */
* It used to live in a "Contacto" section with a single row that repeated the
* number already visible behind the WhatsApp and Llamar buttons. Here it sits
* next to "Miembro desde…", copies on one tap and is 44px tall even though the
* text is 14px: it is a control, not decorative data. */
export function AttendeePhoneLine() {
const { attendee } = useAttendeeDetail()
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"
>
<span className="truncate text-sm text-foreground">{label}</span>
{/* `aria-hidden`: la confirmación se anuncia desde la región viva de
abajo, así no se cuela en el nombre del botón. */}
{/* `aria-hidden`: the confirmation is announced from the live region
below, so it does not sneak into the button's name. */}
{copied ? (
<span
aria-hidden="true"

View File

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

View File

@@ -3,18 +3,18 @@ import type { ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { cn } from '../../lib/utils'
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
/* The grey has no opacity modifier: on the dark background `text-foreground/50`
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'
/* La fila que despliega la sección es un botón, no un título: por eso lleva
superficie de hover y presión, se pinta en `primary` para que se lea
distinta de los títulos fijos, y el chevron cae al borde derecho de la fila
en vez de pegado al texto.
/* The row that expands the section is a button, not a heading: that is why it
gets hover and press surfaces, it is painted in `primary` so it reads
different from the fixed titles, and the chevron lands on the row's right edge
instead of hugging the text.
El `px-3` es interno: la banda de hover sigue a sangre hasta el borde de la
sección y lo que se separa del borde es el contenido (el `px-3` del `h2` y
del `trailing` de abajo alinea rótulo y resumen con esta fila). */
The `px-3` is internal: the hover band bleeds all the way to the section edge
and it is the content that is set off from the edge (the `px-3` on the `h2`
and on the `trailing` below align the label and the summary with this row). */
const TOGGLE_ROW_CLASS = cn(
SECTION_TITLE_CLASS,
'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 = {
/** Título de la sección. Un string por lo general. */
/** The section title. Usually a string. */
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
/** Cuando está, el título entero es el disparador del contenido y `title` es
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el
* botón ocupa la fila completa. */
/** When present, the whole title is the content's trigger and `title` is just
* its label: the `<h2>` is still the section heading and the button takes the
* full row. */
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
children: ReactNode
}
/** Bloque de sección: separador fino sobre el fondo, título chico en
* mayúsculas y contenido sin padding propio (el de la pantalla).
/** Section block: thin separator over the background, small uppercase title and
* 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
* padding, así que el separador queda siempre a la misma distancia del
* contenido de arriba. Sumar otra sección (Pagos, por ejemplo) es insertar
* otro bloque y nada más. */
* The spacing lives here and not in the screen: every section closes with its
* own padding, so the separator always sits the same distance from the content
* above. Adding another section (Pagos, say) means inserting one more block and
* nothing else. */
export function Section({ title, trailing, toggle, children }: SectionProps) {
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">
<div className="flex items-center justify-between gap-3">
{toggle ? (
// El botón vive dentro del `<h2>`: el encabezado no se pierde y el
// disparador sigue siendo un control de verdad (Enter, Espacio y foco
// visible por teclado).
// The button lives inside the `<h2>`: the heading is not lost and the
// trigger is still a real control (Enter, Space and keyboard-visible
// focus).
<h2 id={headingId} className="min-w-0 flex-1">
<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
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
* `primary-soft` fill, which is the same filled surface the group detail uses:
* a thin border over `surface` is invisible in the light theme because
* `surface` and `background` are both white. 44px tall for the finger, and the
* same focus ring and press feedback as the app's `Button`. */
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'
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna:
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */
/** A panel's primary action (Enviar por WhatsApp). Same surface as the app's
* `primary` `Button` —`accent` fill with `on-accent` text, which gives 6.8:1 in
* both themes— but full width because it is alone in the column: next to the
* secondary one at 50% the long labels wrap onto two lines. */
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'

View File

@@ -1,8 +1,8 @@
import type { AttendanceHistoryItem } from '@gruperly/shared'
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
"Ver todas" no promete más de lo que hay. */
/* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
backend). It is the real ceiling on what this screen can show, so "Ver todas"
does not promise more than there is. */
export const HISTORY_PREVIEW = 5
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
están pensados como texto sobre superficies oscuras y el verde sobre blanco
queda justo por debajo de AA, así que la fila lleva las tres señales. */
/* The status is read through text and icon, not color alone: the status tokens
are meant as text over dark surfaces and the green on white sits just below
AA, so the row carries all three signals. */
export function attendanceStatusClass(status: AttendanceSession['status']): string {
switch (status) {
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 {
return new Date(iso).toLocaleDateString('es-MX', {
day: 'numeric',
@@ -59,9 +59,9 @@ export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases`
}
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
* contrario (más antigua → más reciente). */
/** What is displayed: from the most recent to the oldest, with the last
* `HISTORY_PREVIEW` as the preview. The endpoint returns the opposite order
* (oldest → most recent). */
export function visibleSessions(
sessions: AttendanceSession[],
showAll: boolean,
@@ -70,26 +70,27 @@ export function visibleSessions(
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
}
/** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las
* "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y
* meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */
/** Classes with a recorded attendance: attended, was absent or was absent with
* notice. The "Sin registrar" ones do not count: without a record there is
* neither attendance nor absence, and putting them in the denominator made
* "1 de 3" read as two absences. */
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
return sessions.filter((session) => session.status != null)
}
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
/** "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
}
/** Resumen de las filas que se están mostrando: cuántas clases registró la
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar.
/** Summary of the rows being shown: how many classes the person recorded out of
* how many have a record, and how many were left unmarked.
*
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo
* mismo dos veces. */
* The "sin registrar" text is dimmed when there is no marked class: the summary
* already says there is no data and the two texts would say the same thing
* twice. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
const marked = markedSessions(sessions)
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
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
/** Copies to the clipboard and confirms in the same spot where it was pressed,
* which is where the eye already is: a toast on top forces the view to hunt for
* the control again. */
export function useCopyToClipboard() {
const [copied, setCopied] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -24,8 +25,8 @@ export function useCopyToClipboard() {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
})
// Si el navegador rechaza la escritura no hay nada que confirmar: se
// deja el control como estaba en vez de dejar la promesa sin manejar.
// If the browser rejects the write there is nothing to confirm: the control
// is left as it was instead of leaving the promise unhandled.
.catch(() => setCopied(false))
}

View File

@@ -44,7 +44,8 @@ export function SignupPage() {
return
}
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 } })
}
})

View File

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

View File

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

View File

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

View File

@@ -82,8 +82,8 @@ export function GroupsView() {
) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
/* Un ícono solo, con un punto focal, y el texto en secundario: la
pantalla vacía compite con la acción y no puede ganar. */
/* A single icon, one focal point, and the text in secondary: the empty
state competes with the action and must not win. */
<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">
<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 [isDragging, setIsDragging] = useState(false)
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
// así que la página se monta sin spinner ni fetch duplicado.
// Same query keys as the group detail: the data is already in cache on
// navigation, so the page mounts with no spinner and no duplicated fetch.
const groupQuery = useQuery({
queryKey: ['group', groupId],
queryFn: () => getGroup(groupId),

View File

@@ -73,13 +73,14 @@ export function AnalyticsView() {
await navigator.clipboard.writeText(message)
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
} 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')
}
// El nombre suele estar en caché porque se llega desde la ficha del grupo: así
// el título grande aparece de entrada y no hay salto cuando cargan las queries.
// The group name is usually cached because the user comes from the group detail
// 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 groupName = riskQuery.data?.groupName ?? cachedGroupName
const analytics = analyticsQuery.data
@@ -87,14 +88,15 @@ export function AnalyticsView() {
const isPending = analyticsQuery.isPending || riskQuery.isPending
const hasFailed = analyticsQuery.isError || riskQuery.isError
// El contenido necesita los dos queries: sin `riskQuery` no hay ni el nombre
// del grupo ni la lista de alumnos en riesgo.
// The content needs both queries: without `riskQuery` there is neither the
// group name nor the list of attendees at risk.
const showContent = !isPending && !hasFailed && Boolean(analytics)
return (
<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
la barra y evita que el layout salte cuando llegan los datos. */}
{/* The large title always renders, even while loading: it is what gives
the bar its height and stops the layout from jumping when the data
arrives. */}
<LargeTitle
title={groupName ?? 'Grupo'}
leading={
@@ -108,9 +110,9 @@ export function AnalyticsView() {
</Link>
}
>
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el
título grande identifica el grupo y la barra colapsada lo muestra
para saber siempre sobre qué se está mirando. */}
{/* "Estadísticas" is the screen's subtitle, not its title: the large
title identifies the group and the collapsed bar keeps showing it so
you always know what you are looking at. */}
<div className="mt-2 flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<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'
/* Derivaciones de la tarjeta del listado de grupos. La tarjeta no consulta
nada: decide acá qué se ve, con qué tono y con qué peso visual, para que el
JSX solo arme el layout y las reglas se puedan testear sueltas.
/* Derivations for the group listing card. The card queries nothing: it decides
here what is shown, with what tone and with what visual weight, so the JSX only
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:
los trae `GET /groups-risk/overview`, que corre la misma función de dominio
(`getGroupAttendanceSummary` en packages/shared) que va a usar la sección de
seguimiento del Inicio. Acá solo se adapta esa respuesta a lo que la
tarjeta necesita pintar, y se decide cómo se lee. */
The per-level counts and the urgent attendees are not computed on the client:
they come from `GET /groups-risk/overview`, which runs the same domain function
(`getGroupAttendanceSummary` in packages/shared) that the follow-up section on
Home will use. Here we only adapt that response to what the card needs to paint,
and we decide how it reads. */
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
/** A partir de este cupo el indicador deja de ser un segmento por lugar y pasa
* a bloques proporcionales.
/** From this capacity on, the indicator stops being one segment per spot and
* switches to proportional blocks.
*
* El umbral lo fija el ancho, no una ronda. La barra tiene que entrar en la
* tarjeta de un teléfono: ~291px en un viewport de 402px, ya descontando el
* padding de `<main>`, el de la card y el label de ocupación. Con el gap de
* 6px, diez segmentos salen de ~24px cada uno: angosto pero todavía una
* píldora con su color. Ese número depende de dos decisiones de la card que no
* son obvio: el label dice "4/5" en móvil y no "4/5 miembros" (la palabra se
* llevaba ~60px), y el segmento reparte el ancho en vez de medir 50px fijos.
* Con cualquiera de las dos al revés, el cupo 10 vuelve a ser ilegible.
* The threshold is set by the width, not by a round number. The bar has to fit
* in a phone's card: ~291px on a 402px viewport, after discounting `<main>`'s
* padding, the card's and the occupancy label. With the 6px gap, ten segments
* come out at ~24px each: narrow but still a pill with its own color. That number
* depends on two card decisions that are not obvious: the label says "4/5" on
* mobile and not "4/5 miembros" (the word took ~60px), and the segment splits
* the width instead of measuring a fixed 50px. With either of the two the other
* way, capacity 10 becomes unreadable again.
*
* A partir del séptimo la píldora se angosta de a poco, y en un viewport de
* 320px el cupo 10 cae a ~15px, que ya se lee más como punto que como color.
* Se prefiere igual: ver qué lugar está libre y de qué nivel es cada uno sigue
* informando más que una barra proporcional, y el reparto flexible más el
* `overflow-hidden` garantizan que nunca se desborde la pantalla. */
* From the seventh on the pill narrows gradually, and on a 320px viewport
* capacity 10 drops to ~15px, which already reads more like a dot than a color.
* We prefer it anyway: seeing which spot is free and what level each one is still
* says more than a proportional bar, and the flexible split plus `overflow-hidden`
* guarantee it never overflows the screen. */
export const SEGMENTED_CAPACITY_MAX = 10
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(
members: GroupMember[],
@@ -75,11 +75,11 @@ export function capacityCountsFromMembers(
}
/**
* Reglas de texto de alerta a partir de los miembros:
* - 1 en riesgo alto: "{Nombre}: {N} faltas" + (si hay atención > 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"
* - 0 en riesgo alto pero atención > 0: "{K} en atención"
* - Ninguno: null
* Alert text rules derived from the members:
* - 1 at high risk: "{Nombre}: {N} faltas" + (if attention > 0) " · {K} en atención"
* - 2 or more at high risk: "{N} en riesgo alto" + (if attention > 0) " · {K} en atención"
* - 0 at high risk but attention > 0: "{K} en atención"
* - None: null
*/
export function alertTextFromMembers(members: GroupMember[]): string | null {
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
* para unificar la representación interna.
* Turns a GroupListItem and GroupRiskSummary into a list of GroupMember to unify
* the internal representation.
*/
export function membersFromGroupAndRisk(
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
* nombra a los que hay que mirar, y el resto de la matrícula es lo que queda
* bien. Se acota a 0 porque el resumen cuenta los miembros activos y la tarjeta
* muestra todos.
* `ok` is the remainder, not a number from the API: the risk summary only names
* the ones worth watching, and the rest of the roster is what is doing fine. It
* is clamped to 0 because the summary counts active members while the card shows
* all of them.
*
* Sin resumen todavía (o si la consulta falla) todos los miembros caen en `ok`.
* Es el estado en calma: el resumen puede seguir cargando y la tarjeta tiene
* que poder pintar igual.
* With no summary yet (or if the query fails) every member falls into `ok`. It is
* the calm state: the summary can still be loading and the card has to be able
* to paint anyway.
*/
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
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 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
* faltas. Con dos o más se resume por nivel. Cuando no hay nada que reportar,
* el componente omite esta línea por completo.
* With a single person at high risk it shows their name and absence count. With
* two or more it summarizes by level. When there is nothing to report, the
* component leaves this line out entirely.
*/
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
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
* medir a la matrícula, un segmento (o bloque) por miembro, con los lugares
* libres en cero. Un grupo sin cupo no tiene "lugares libres" que mostrar, pero
* sí tiene gente en riesgo, y esa es justo la señal que la barra existe para
* comunicar. Lo que sí desaparece es la barra de un grupo vacío: sin miembros no
* hay nada que repartir.
* When the group has no declared capacity the bar does not disappear: it goes on
* measuring the roster, one segment (or block) per member, with the free spots
* at zero. A group with no capacity has no "free spots" to show, but it does have
* people at risk, and that is exactly the signal the bar exists to communicate.
* What does disappear is the bar of an empty group: with no members there is
* nothing to split.
*/
export function barCapacity(group: GroupLike): number {
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 {
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 {
if (group.capacity === null) return membersLabel(group.attendeesCount)
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(
urgentes: UrgentMemberSummary[],
counts: CapacityCounts,
@@ -269,7 +269,7 @@ function namedHighRiskMember(
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 {
const partes: string[] = []
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
@@ -277,10 +277,11 @@ function countedLevels(counts: CapacityCounts): string {
return partes.join(' · ')
}
/* El motivo que mejor explica por qué alguien está en la línea de estado, en el
orden en que la regla los considera: primero la racha de faltas (algo que se
está yendo), después el tiempo sin aparecer, y por último la asistencia. Con
una sola falta y al día se devuelve null: no alcanza para nombrar a nadie. */
/* The reason that best explains why someone is on the status line, in the order
the rule considers them: first the streak of absences (something that is
going away), then the time since last showing up, and last the attendance
rate. With a single absence and ok it returns null: not enough to name
anyone. */
function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
@@ -290,8 +291,8 @@ function absenceReason(miembro: UrgentMemberSummary): string | null {
return null
}
/* Solo el primer nombre: en una línea de 360px "Sofía Ramírez: 4 faltas" no
entra, y entre dos personas con el mismo nombre la ficha las distingue. */
/* First name only: on a 360px line "Sofía Ramírez: 4 faltas" does not fit, and
between two people with the same name the detail page tells them apart. */
function firstName(fullName: string): string {
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 = [
{

View File

@@ -5,11 +5,11 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
MEDIUM: 'Riesgo moderado',
}
/* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla
(abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */
/* The badge only says "Riesgo moderado"; this sentence explains what it is about
(an attendee dropping out, not fraud or collections) and lives in the tooltip. */
export const RISK_HINT =
'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á:
vive en `card.ts`, que además decide el peso visual del badge. Esto quedó
con la copia estática de la ficha del grupo. */
/* The concrete reason ("4 members with consecutive absences") is not computed
here anymore: it lives in `card.ts`, which also decides the badge's visual
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 = {
groupId: string
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
groupQueryPending: boolean
riskLevel: GroupRiskLevel
@@ -50,7 +50,7 @@ type GroupDetailContextValue = {
whatsappMessage: string
searchFilter: string
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
setOverdueOnly: (value: boolean) => void
listSection: ListSection
@@ -96,8 +96,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
const [searchFilter, setSearchFilter] = useState('')
const [overdueOnly, setOverdueOnly] = useState(false)
// Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
// pestaña se limpian para no heredar un filtro sin coincidencias.
// The list's controls belong to the view that opened them: on a tab change
// they are cleared so as not to inherit a filter with no matches.
const setListSection = (value: ListSection) => {
setListSectionState(value)
setSearchFilter('')
@@ -286,14 +286,15 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
}
} 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')
}
// El título grande va siempre, incluso cargando: es lo que da altura a la
// barra immersive y evita que el layout salte. Al llegar desde la ficha del
// grupo el nombre ya está en caché; en la primera carga cae a "Grupo".
// The large title always renders, even while loading: it is what gives the
// immersive bar its height and stops the layout from jumping. Arriving from
// 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 groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'

View File

@@ -25,8 +25,9 @@ export function GroupDetailView() {
return (
<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
la barra immersive y evita que el layout salte cuando llegan los datos. */}
{/* The large title always renders, even while loading: it is what gives
the immersive bar its height and stops the layout from jumping when
the data arrives. */}
<GroupHeader />
{groupQueryPending ? (

View File

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

View File

@@ -7,10 +7,10 @@ import {
import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider'
/* Escala de la tarjeta: label 11 (etiqueta) · valor 16 (dato) · hero 24
(cupo). El cupo es lo único que se escanea de un vistazo, por eso es el
único que sube de nivel; el resto se lee en línea. El ritmo vertical está
apretado a propósito (~24px menos que antes) sin bajar la legibilidad. */
/* The card's scale: label 11 (label) · value 16 (data) · hero 24 (capacity). The
capacity is the only thing you scan at a glance, which is why it is the only
one that goes up a level; the rest is read inline. The vertical rhythm is
deliberately tight (~24px less than before) without hurting legibility. */
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'

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,12 +9,13 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a
`primary-soft`, el fondo de la fila, y el separador desaparecería. */}
{/* `border-foreground/10` and not `border`: in dark `--border` is the same
as `primary-soft`, the row's background, and the separator would
disappear. */}
<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="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="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span>
@@ -26,7 +27,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
<tr
key={entry.id}
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"
onClick={() => setSelectedPreRegistration(entry)}
onKeyDown={(e) => {
@@ -36,8 +38,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
}
}}
>
{/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
{/* `px-3` aligns the text with the chips and the search above: it is
the same 12px left axis across the whole section. */}
<td className="px-3 py-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">

View File

@@ -34,7 +34,8 @@ export function SectionChips() {
{SECTIONS.map((section) => {
const isActive = listSection === section.id
const count = counts[section.id]
// Ámbar solo cuando hay algo que decidir: pre-inscripciones por revisar.
// Amber only when there is something to decide: pre-registrations to
// review.
const isAttention = section.id === 'pending' && preRegistrationsTotal > 0
const Icon = section.icon
@@ -45,7 +46,7 @@ export function SectionChips() {
aria-pressed={isActive}
onClick={() => setListSection(section.id)}
className={cn(
// min-h-11 (44px): objetivo táctil mínimo de iOS/Android.
// min-h-11 (44px): minimum iOS/Android touch target.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold',
'transition-[background-color,color,border-color,box-shadow] duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',

View File

@@ -9,8 +9,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
{/* `border-foreground/10` y no `border`: en dark `--border` es igual a
`primary-soft`, el fondo de la fila, y el separador desaparecería. */}
{/* `border-foreground/10` and not `border`: in dark `--border` is the same
as `primary-soft`, the row's background, and the separator would
disappear. */}
<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="px-3 pb-1.5">Teléfono</th>
@@ -24,7 +25,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
<tr
key={entry.id}
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"
onClick={() => setSelectedWaitlistEntry(entry)}
onKeyDown={(e) => {
@@ -34,8 +36,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
}
}}
>
{/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
{/* `px-3` aligns the text with the chips and the search above: it is
the same 12px left axis across the whole section. */}
<td className="px-3 py-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">

View File

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

View File

@@ -2,12 +2,13 @@ import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'
import { PAYMENT_DUE_SOON_DAYS } from './constants'
/* La fila del listado no pide al backend juicios de presentación: pide los
datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los
días que faltan cambian según cuándo se mira, así que no pueden venir
guardados desde el servidor. */
/* The listing's row does not ask the backend for presentation verdicts: it asks
for the raw data (recent classes, current charge) and the text comes from
here. The days remaining change depending on when you look, so they cannot
come stored from the server. */
/** Días calendario entre dos fechas, sin horas: "vence el día 10" no tiene hora. */
/** Calendar days between two dates, without times: "due on the 10th" has no
* time of day. */
function calendarDaysBetween(from: Date, to: Date): number {
const startOf = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
@@ -20,15 +21,15 @@ export type PaymentState =
| { kind: 'overdue'; days: number }
/**
* Qué hay que marcarle al cobro en la fila.
* What to mark on the charge in the row.
*
* Devuelve `null` cuando no hay nada que avisar: o el miembro no tiene ningún
* cobro registrado, o el que tiene vence más adelante que la ventana de aviso y
* todavía no venció. No es lo mismo que "al día", que es un pago cerrado.
* Returns `null` when there is nothing to warn about: either the attendee has no
* recorded charge, or the one they have is due later than the warning window and
* has not expired yet. That is not the same as "ok", which is a closed payment.
*
* Un `PENDING` con vencimiento ya pasado cuenta como vencido, igual que un
* `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo
* actualiza a mano y la fila no puede depender de esa disciplina.
* A `PENDING` whose due date has already passed counts as overdue, same as an
* `OVERDUE`: the stored state often stays at PENDING until someone updates it by
* hand, and the row cannot depend on that discipline.
*/
export function resolvePaymentState(
payment: AttendeeListItem['payment'],
@@ -57,7 +58,7 @@ export function paymentStateLabel(state: PaymentState): string {
case 'settled':
return 'Al día'
case 'dueSoon':
// "Vence en 0 d" no es español de persona: hoy y mañana tienen palabras.
// "Vence en 0 d" is not natural Spanish: today and tomorrow have words.
if (state.days === 0) return 'Vence hoy'
if (state.days === 1) return 'Vence mañana'
return `Vence en ${state.days} d`
@@ -67,20 +68,20 @@ export function paymentStateLabel(state: PaymentState): string {
}
export type AttendanceSummary = {
/** Estados a dibujar, del más antiguo al más reciente. */
/** States to draw, from the oldest to the most recent. */
dots: AttendanceStatus[]
attended: number
recorded: number
/** "Sin clases aún" cuando no hay nada registrado. */
/** "Sin clases aún" when nothing is recorded. */
label: string
}
/** Los últimos puntos de clase registrados, contados sobre esa misma ventana. */
/** The last recorded class points, counted over that same window. */
export function summarizeAttendance(
recentAttendance: AttendanceStatus[],
): AttendanceSummary {
// La ventana la fija el backend; el corte final evita que una fila se alargue
// si el contrato llegara con más clases de las previstas.
// The window is set by the backend; the final cut prevents a row from getting
// longer if the contract ever delivers more classes than expected.
const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT)
const recorded = dots.length
@@ -97,7 +98,7 @@ export function summarizeAttendance(
}
}
/** Orden alfabético fijo del listado. */
/** The listing's fixed alphabetical order. */
export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number {
return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' })
}

View File

@@ -17,7 +17,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)
const { refresh } = useAuth()
const goToDashboard = () => {
// Revalida la caché (estado del onboarding, sesión, grupos) antes de redirigir.
// Revalidates the cache (onboarding state, session, groups) before redirecting.
void queryClient.invalidateQueries()
void refresh()
void navigate({ to: '/' })

View File

@@ -35,7 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const status = statusQuery.data
if (!status) return
// Si interrumpió después de conectar el cobro, retomamos en el paso del grupo.
// If they dropped out after connecting payments, we resume at the group step.
if (status.step === 'PAYMENT_CONNECTED') {
setStep((current) => (current === 0 ? 2 : current))
}

View File

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

View File

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

View File

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