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:
@@ -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',
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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 = [
|
||||
{
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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 ? (
|
||||
|
||||
@@ -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',
|
||||
)}
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user