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:
@@ -1,12 +1,12 @@
|
||||
#!/bin/sh
|
||||
# Entrypoint de producción del backend: aplica las migraciones y levanta el
|
||||
# servidor en el mismo contenedor.
|
||||
# Production entrypoint for the backend: applies the migrations and starts the
|
||||
# server in the same container.
|
||||
#
|
||||
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo
|
||||
# serían ~10MB por un shebang).
|
||||
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||
# installed (adding it would be ~10MB for a shebang).
|
||||
#
|
||||
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una
|
||||
# base ya migrada a mano o una que se gestiona fuera de este despliegue).
|
||||
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||
# a database already migrated by hand, or one managed outside this deployment).
|
||||
set -e
|
||||
|
||||
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||
@@ -18,8 +18,8 @@ else
|
||||
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||
i=1
|
||||
|
||||
# La base puede seguir arrancando cuando este contenedor ya empezó, y un
|
||||
# deploy suele convivir con un reinicio de Postgres.
|
||||
# The database may still be starting up when this container is already
|
||||
# running, and a deploy usually overlaps a Postgres restart.
|
||||
while [ "$i" -le "$attempts" ]; do
|
||||
if bun run db:deploy; then
|
||||
echo "migrate: listo"
|
||||
@@ -37,6 +37,6 @@ else
|
||||
done
|
||||
fi
|
||||
|
||||
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop`
|
||||
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma).
|
||||
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||
exec "$@"
|
||||
|
||||
@@ -27,7 +27,7 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|
||||
const normalizedPath = normalizePath(path);
|
||||
|
||||
// Aviso de ausencia con token personal del alumno (sin sesión).
|
||||
// Absence notice sent with the attendee's personal token (no session).
|
||||
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@ type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
|
||||
// Colores de marca (mismo sistema que la web: index.css de apps/web).
|
||||
// Brand colors (same system as the web app: index.css in apps/web).
|
||||
const BRAND_600 = '#2544ea'
|
||||
const TEXT_STRONG = '#0f172a'
|
||||
const TEXT_MUTED = '#475569'
|
||||
const ON_ACCENT = '#ffffff'
|
||||
const LINK_BG = BRAND_600
|
||||
|
||||
// Logotipo embebido como data URI para que los mails no dependan de hosting.
|
||||
// Logo embedded as a data URI so the emails don't depend on hosting.
|
||||
function loadLogoTypoDataUri(): string {
|
||||
try {
|
||||
const base64 = readFileSync(
|
||||
@@ -66,7 +66,7 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
// With no SMTP configured (dev) the flow still doesn't break: it only logs a warning
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
@@ -111,8 +111,8 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||
// Add implementations and switch between them with EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ import {
|
||||
} from '../../lib/risk';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
/* Cuántas clases se miran hacia atrás por alumno. Es el techo real del modelo:
|
||||
los `class_sessions` no se crean solos, se materializan cuando alguien entra
|
||||
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20
|
||||
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el
|
||||
porcentaje de asistencia que muestra la tarjeta. */
|
||||
/* How many classes we look back per attendee. That is the real ceiling of the
|
||||
model: `class_sessions` are not created on their own, they get materialized
|
||||
when someone opens "today's classes", so pulling years of rows makes no
|
||||
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
|
||||
the attendance rate the card shows. */
|
||||
const MEMBER_HISTORY_LIMIT = 20;
|
||||
|
||||
type GetGroupsRiskOverviewDeps = {
|
||||
@@ -42,7 +42,7 @@ type GroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
capacity: number | null;
|
||||
/** Los que todavía esperan cupo (`GroupWaitlistEntry` en PENDING). */
|
||||
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
||||
_count: { waitlist: number };
|
||||
};
|
||||
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||
@@ -54,10 +54,10 @@ type AttendanceRow = {
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
||||
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
|
||||
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
|
||||
// Risk status light summary per group for the group listing.
|
||||
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
|
||||
// any is at medium risk and NONE otherwise. The counters state the reason
|
||||
// (consecutive absences or low attendance) so the listing can name it.
|
||||
export class GetGroupsRiskOverview {
|
||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||
|
||||
@@ -92,10 +92,10 @@ export class GetGroupsRiskOverview {
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el
|
||||
historial completo del alumno, no sobre la ventana mensual. Sin recorte
|
||||
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`,
|
||||
sobre las clases del grupo y no sobre estas filas. */
|
||||
/* No date filter, as before: the status light streak counts over the
|
||||
attendee's full history, not over the monthly window. No cap either:
|
||||
the cut to the last 20 classes is done by `memberSessions`, over the
|
||||
group's classes and not over these rows. */
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: {
|
||||
@@ -118,9 +118,10 @@ export class GetGroupsRiskOverview {
|
||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||
|
||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
|
||||
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
|
||||
// a racha y aun así quedan por debajo del mínimo de asistencia.
|
||||
// Why there is risk, computed in the same pass: a member with an absence
|
||||
// streak counts in the first counter and only there; the second one
|
||||
// groups the members that don't reach a streak and are still below the
|
||||
// attendance minimum.
|
||||
const absenceStreakCountByGroup = new Map<string, number>();
|
||||
const lowAttendanceCountByGroup = new Map<string, number>();
|
||||
|
||||
@@ -169,14 +170,14 @@ export class GetGroupsRiskOverview {
|
||||
}
|
||||
|
||||
/**
|
||||
* El resumen por nivel que consumen la tarjeta del listado y la sección de
|
||||
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función
|
||||
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla
|
||||
* no tenga dos copias: una acá y otra en el cliente.
|
||||
* The per-level summary consumed by the listing card and the Home follow-up
|
||||
* section. It comes from `getGroupAttendanceSummary`, the same domain function
|
||||
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||
* copies: one here and another in the client.
|
||||
*
|
||||
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen
|
||||
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo
|
||||
* para pintar el indicador.
|
||||
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
|
||||
* summary counts the group members and the card needs the capacity slots to
|
||||
* paint the indicator.
|
||||
*/
|
||||
function buildSummaryFields(
|
||||
group: GroupRow,
|
||||
@@ -194,9 +195,9 @@ function buildSummaryFields(
|
||||
.filter((attendee) => attendee.groupId === group.id)
|
||||
.map((attendee) => {
|
||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
||||
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej.
|
||||
// creado hoy pero con clases pasadas registradas), su fecha efectiva de
|
||||
// incorporación es la de la primera clase a la que se le tomó asistencia.
|
||||
// If the attendee has attendances before their enrollment date in the
|
||||
// DB (e.g. created today but with past classes already recorded), their
|
||||
// effective join date is the first class they were marked for.
|
||||
const earliestAttendance = attendeeAttendances.reduce<Date | null>(
|
||||
(earliest, att) =>
|
||||
!earliest || att.classSession.startsAt < earliest
|
||||
@@ -257,18 +258,18 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
||||
return byAttendee;
|
||||
}
|
||||
|
||||
/* El universo de clases es el del grupo, no el de las filas de `Attendance`.
|
||||
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así
|
||||
que "esta clase pasó y no hay registro de este alumno" es un estado real y
|
||||
frecuente, no una falta. Si la lista se armara desde las filas de asistencia
|
||||
esas clases no existirían y la racha no se cortaría: dos faltas separadas por
|
||||
una clase sin marcar se contarían como tres seguidas.
|
||||
El dominio ya las trata como neutras (`status: null`), así que acá solo hay
|
||||
que elegir bien el universo y dejar el criterio en un solo lado.
|
||||
`sessions` viene de más reciente a más antigua, así que quedarse con las
|
||||
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El
|
||||
recorte va por alumno y no global para que un grupo con mucha historia no le
|
||||
robe ventana a los grupos que se listan después. */
|
||||
/* The universe of classes is the group's, not the `Attendance` rows'.
|
||||
Attendance is recorded attendee by attendee and only when someone marks a
|
||||
class, so "this class happened and this attendee has no record" is a real
|
||||
and frequent state, not an absence. If the list were built from the
|
||||
attendance rows those classes wouldn't exist and the streak wouldn't break:
|
||||
two absences separated by an unmarked class would count as three in a row.
|
||||
The domain already treats them as neutral (`status: null`), so all that is
|
||||
left here is to pick the right universe and keep the criterion on one side.
|
||||
`sessions` comes from most recent to oldest, so keeping the first
|
||||
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
|
||||
and not global, so a group with a long history doesn't steal window from
|
||||
the groups listed after it. */
|
||||
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
|
||||
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso.
|
||||
// Verifies the user is the group owner or a member. Returns the group if they have access.
|
||||
export async function findGroupForUser(
|
||||
db: AnalyticsAccessDb,
|
||||
groupId: string,
|
||||
|
||||
@@ -5,14 +5,14 @@ export type AttendanceStreamEntry = {
|
||||
|
||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||
|
||||
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
|
||||
/** Minimum streak of unexcused absences that already triggers risk. */
|
||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
||||
|
||||
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
|
||||
/** Monthly attendance (30-day window) below which there is risk. */
|
||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
||||
|
||||
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
|
||||
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
|
||||
// Counts the consecutive unexcused absences from the most recent class.
|
||||
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
|
||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
let streak = 0;
|
||||
for (const entry of entries) {
|
||||
@@ -24,7 +24,7 @@ export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
return streak;
|
||||
}
|
||||
|
||||
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
|
||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.status === 'PRESENT') {
|
||||
@@ -34,8 +34,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Porcentaje de asistencia sobre el total de sesiones del período.
|
||||
// Las sesiones sin registrar cuentan como no asistidas.
|
||||
// Attendance rate over the total number of sessions in the period.
|
||||
// Sessions with no record count as not attended.
|
||||
export function monthlyAttendanceRate(
|
||||
entries: AttendanceStreamEntry[],
|
||||
totalSessions: number,
|
||||
@@ -47,7 +47,7 @@ export function monthlyAttendanceRate(
|
||||
return Math.round((present / totalSessions) * 100);
|
||||
}
|
||||
|
||||
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%.
|
||||
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
|
||||
export function classifyRisk(
|
||||
consecutiveAbsences: number,
|
||||
monthlyRate: number,
|
||||
|
||||
@@ -41,7 +41,7 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Cargar teléfonos existentes del grupo
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
|
||||
@@ -18,18 +18,18 @@ export class ListAttendees {
|
||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con
|
||||
una petición por miembro. Ambas relaciones vienen acotadas a propósito:
|
||||
la tabla de pagos crece un renglón por mes y para siempre, y el listado
|
||||
solo necesita el estado actual de cada persona. */
|
||||
/* Each row's summary travels in the same query instead of being built
|
||||
with one request per member. Both relations are capped on purpose:
|
||||
the payments table grows one row per month forever, and the listing
|
||||
only needs each person's current state. */
|
||||
db.attendee.findMany({
|
||||
...(where ? { where } : {}),
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
// Por fecha de la clase, no por `markedAt`: marcar la asistencia
|
||||
// tarde no debe cambiar qué clase cuenta como reciente.
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
|
||||
@@ -14,7 +14,7 @@ export type AttendeeRecord = {
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
/** Item del listado con el resumen de asistencia y cobro ya resuelto. */
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
|
||||
payments: {
|
||||
@@ -39,15 +39,15 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
};
|
||||
}
|
||||
|
||||
/* El renglón que resume el cobro vigente. Si hay algo impago manda el de
|
||||
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos
|
||||
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada
|
||||
impago, el último pago cerrado sirve para marcar la fila como al día. */
|
||||
/* The row that summarizes the current charge. If something is unpaid the
|
||||
oldest due date wins: someone carrying an old charge has to see how many
|
||||
days late they are, not the due date of a new charge. If nothing is left
|
||||
unpaid, the last closed payment serves to mark the row as ok. */
|
||||
function pickRelevantPayment(
|
||||
payments: AttendeeListItemRecord['payments'],
|
||||
): AttendeeListItem['payment'] {
|
||||
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos
|
||||
// acá también evita que un cargo anulado gane la fila por ser el más antiguo.
|
||||
// CANCELLED is not a charge. The query already filters them out, but dropping
|
||||
// them here too keeps a voided charge from winning the row for being the oldest.
|
||||
const byDueDate = payments
|
||||
.filter((payment) => payment.status !== 'CANCELLED')
|
||||
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
|
||||
@@ -60,8 +60,8 @@ function pickRelevantPayment(
|
||||
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
|
||||
}
|
||||
|
||||
/* La consulta viene en orden descendente; la fila los muestra de más antigua a
|
||||
más reciente para que el punto de la derecha sea el último hecho. */
|
||||
/* The query comes in descending order; the row shows them from oldest to most
|
||||
recent so the dot on the right is the latest event. */
|
||||
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
@@ -71,8 +71,8 @@ export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeL
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||
* Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
|
||||
* Keeps a leading '+' for international numbers.
|
||||
*/
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal.
|
||||
// Public route (whitelisted in session-auth): the attendee gets in with their personal token.
|
||||
route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
|
||||
const query = c.req.valid('query') as AbsenceQuery;
|
||||
const useCase = new GetAbsenceDetails();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token.
|
||||
// Public route (whitelisted in session-auth): the attendee reports an absence with a token.
|
||||
route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
|
||||
const payload = c.req.valid('json') as PublicNotifyAbsence;
|
||||
const useCase = new PublicNotifyAbsenceUseCase();
|
||||
|
||||
@@ -18,8 +18,8 @@ type PaymentLike = {
|
||||
dueDate: Date;
|
||||
};
|
||||
|
||||
// Estado de cobro calculado en tiempo real (sin columna denormalizada):
|
||||
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó.
|
||||
// Payment status computed in real time (no denormalized column):
|
||||
// PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
|
||||
export function resolvePaymentStatus(
|
||||
payments: PaymentLike[],
|
||||
startOfToday: Date,
|
||||
@@ -52,7 +52,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión.
|
||||
// Verifies the user is the owner or a member of the group that owns the session.
|
||||
export function ensureSessionAccess(
|
||||
session: ClassSessionRecord & { group: GroupWithAccess },
|
||||
userId: string,
|
||||
|
||||
@@ -17,9 +17,9 @@ type RegisterAbsenceInput = {
|
||||
releaseHours: number;
|
||||
};
|
||||
|
||||
// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token):
|
||||
// - Marca la asistencia como EXCUSED (upsert idempotente).
|
||||
// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo.
|
||||
// Shared core of the absence notice (authenticated teacher and attendee with a token):
|
||||
// - Marks the attendance as EXCUSED (idempotent upsert).
|
||||
// - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot.
|
||||
export async function registerAbsence(
|
||||
deps: RegisterAbsenceDeps,
|
||||
input: RegisterAbsenceInput,
|
||||
|
||||
@@ -13,7 +13,7 @@ type ScheduledGroup = {
|
||||
time: string | null;
|
||||
};
|
||||
|
||||
// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor).
|
||||
// Computes which groups have a class today (from days/time and the teacher's time zone).
|
||||
export function buildTodayCandidates(
|
||||
groups: ScheduledGroup[],
|
||||
now: Date,
|
||||
@@ -37,7 +37,7 @@ export function buildTodayCandidates(
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids.
|
||||
// Materializes (idempotent upsert) today's ClassSession rows and returns their ids.
|
||||
export async function ensureTodaySessions(
|
||||
db: Pick<ClassesDb, 'classSession'>,
|
||||
candidates: TodaySessionCandidate[],
|
||||
|
||||
@@ -24,9 +24,9 @@ type ListGroupsDeps = {
|
||||
const OCCUPANCY_COUNT_INCLUDE = {
|
||||
_count: {
|
||||
select: {
|
||||
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
|
||||
// Group members. No status filter, same as the detail page counts.
|
||||
attendees: true,
|
||||
// Lista de espera: los que todavía esperan cupo (los revisados salen).
|
||||
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
|
||||
waitlist: { where: { status: 'PENDING' as const } },
|
||||
},
|
||||
},
|
||||
@@ -43,10 +43,10 @@ export class ListGroups {
|
||||
const now = this.deps.now ?? new Date();
|
||||
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
||||
|
||||
// Traemos los grupos del usuario con sus contadores y los ordenamos acá:
|
||||
// la próxima clase se deriva de días + hora, no hay columna por la que
|
||||
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la
|
||||
// zona horaria de la persona (o la del servidor si no viaja).
|
||||
// We fetch the user's groups with their counters and sort them here: the next
|
||||
// class is derived from days + time, there is no column to sort on in the
|
||||
// database. It's the same engine the home summary uses, with the person's
|
||||
// time zone (or the server's if it doesn't come along).
|
||||
const records: GroupListRecord[] = await db.group.findMany({
|
||||
where,
|
||||
include: OCCUPANCY_COUNT_INCLUDE,
|
||||
@@ -58,9 +58,9 @@ export class ListGroups {
|
||||
nextAt: nextOccurrenceAt(record, now, timeZone),
|
||||
}));
|
||||
|
||||
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
|
||||
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
|
||||
que era el criterio anterior de la lista. */
|
||||
/* A group with no schedule has no class to compare, so it goes last;
|
||||
between groups with the same class (or with no schedule) the newest one
|
||||
breaks the tie, which was the listing's previous criterion. */
|
||||
const ordered = withNextClass.sort((a, b) => {
|
||||
if (a.nextAt !== null && b.nextAt !== null) {
|
||||
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();
|
||||
|
||||
@@ -21,10 +21,10 @@ export type GroupRecord = {
|
||||
inviteToken?: string | null;
|
||||
};
|
||||
|
||||
/* El listado suma los contadores de ocupación a cada grupo para que la card los
|
||||
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma
|
||||
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de
|
||||
espera solo los que siguen esperando cupo (PENDING). */
|
||||
/* The listing adds the occupancy counters to each group so the card can show
|
||||
them without asking for one endpoint per group. They come from the `_count` of
|
||||
the same query: all the members (same as the detail page counts) and only the
|
||||
waitlist entries still waiting for a spot (PENDING). */
|
||||
export type GroupListRecord = GroupRecord & {
|
||||
_count?: { attendees: number; waitlist: number };
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { WeekDay } from '@gruperly/shared';
|
||||
|
||||
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City';
|
||||
|
||||
// Ventana (en horas) durante la que una clase ya arrancada se muestra como "en curso".
|
||||
// Window (in hours) during which an already started class shows as "in progress".
|
||||
export const CLASS_WINDOW_HOURS = 2;
|
||||
export const CLASS_WINDOW_MS = CLASS_WINDOW_HOURS * 60 * 60 * 1000;
|
||||
|
||||
@@ -21,7 +21,7 @@ export type NextClassOccurrence = {
|
||||
isNow: boolean;
|
||||
};
|
||||
|
||||
// Convierte un tiempo de "pared" (wall clock) expresado en `timeZone` al instante absoluto.
|
||||
// Converts a "wall clock" time expressed in `timeZone` into the absolute instant.
|
||||
export function zonedWallClockToUtc(wall: string, timeZone: string): Date {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall);
|
||||
if (!match) {
|
||||
@@ -145,8 +145,8 @@ function pad(value: number): string {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
// Instante absoluto de la clase de HOY (aunque la hora ya haya pasado), o null si el grupo
|
||||
// no tiene clase programada para el día de `now` en `timeZone`.
|
||||
// Absolute instant of TODAY's class (even if the time has already passed), or null if the
|
||||
// group has no class scheduled for `now`'s day in `timeZone`.
|
||||
export function todayOccurrence(opt: {
|
||||
days: WeekDay[];
|
||||
time: string;
|
||||
@@ -181,7 +181,7 @@ export function todayOccurrence(opt: {
|
||||
return zonedWallClockToUtc(wall, timeZone);
|
||||
}
|
||||
|
||||
// Primer instante del día de `now` en `timeZone` (medianoche local).
|
||||
// First instant of `now`'s day in `timeZone` (local midnight).
|
||||
export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
|
||||
const { year, month, day } = wallDateInTimeZone(now, timeZone);
|
||||
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
|
||||
|
||||
@@ -78,8 +78,8 @@ describe('GET /groups-risk/overview', () => {
|
||||
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// `toMatchObject` porque el item ahora arrastra también el resumen por nivel
|
||||
// que consume la tarjeta; acá se está probando el semáforo de siempre.
|
||||
// `toMatchObject` because the item now also carries the per-level summary
|
||||
// the card consumes; here we are testing the usual status light.
|
||||
expect(await res.json()).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
@@ -117,21 +117,21 @@ describe('GET /groups-risk/overview', () => {
|
||||
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
|
||||
]);
|
||||
prismaFetchAttendanceFindMany([
|
||||
// Dos faltas seguidas: cuenta en el motivo de faltas.
|
||||
// Two consecutive absences: counts toward the absence reason.
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'PRESENT', at(3)),
|
||||
// Sin racha, pero asiste menos de la mitad de las clases del mes.
|
||||
// No streak, but attends less than half of the month's classes.
|
||||
attendance('a-2', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-2', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-2', 's3', 'ABSENT', at(3)),
|
||||
attendance('a-2', 's4', 'ABSENT', at(4)),
|
||||
// Al día.
|
||||
// Ok.
|
||||
attendance('a-3', 's1', 'PRESENT', at(1)),
|
||||
attendance('a-3', 's2', 'PRESENT', at(2)),
|
||||
attendance('a-3', 's3', 'PRESENT', at(3)),
|
||||
attendance('a-3', 's4', 'PRESENT', at(4)),
|
||||
// Otra vez por racha, en el otro grupo.
|
||||
// Again via streak, in the other group.
|
||||
attendance('b-1', 's5', 'ABSENT', at(1)),
|
||||
attendance('b-1', 's6', 'ABSENT', at(2)),
|
||||
]);
|
||||
@@ -160,9 +160,9 @@ describe('GET /groups-risk/overview', () => {
|
||||
});
|
||||
});
|
||||
|
||||
/* Lo que consume la tarjeta del listado. El semáforo de arriba ya tenía sus
|
||||
tests; lo que faltaba era fijar el payload nuevo contra el mismo endpoint,
|
||||
porque es el contrato que el frontend lee. */
|
||||
/* What the listing card consumes. The status light above already had its
|
||||
tests; what was missing was pinning the new payload against the same
|
||||
endpoint, because that is the contract the frontend reads. */
|
||||
it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
|
||||
prismaFetchAttendeeFindMany([
|
||||
@@ -175,10 +175,10 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// El mock ignora el `orderBy`, así que las filas van de la más reciente a la
|
||||
// más antigua como las devolvería Prisma: de ese orden depende la racha.
|
||||
// `at(n)` son n días hacia atrás; el resumen descarta lo que no ocurrió, así
|
||||
// que las fechas tienen que estar en el pasado y no en el futuro.
|
||||
// The mock ignores `orderBy`, so the rows come most recent first, as Prisma
|
||||
// would return them: the streak depends on that order.
|
||||
// `at(n)` is n days back; the summary drops what has not happened yet, so
|
||||
// the dates have to be in the past, not in the future.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
@@ -197,11 +197,11 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
riesgoAlto: 1,
|
||||
atencion: 1,
|
||||
ok: 1,
|
||||
// El cupo es de 5 y hay 3 miembros, no 2: los lugares libres se calculan
|
||||
// contra el cupo y no como "los que no tienen ninguna señal".
|
||||
// Capacity is 5 and there are 3 members, not 2: free spots are computed
|
||||
// against capacity, not as "the ones with no signal at all".
|
||||
libres: 2,
|
||||
enEspera: 2,
|
||||
// Promedio de las tasas ya redondeadas por persona: 0, 33 y 100 → 44.
|
||||
// Average of the already-rounded per-person rates: 0, 33 and 100 → 44.
|
||||
asistencia: 44,
|
||||
});
|
||||
expect(items[0].urgentes).toEqual([
|
||||
@@ -218,8 +218,8 @@ it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo',
|
||||
fullName: 'Diego Soto',
|
||||
level: 'atencion',
|
||||
consecutiveAbsences: 2,
|
||||
// Cuenta desde su última clase con presencia, no desde la más
|
||||
// reciente del grupo: la suya fue hace 3 días.
|
||||
// Counted from their last class they attended, not from the group's
|
||||
// most recent one: theirs was 3 days ago.
|
||||
daysSinceLastAttendance: 3,
|
||||
attendanceRate: 33,
|
||||
},
|
||||
@@ -267,9 +267,9 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// Falta, clase sin marcar, falta. Leyendo solo las filas de `Attendance` esto
|
||||
// parecería una racha de 2 y el grupo saldría en atención; la clase del medio
|
||||
// pasó y no tiene registro, así que la racha real es de 1.
|
||||
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
|
||||
// would look like a streak of 2 and the group would land in attention; the
|
||||
// middle class happened and has no record, so the real streak is 1.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
@@ -289,7 +289,7 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
|
||||
level: 'ok',
|
||||
consecutiveAbsences: 1,
|
||||
daysSinceLastAttendance: 1,
|
||||
// Las dos clases con dato fueron falta; la del medio no entra al promedio.
|
||||
// Both marked classes were absences; the middle one does not go into the average.
|
||||
attendanceRate: 0,
|
||||
},
|
||||
]);
|
||||
@@ -303,9 +303,9 @@ it('las faltas pegadas hasta la última clase sí cuentan como racha', async ()
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// La racha se cuenta hacia atrás desde la clase más reciente, así que llegan
|
||||
// justo hasta el final: s1 y s2 pegadas, y la de hace 3 días sin registrar,
|
||||
// que queda antes de la racha y no la toca.
|
||||
// The streak is counted backwards from the most recent class, so they reach
|
||||
// exactly the end: s1 and s2 back to back, and the one 3 days ago is
|
||||
// unmarked, which falls before the streak and does not touch it.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's1', 'ABSENT', at(1)),
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
@@ -336,10 +336,11 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
|
||||
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
|
||||
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
|
||||
]);
|
||||
// Mismas dos faltas pegadas del caso anterior, pero la clase más reciente
|
||||
// (s1) es la que no tiene registro. Como la racha se cuenta desde el final y
|
||||
// "sin dato" no es ausencia, no hay racha: se ve la asimetría a propósito,
|
||||
// porque es lo mismo que ya pasa con una clase justificada.
|
||||
// The same two back-to-back absences as the previous case, but the most
|
||||
// recent class (s1) is the one with no record. Since the streak is counted
|
||||
// from the end and "no record" is not an absence, there is no streak: the
|
||||
// asymmetry is there on purpose, because it is the same thing that already
|
||||
// happens with an excused class.
|
||||
prismaFetchAttendanceFindMany([
|
||||
attendance('a-1', 's2', 'ABSENT', at(2)),
|
||||
attendance('a-1', 's3', 'ABSENT', at(3)),
|
||||
@@ -366,7 +367,7 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
|
||||
|
||||
it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
|
||||
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]);
|
||||
// El alumno fue creado hoy (offset 0), pero tiene 3 faltas en clases de hace 7, 3 y 1 días.
|
||||
// The attendee was created today (offset 0), but has 3 absences in classes 7, 3 and 1 days ago.
|
||||
prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
|
||||
prismaFetchClassSessionFindMany([
|
||||
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
|
||||
@@ -388,10 +389,10 @@ it('reconoce asistencias previas a la fecha de alta del alumno como historial v
|
||||
expect(items[0].absenceStreakCount).toBe(1);
|
||||
});
|
||||
|
||||
/* El use-case pide `capacity` y el conteo de lista de espera para poder calcular
|
||||
los lugares libres, y `fullName` + `createdAt` de cada alumno para el resumen
|
||||
por nivel. Los fixtures los dan para que los tests viejos no tengan que
|
||||
saber de eso. */
|
||||
/* The use-case asks for `capacity` and the waitlist count to compute the
|
||||
free spots, and `fullName` + `createdAt` of every attendee for the per-level
|
||||
summary. The fixtures provide them so the older tests don't have to know
|
||||
about that. */
|
||||
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
|
||||
return { id, name, capacity, _count: { waitlist: waiting } };
|
||||
}
|
||||
@@ -416,9 +417,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
|
||||
db.attendance.findMany.mockResolvedValue(rows);
|
||||
}
|
||||
|
||||
/* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo
|
||||
con las filas de asistencia, y sin ese cruce toda clase quedaría sin registro
|
||||
para todo el mundo. */
|
||||
/* The `classSessionId` matters: the summary is built by cross-referencing the
|
||||
group's class sessions with the attendance rows, and without that join every
|
||||
class would have no record for everyone. */
|
||||
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
|
||||
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
|
||||
}
|
||||
@@ -8,30 +8,29 @@ import {
|
||||
summarizeMemberAttendance,
|
||||
} from '@gruperly/shared';
|
||||
|
||||
/* La regla de riesgo es de negocio, no de pantalla: estos tests la fijan para
|
||||
que cambiar un umbral o refactorizar el filtro de clases no mueva el
|
||||
semáforo de la lista de grupos en silencio.
|
||||
/* The risk rule is business logic, not a screen concern: these tests pin it so
|
||||
that changing a threshold or refactoring the class filter doesn't quietly
|
||||
move the status light of the group list.
|
||||
|
||||
Dos helpers de armazón:
|
||||
Two test-scaffold helpers:
|
||||
|
||||
- `dense` mete las clases en días consecutivos, para que "hace cuánto no lo
|
||||
vemos" quede siempre cerca y el caso aísle la regla que dice probar (una
|
||||
clase por semana haría saltar el umbral de inactividad en casi todo).
|
||||
- `series` respeta los offsets que se le pasan, para los casos que sí
|
||||
necesitan huecos.
|
||||
- `dense` puts the classes on consecutive days, so that "how long since we
|
||||
saw them" is always close by and the case isolates the rule it claims to
|
||||
test (one class a week would trip the inactivity threshold almost always).
|
||||
- `series` honors the offsets it is given, for the cases that do need gaps.
|
||||
|
||||
Todas las fechas se cuelgan de un `NOW` fijo: la función recibe el momento
|
||||
como argumento justamente para poder testear sin reloj. */
|
||||
All dates hang off a fixed `NOW`: the function takes the moment as an
|
||||
argument precisely so it can be tested without a clock. */
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const NOW = new Date('2026-09-30T20:00:00.000Z');
|
||||
|
||||
/** Días hacia atrás desde `NOW`, en ISO. Negativo = clase futura. */
|
||||
/** Days back from `NOW`, in ISO. Negative = future class. */
|
||||
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
|
||||
|
||||
type Status = MemberClassSession['status'];
|
||||
|
||||
/** Clases en días consecutivos, de la más antigua a la más reciente. */
|
||||
/** Classes on consecutive days, oldest first. */
|
||||
function dense(statuses: Status[]): MemberClassSession[] {
|
||||
return statuses.map((status, index) => ({
|
||||
sessionId: `ses_${statuses.length - index}`,
|
||||
@@ -40,7 +39,7 @@ function dense(statuses: Status[]): MemberClassSession[] {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Clases con los offsets que se le pasen, en cualquier orden. */
|
||||
/** Classes with the offsets given, in any order. */
|
||||
function series(rows: [Status, number][]): MemberClassSession[] {
|
||||
return rows.map(([status, offsetDays], index) => ({
|
||||
sessionId: `ses_${index}`,
|
||||
@@ -69,7 +68,7 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('no cuenta clases que todavía no ocurrieron', () => {
|
||||
// Asistió a las tres últimas y falta a las tres siguientes: nadie se está yendo.
|
||||
// Attended the last three and is absent for the next three: nobody is drifting away.
|
||||
const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]]));
|
||||
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
|
||||
});
|
||||
@@ -78,14 +77,15 @@ describe('getMemberAttendanceRisk', () => {
|
||||
const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(3);
|
||||
// 4 días sin aparecer: el nivel viene de la racha, no del tiempo sin venir.
|
||||
// 4 days since last showing up: the level comes from the streak, not from the
|
||||
// time since they last came.
|
||||
expect(señales.daysSinceLastAttendance).toBe(4);
|
||||
expect(señales.level).toBe('riesgo_alto');
|
||||
});
|
||||
|
||||
it('una racha larguísima sin ninguna clase con presencia igual es riesgo alto', () => {
|
||||
// Nunca asistió a una clase elegible: la referencia para "hace cuánto no lo
|
||||
// vemos" es la última clase, así que no queda en verde para siempre.
|
||||
// Never attended an eligible class: the reference for "how long since we saw
|
||||
// them" is the last class, so it doesn't stay green forever.
|
||||
const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT']));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(5);
|
||||
@@ -99,8 +99,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
|
||||
// Una sola falta, la más reciente: la racha no llega. El nivel lo dispara
|
||||
// el tiempo sin aparecer.
|
||||
// A single absence, the most recent one: the streak doesn't reach. What drives
|
||||
// the level is the time since they last showed up.
|
||||
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
|
||||
const señales = summarizeMemberAttendance(alumno, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -110,8 +110,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
|
||||
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
|
||||
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
|
||||
// Dos faltas de racha: la atención le llega por la racha, y los 10 días
|
||||
// justos no mueven el nivel.
|
||||
// Two streak absences: attention comes from the streak, and exactly 10 days
|
||||
// does not move the level.
|
||||
expect(
|
||||
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
|
||||
).toBe('atencion');
|
||||
@@ -121,9 +121,9 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una tendencia a la baja da atención', () => {
|
||||
// 12 clases con dato. Las 4 anteriores al 100%, las 4 últimas al 50%, y la
|
||||
// más reciente es un PRESENT: racha 0 y asistencia reciente, así que la
|
||||
// tendencia es lo único que puede disparar la alerta.
|
||||
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
|
||||
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
|
||||
// the only thing that can raise the alert.
|
||||
const candidato = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
|
||||
@@ -135,8 +135,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('perder una sola clase no es tendencia', () => {
|
||||
// Mismo caso que el anterior con una clase menos perdida en la ventana
|
||||
// reciente: 3 de 4 contra 4 de 4. Es ruido, no una caída.
|
||||
// Same case as the previous one with one class fewer missed in the recent
|
||||
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
|
||||
const estable = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
|
||||
@@ -145,16 +145,16 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('la tendencia necesita historia para las dos ventanas', () => {
|
||||
// 5 clases con dato: la ventana anterior quedaría con una sola, así que no
|
||||
// hay contra qué comparar.
|
||||
// 5 marked classes: the previous window would be left with a single one, so
|
||||
// there is nothing to compare against.
|
||||
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
|
||||
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
|
||||
});
|
||||
|
||||
it('la racha manda sobre la tendencia', () => {
|
||||
// 16 clases: 4 anteriores al 100%, y las 4 últimas con 3 faltas seguidas
|
||||
// una clase con presencia. La tendencia sola daría atención; las 3 faltas
|
||||
// seguidas de punta dan riesgo alto, que es lo que tiene que ganar.
|
||||
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
|
||||
// absences and one attended class. The trend alone would give attention;
|
||||
// the 3 trailing absences give high risk, which is what has to win.
|
||||
const alumno = member(dense([
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
|
||||
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
|
||||
@@ -166,8 +166,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
|
||||
// Faltó, la de en medio no tiene registro, volvió a faltar. La racha real
|
||||
// es de una, no de dos.
|
||||
// Absent, the middle one has no record, absent again. The real streak
|
||||
// is one, not two.
|
||||
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(conHueco, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -177,8 +177,8 @@ describe('getMemberAttendanceRisk', () => {
|
||||
});
|
||||
|
||||
it('una clase justificada es la clase que no cuenta', () => {
|
||||
// Faltó, avisó, volvió a faltar: la racha es de una, y el promedio ignora la
|
||||
// clase justificada en vez de contarla como asistencia o como falta.
|
||||
// Absent, notified, absent again: the streak is one, and the average ignores
|
||||
// the excused class instead of counting it as attendance or as an absence.
|
||||
const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]]));
|
||||
const señales = summarizeMemberAttendance(justificada, NOW);
|
||||
expect(señales.consecutiveAbsences).toBe(1);
|
||||
@@ -293,7 +293,7 @@ describe('getGroupAttendanceSummary', () => {
|
||||
members: [
|
||||
conNivel('a', 'ok'),
|
||||
{ attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) },
|
||||
// Recién Chess: sin clases con dato, no mueve el promedio.
|
||||
// Just joined Chess: no marked classes, so they don't move the average.
|
||||
{ attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
|
||||
],
|
||||
now: NOW,
|
||||
|
||||
@@ -412,7 +412,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
|
||||
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
// Simular que ya existe un alumno con teléfono '11111111'
|
||||
// Simulate that an attendee with phone '11111111' already exists
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ phone: '11111111' },
|
||||
] as never);
|
||||
@@ -434,8 +434,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
attendees: [
|
||||
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
|
||||
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Ya existe en BD
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicado dentro del lote
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
|
||||
],
|
||||
}),
|
||||
});
|
||||
@@ -484,8 +484,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
// El resumen de la fila se pide en la misma consulta: una petición por
|
||||
// miembro sería N+1 sobre un listado de hasta 100.
|
||||
// The row summary is requested in the same query: one request per
|
||||
// member would be N+1 over a listing of up to 100.
|
||||
include: {
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
|
||||
@@ -2,8 +2,8 @@ import { describe, expect, it } from 'bun:test';
|
||||
import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers';
|
||||
import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
/* El resumen de la fila se arma en memoria: qué clase cuenta como reciente y
|
||||
qué cobro se muestra. Son las dos decisiones que la fila leen. */
|
||||
/* The row summary is built in memory: which class counts as recent and
|
||||
which payment is shown. Those are the two decisions the row reads. */
|
||||
|
||||
function record(
|
||||
overrides: Partial<AttendeeListItemRecord> = {},
|
||||
@@ -32,7 +32,7 @@ describe('toAttendeeListItemDto', () => {
|
||||
it('invierte la asistencia para que la clase más reciente quede a la derecha', () => {
|
||||
const dto = toAttendeeListItemDto(
|
||||
record({
|
||||
// Llega de más reciente a más antigua.
|
||||
// It arrives from most recent to oldest.
|
||||
attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -33,7 +33,7 @@ const attendeeRow = {
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
};
|
||||
|
||||
// Lo que devuelve el mock de Prisma: la fila más las relaciones del resumen.
|
||||
// What the Prisma mock returns: the row plus the summary relations.
|
||||
const attendee = {
|
||||
...attendeeRow,
|
||||
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
|
||||
@@ -58,8 +58,8 @@ describe('attendees routes', () => {
|
||||
...attendeeRow,
|
||||
createdAt: attendeeRow.createdAt.toISOString(),
|
||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||
// La consulta viene de más reciente a más antigua; la fila los
|
||||
// muestra al revés, con la clase más reciente a la derecha.
|
||||
// The query comes most recent first; the row shows them
|
||||
// the other way around, with the most recent class on the right.
|
||||
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
|
||||
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
|
||||
},
|
||||
|
||||
@@ -77,7 +77,7 @@ function makeSession(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Fecha "hoy" a las 19:00 UTC, del día real del runner.
|
||||
// "Today" at 19:00 UTC, on the runner's real day.
|
||||
function todayAtUtc() {
|
||||
const date = new Date();
|
||||
date.setUTCHours(19, 0, 0, 0);
|
||||
|
||||
@@ -84,8 +84,8 @@ describe('groups routes', () => {
|
||||
const where = {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
};
|
||||
// Los contadores de ocupación viajan en la misma consulta; la lista de
|
||||
// espera cuenta solo los PENDING, los que siguen esperando cupo.
|
||||
// The occupancy counters ride along in the same query; the waitlist
|
||||
// counts only PENDING, the ones still waiting for a spot.
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where,
|
||||
include: {
|
||||
@@ -131,8 +131,8 @@ describe('groups routes', () => {
|
||||
},
|
||||
]);
|
||||
|
||||
// Lunes 2026-01-05 al mediodía en Ciudad de México: la clase de las 18:00
|
||||
// todavía no empieza, así que ese grupo va primero.
|
||||
// Monday 2026-01-05 at noon in Mexico City: the 18:00 class
|
||||
// hasn't started yet, so that group goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
@@ -140,7 +140,7 @@ describe('groups routes', () => {
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
// A igual clase se pone delante el más nuevo, que era el criterio anterior.
|
||||
// On a tie the newest one goes first, which was the previous criterion.
|
||||
expect(result.value.data.map((item) => item.id)).toEqual([
|
||||
'hoy-tarde',
|
||||
'hoy-tarde-viejo',
|
||||
@@ -157,8 +157,8 @@ describe('groups routes', () => {
|
||||
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// Lunes al mediodía: la clase de las 10:00 de A ya pasó, así que su
|
||||
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero.
|
||||
// Monday at noon: A's 10:00 class already happened, so its
|
||||
// next occurrence is next Monday and B (Wednesday) goes first.
|
||||
const result = await new ListGroups({
|
||||
db,
|
||||
now: new Date('2026-01-05T18:00:00.000Z'),
|
||||
|
||||
@@ -5,7 +5,7 @@ const TZ = 'America/Mexico_City';
|
||||
|
||||
describe('nextClassOccurrence', () => {
|
||||
it('devuelve la próxima clase de hoy cuando aún no arrancó', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -21,7 +21,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('marca en curso si la clase arrancó hace menos de la ventana', () => {
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // miércoles 19:00 hora CDMX (1 h tras la clase)
|
||||
const now = new Date('2026-09-24T01:00:00.000Z'); // Wednesday 19:00 CDMX time (1 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -37,7 +37,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('salta a la próxima semana si la clase ya pasó la ventana', () => {
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // miércoles 21:00 hora CDMX (3 h tras la clase)
|
||||
const now = new Date('2026-09-24T03:00:00.000Z'); // Wednesday 21:00 CDMX time (3 h after the class)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['WEDNESDAY'],
|
||||
@@ -53,7 +53,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('elige la ocurrencia más próxima entre varios días', () => {
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // miércoles 12:00 hora CDMX
|
||||
const now = new Date('2026-09-23T18:00:00.000Z'); // Wednesday 12:00 CDMX time
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
|
||||
@@ -69,7 +69,7 @@ describe('nextClassOccurrence', () => {
|
||||
});
|
||||
|
||||
it('cruza de mes sin problema', () => {
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // martes 12:00 hora CDMX (último día de septiembre es miércoles 30)
|
||||
const now = new Date('2026-09-29T18:00:00.000Z'); // Tuesday 12:00 CDMX time (September's last day is Wednesday the 30th)
|
||||
|
||||
const result = nextClassOccurrence({
|
||||
days: ['THURSDAY'],
|
||||
|
||||
@@ -193,7 +193,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires (UTC-3). La clase de las 10:00 ya arrancó.
|
||||
// 10:23 in Buenos Aires (UTC-3). The 10:00 class already started.
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId, { timeZone: 'America/Argentina/Buenos_Aires' });
|
||||
|
||||
@@ -212,7 +212,7 @@ describe('GetHomeSummary', () => {
|
||||
{ ...groupA, days: ['WEDNESDAY'], time: '10:00' },
|
||||
]);
|
||||
|
||||
// 10:23 en Buenos Aires, pero la zona por defecto es CDMX → las 07:23 CDMX (aún no empieza).
|
||||
// 10:23 in Buenos Aires, but the default zone is CDMX → 07:23 CDMX (not started yet).
|
||||
const useCase = new GetHomeSummary({ db, now: new Date('2026-09-23T13:23:00.000Z') });
|
||||
const result = await useCase.execute(userId);
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('session auth', () => {
|
||||
it('classifies absence notification endpoints as public (token-based)', () => {
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).toBe(true);
|
||||
// Las rutas autenticadas de clases siguen protegidas.
|
||||
// The authenticated class routes stay protected.
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/today')).toBe(false);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false);
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<!-- viewport-fit=cover habilita env(safe-area-inset-*) en iOS standalone. -->
|
||||
<!-- viewport-fit=cover enables env(safe-area-inset-*) in iOS standalone. -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<title>Gruperly</title>
|
||||
<meta name="description" content="Gestión de cobros grupales" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" />
|
||||
|
||||
<!-- iOS standalone: sin esto la app abre en un pestaña de Safari. -->
|
||||
<!-- iOS standalone: without this the app opens in a Safari tab. -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="Gruperly" />
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* Genera el set de iconos PWA desde el isotipo SVG de marca.
|
||||
* Generates the PWA icon set from the brand isotype SVG.
|
||||
*
|
||||
* Uso: bun --filter @gruperly/web icons
|
||||
* Usage: bun --filter @gruperly/web icons
|
||||
*
|
||||
* Las salidas se versionan en `public/`; el build de Vite no las regenera
|
||||
* (sharp es una devDependency y no debe entrar en la imagen de Docker).
|
||||
* Re-correr solo cuando cambia `src/assets/brand/isotipo-y-organica.svg`.
|
||||
* The outputs are versioned in `public/`; the Vite build does not regenerate
|
||||
* them (sharp is a devDependency and must not end up in the Docker image).
|
||||
* Re-run only when `src/assets/brand/isotipo-y-organica.svg` changes.
|
||||
*/
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
@@ -16,30 +16,30 @@ const webDir = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg')
|
||||
const publicDir = join(webDir, 'public')
|
||||
|
||||
/** Fondo del tema claro; también sirve de lienzo para los iconos opacos. */
|
||||
/** Light theme background; it also serves as the canvas for opaque icons. */
|
||||
const BACKGROUND = '#ffffff'
|
||||
const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const
|
||||
|
||||
type IconTarget = {
|
||||
file: string
|
||||
size: number
|
||||
/** Rellena el lienzo con `BACKGROUND` en vez de dejar transparencia. */
|
||||
/** Fills the canvas with `BACKGROUND` instead of leaving it transparent. */
|
||||
opaque: boolean
|
||||
/** Fracción del lado que ocupa el logo. 1 = sin padding. */
|
||||
/** Fraction of the side the logo takes up. 1 = no padding. */
|
||||
contentRatio: number
|
||||
}
|
||||
|
||||
const targets: IconTarget[] = [
|
||||
{ file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 },
|
||||
{ file: 'pwa-512x512.png', size: 512, opaque: false, contentRatio: 0.9 },
|
||||
// Android recorta los iconos adaptativos en círculo: el contenido útil
|
||||
// vive en el 80% central del canvas, así que el logo va over white y escalado.
|
||||
// Android crops adaptive icons in a circle: the useful content lives in the
|
||||
// central 80% of the canvas, so the logo goes on white and scaled.
|
||||
{ file: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 },
|
||||
{ file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 },
|
||||
]
|
||||
|
||||
// El viewBox del isotipo no arranca en 0 y deja aire alrededor del glifo:
|
||||
// `trim` recorta ese margen para que el encuadre use el área real del dibujo.
|
||||
// The isotype viewBox does not start at 0 and leaves air around the glyph:
|
||||
// `trim` crops that margin so the framing uses the drawing's real area.
|
||||
const logo = await sharp(await readFile(source), { density: 512 })
|
||||
.trim({ threshold: 1 })
|
||||
.png()
|
||||
|
||||
@@ -20,8 +20,8 @@ export function BottomNav() {
|
||||
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
|
||||
)}
|
||||
>
|
||||
{/* Pastilla suave detrás del ícono: el estado activo se lee por
|
||||
color + fondo, no solo por el tono del texto. */}
|
||||
{/* Soft pill behind the icon: the active state is read by
|
||||
color + background, not only by the text tone. */}
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',
|
||||
|
||||
@@ -9,9 +9,9 @@ export function Header() {
|
||||
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
||||
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
|
||||
<div className="flex min-w-0 items-center">
|
||||
{/* `Link` y no `<a>`: en mobile el logo es la única forma de volver al
|
||||
inicio y un anchor recargaría el documento entero, perdiendo el
|
||||
estado en memoria (cache de React Query, evento de instalación). */}
|
||||
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
|
||||
home screen and an anchor would reload the whole document, losing
|
||||
the in-memory state (React Query cache, install event). */}
|
||||
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||
<Logo className="h-8" />
|
||||
</Link>
|
||||
|
||||
@@ -4,32 +4,33 @@ import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
||||
import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse'
|
||||
|
||||
type LargeTitleProps = {
|
||||
/** Texto del título. Es el mismo en el grande y en el de la barra: el `h1`
|
||||
* real es el grande, el de la barra es un duplicado visual. */
|
||||
/** Title text. It's the same in the large title and in the bar's copy: the
|
||||
* real `h1` is the large one, the bar's is a visual duplicate. */
|
||||
title: string
|
||||
/** Acción a la izquierda de la barra. En desktop es el link "volver" que
|
||||
* antes vivía en el cuerpo de la pantalla; en mobile se oculta. */
|
||||
/** Action to the left of the bar. On desktop it's the "Volver" link that
|
||||
* used to live in the screen body; on mobile it's hidden. */
|
||||
leading?: ReactNode
|
||||
/** Contexto que no puede desaparecer al scrollear (ej. el contador de
|
||||
* presentes). Viaja a la barra y se funde con el título. */
|
||||
/** Context that can't disappear on scroll (e.g. the present counter). It
|
||||
* travels to the bar and blends with the title. */
|
||||
barTrailing?: ReactNode
|
||||
/** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */
|
||||
/** Metadata under the large title: badges, description. It goes away when
|
||||
* the title collapses. */
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Encabezado de pantalla con Large Title (patrón de iOS): el título arranca
|
||||
* grande y al scrollear se desliza debajo de la barra, que se opaca y recibe
|
||||
* el título en versión chica.
|
||||
* Screen header with Large Title (the iOS pattern): the title starts large and
|
||||
* slides under the bar as you scroll, while the bar goes opaque and takes the
|
||||
* title in its small version.
|
||||
*
|
||||
* El título grande es un bloque normal en el flujo; la barra vive en una caja
|
||||
* sticky que el layout monta arriba de `<main>` (ver `ImmersiveBarHost`), así
|
||||
* el contenido se desliza por debajo sin márgenes negativos ni `fixed` que
|
||||
* haya que compensar en desktop.
|
||||
* The large title is a normal block in the flow; the bar lives in a sticky box
|
||||
* that the layout mounts above `<main>` (see `ImmersiveBarHost`), so the content
|
||||
* slides under it without negative margins or a `fixed` we'd have to compensate
|
||||
* for on desktop.
|
||||
*
|
||||
* El estado del scroll vive acá adentro a propósito: `children` llega como prop
|
||||
* ya construido, así React reutiliza los elementos y el subtree de abajo no se
|
||||
* re-renderiza en cada frame de scroll.
|
||||
* The scroll state lives in here on purpose: `children` arrives as an already
|
||||
* built prop, so React reuses the elements and the subtree below doesn't
|
||||
* re-render on every scroll frame.
|
||||
*/
|
||||
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
|
||||
const { titleRef, progress } = useLargeTitleCollapse()
|
||||
@@ -40,9 +41,9 @@ export function LargeTitle({ title, leading, barTrailing, children }: LargeTitle
|
||||
{barHost
|
||||
? createPortal(
|
||||
<div className="relative flex h-full items-center gap-3 px-4 lg:px-0">
|
||||
{/* El fondo va en una capa propia: se opaca con el scroll mientras
|
||||
el título entra, y `leading` (el link "volver") no puede
|
||||
fundirse con él porque existe siempre. */}
|
||||
{/* The background goes on its own layer: it goes opaque with the
|
||||
scroll while the title slides in, and `leading` (the "Volver"
|
||||
link) can't blend with it because it always exists. */}
|
||||
<div
|
||||
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
|
||||
style={{ opacity: progress }}
|
||||
|
||||
@@ -12,18 +12,18 @@ export function RootLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh w-full overflow-x-clip">
|
||||
{/* En las rutas immersive la pantalla trae su propia barra (LargeTitle),
|
||||
con el logo y el nombre del grupo: el header global con logo + tema +
|
||||
avatar sería una segunda barra compitiendo por los mismos píxeles. */}
|
||||
{/* On immersive routes the screen brings its own bar (LargeTitle) with
|
||||
the logo and the group name: the global header with logo + theme +
|
||||
avatar would be a second bar competing for the same pixels. */}
|
||||
{immersive ? null : <Header />}
|
||||
|
||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||
<Sidebar immersive={immersive} />
|
||||
|
||||
<ImmersiveBarProvider>
|
||||
{/* pt-0 en immersive: el padding superior lo aporta la caja de la
|
||||
barra, y si no el título grande arrancaría 16px más abajo de la
|
||||
base de la barra y el colapso se mediría corrido. */}
|
||||
{/* pt-0 on immersive: the bar's box provides the top padding,
|
||||
otherwise the large title would start 16px below the bottom of the
|
||||
bar and the collapse would be measured off. */}
|
||||
<main
|
||||
className={cn(
|
||||
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',
|
||||
|
||||
@@ -7,17 +7,17 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
// Sin header global no hay nada que esquive arriba: la columna del sidebar
|
||||
// pasa a ocupar la ventana completa y queda a la altura de la barra de
|
||||
// LargeTitle.
|
||||
// Without the global header there's nothing to clear above: the sidebar
|
||||
// column takes over the whole window and lines up with the height of the
|
||||
// LargeTitle bar.
|
||||
<aside
|
||||
className={cn(
|
||||
'sticky hidden w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex',
|
||||
immersive ? 'top-0 h-dvh' : 'top-16 h-[calc(100dvh-4rem)]',
|
||||
)}
|
||||
>
|
||||
{/* `Link` y no `<a>`: un anchor recargaría el documento y perdería el
|
||||
estado en memoria (cache de React Query, evento de instalación). */}
|
||||
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
|
||||
in-memory state (React Query cache, install event). */}
|
||||
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||
<Logo className="h-10" />
|
||||
</Link>
|
||||
|
||||
@@ -13,10 +13,10 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
||||
]
|
||||
|
||||
/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem
|
||||
* activo es "Grupos", no ninguno. El prefijo se corta en el separador para
|
||||
* que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay
|
||||
* subrutas del home que deban marcarla. */
|
||||
/** A section stays active within its subroutes: on `/groups/abc` the active
|
||||
* item is "Grupos", not none. The prefix is cut at the separator so
|
||||
* `/groupsomething` isn't taken for "/groups". The root is exact: the home has
|
||||
* no subroutes that should mark it. */
|
||||
export function isNavItemActive(pathname: string, to: string): boolean {
|
||||
if (to === '/') return pathname === '/'
|
||||
return pathname === to || pathname.startsWith(`${to}/`)
|
||||
|
||||
@@ -12,10 +12,10 @@ const variants: Record<BadgeVariant, string> = {
|
||||
warning: 'bg-warning-soft text-warning',
|
||||
danger: 'bg-danger-soft text-danger',
|
||||
neutral: 'bg-primary-soft text-primary',
|
||||
/* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la
|
||||
tinta de acento legible (`accent-fg` es el azul claro en tema oscuro,
|
||||
7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1
|
||||
y no alcanza el mínimo de 3:1 para contenido no textual. */
|
||||
/* Informational state, not an alert: waitlist, free spots. Uses the legible
|
||||
accent ink (`accent-fg` is the light blue in the dark theme, 7.1:1 on the
|
||||
card) and not the plain `accent`, which in dark scores 2.2:1 and misses the
|
||||
3:1 minimum for non-text content. */
|
||||
info: 'bg-accent-soft text-accent-fg',
|
||||
}
|
||||
|
||||
|
||||
@@ -28,9 +28,9 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
ref={ref}
|
||||
type={type}
|
||||
className={cn(
|
||||
// `transition-*` explícito en vez de `transition-all`: solo se animan
|
||||
// color, fondo, borde y transform. El feedback de presión se anula
|
||||
// con `motion-reduce` para respetar prefers-reduced-motion.
|
||||
// Explicit `transition-*` instead of `transition-all`: only color,
|
||||
// background, border and transform are animated. Press feedback is
|
||||
// cancelled with `motion-reduce` to respect prefers-reduced-motion.
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-medium transition-[color,background-color,border-color,fill,stroke,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
|
||||
variants[variant],
|
||||
sizes[size],
|
||||
|
||||
@@ -11,8 +11,8 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
<input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
// text-base (16px) en mobile: iOS auto-zoomea al enfocar controles con
|
||||
// font-size < 16px y, al cerrar el teclado, no restaura el scale.
|
||||
// text-base (16px) on mobile: iOS auto-zooms when focusing controls
|
||||
// with font-size < 16px and doesn't restore the scale on keyboard close.
|
||||
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
|
||||
className,
|
||||
|
||||
@@ -2,19 +2,20 @@ import { type ReactNode, useId, useState } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export type TooltipProps = {
|
||||
/** Texto explicativo que se muestra al hacer hover, foco de teclado o tap. */
|
||||
/** Explanatory text shown on hover, keyboard focus or tap. */
|
||||
content: ReactNode
|
||||
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */
|
||||
/** Trigger content. It sits inside a <button> to stay accessible. */
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en sm+). */
|
||||
/** Alternate positioning for the bubble (default: below, anchored right on sm+). */
|
||||
tooltipClassName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Tooltip accesible sin dependencias: hover (ratón), foco (teclado) y tap
|
||||
* (táctil, vía focus). Se cierra con Escape, al salir el puntero o al perder
|
||||
* el foco. El globo se ancla abajo del disparador para no tapar el contenido.
|
||||
* Accessible tooltip with no dependencies: hover (mouse), focus (keyboard) and
|
||||
* tap (touch, via focus). It closes on Escape, when the pointer leaves or when
|
||||
* it loses focus. The bubble is anchored below the trigger so it doesn't cover
|
||||
* the content.
|
||||
*/
|
||||
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -28,8 +29,8 @@ export function Tooltip({ content, children, className, tooltipClassName }: Tool
|
||||
<button
|
||||
type="button"
|
||||
aria-describedby={open ? id : undefined}
|
||||
// El hover solo aplica a punteros de ratón: en táctil no hay "hover
|
||||
// persistente" y el tap se resuelve con focus + click.
|
||||
// Hover only applies to mouse pointers: on touch there is no
|
||||
// "persistent hover" and tap is handled with focus + click.
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType === 'mouse') show()
|
||||
}}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'
|
||||
|
||||
/* Las pantallas "immersive" (ficha de grupo y asistencia) arman su propia barra
|
||||
de título en vez de usar el header global, pero la barra tiene que ser hija
|
||||
directa de `<main>`: un `sticky` solo se pega mientras su caja padre esté en
|
||||
pantalla, y el padre natural de la barra (el bloque del feature) es corto, así
|
||||
que se despegaría a los ~200px de scroll.
|
||||
/* "Immersive" screens (group detail and attendance) build their own title bar
|
||||
instead of using the global header, but the bar has to be a direct child of
|
||||
`<main>`: a `sticky` only sticks while its parent box is on screen, and the
|
||||
bar's natural parent (the feature block) is short, so it would detach at
|
||||
around ~200px of scroll.
|
||||
|
||||
Este provider expone una caja fija de 56px clavada arriba de `<main>` donde la
|
||||
pantalla monta su barra. La caja la dibuja el layout (para que ocupe su lugar
|
||||
desde el primer render) y su contenido lo aporta la pantalla. */
|
||||
This provider exposes a fixed 56px box pinned to the top of `<main>` where
|
||||
the screen mounts its bar. The layout draws the box (so it holds its place
|
||||
from the first render) and the screen supplies its content. */
|
||||
|
||||
type ImmersiveBarValue = {
|
||||
host: HTMLElement | null
|
||||
@@ -29,14 +29,14 @@ export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */
|
||||
/** The bar's box: first child of `<main>`, on immersive routes. */
|
||||
export function ImmersiveBarHost() {
|
||||
const { hostRef } = useContext(ImmersiveBarContext)
|
||||
|
||||
return <div ref={hostRef} className="sticky top-0 z-40 -mx-4 h-14 lg:mx-0" />
|
||||
}
|
||||
|
||||
/** Destino del portal de `LargeTitle`; `null` si la pantalla no es immersive. */
|
||||
/** Portal target for `LargeTitle`; `null` if the screen is not immersive. */
|
||||
export function useImmersiveBarHost() {
|
||||
return useContext(ImmersiveBarContext).host
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ type ThemeContextValue = {
|
||||
|
||||
const STORAGE_KEY = 'theme'
|
||||
|
||||
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */
|
||||
/** Status bar colors in standalone mode. Must match index.css. */
|
||||
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
|
||||
const THEME_COLOR_META_ID = 'theme-color'
|
||||
|
||||
@@ -50,8 +50,8 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
setIsDark(dark)
|
||||
localStorage.setItem(STORAGE_KEY, theme)
|
||||
|
||||
// En standalone la barra de estado se pinta con theme-color; sin esto
|
||||
// queda congelada en el valor que puso el script inline de index.html.
|
||||
// In standalone the status bar is painted with theme-color; without this
|
||||
// it stays frozen at the value the inline script in index.html set.
|
||||
document
|
||||
.getElementById(THEME_COLOR_META_ID)
|
||||
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 />
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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 } })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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={
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
|
||||
@@ -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: '/' })
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
/* Alto de la barra de navegación donde entra el título chico. Tiene que
|
||||
coincidir con el `h-14` de `LargeTitle`: la barra es sticky contra el borde
|
||||
superior de la ventana y el título grande se mide contra este valor. */
|
||||
/* Height of the navigation bar where the small title slides in. It has to
|
||||
match the `h-14` of `LargeTitle`: the bar is sticky to the top edge of the
|
||||
window and the large title is measured against this value. */
|
||||
const BAR_HEIGHT = 56
|
||||
|
||||
function clamp01(value: number) {
|
||||
@@ -11,13 +11,13 @@ function clamp01(value: number) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Progreso de colapso de un Large Title: 0 con el título grande desplegado,
|
||||
* 1 cuando quedó por completo tapado detrás de la barra.
|
||||
* Collapse progress of a Large Title: 0 with the large title fully shown,
|
||||
* 1 once it's completely hidden behind the bar.
|
||||
*
|
||||
* El progreso sale de la posición del título, no del tiempo: se recalcula en
|
||||
* cada frame mientras se scrollea. Por eso el gesto se siente pegado al dedo
|
||||
* en vez de "animado", y por eso `requestAnimationFrame` sirve para agrupar
|
||||
* eventos de scroll, no para interpolar la animación.
|
||||
* The progress comes from the title's position, not from time: it is
|
||||
* recalculated on every frame while scrolling. That's why the gesture feels
|
||||
* stuck to the finger instead of "animated", and why `requestAnimationFrame`
|
||||
* is there to batch scroll events, not to interpolate the animation.
|
||||
*/
|
||||
export function useLargeTitleCollapse() {
|
||||
const titleRef = useRef<HTMLHeadingElement>(null)
|
||||
@@ -32,11 +32,11 @@ export function useLargeTitleCollapse() {
|
||||
const measure = () => {
|
||||
frame = 0
|
||||
const { top, height } = title.getBoundingClientRect()
|
||||
// 0 cuando el borde superior del título llega a la base de la barra, 1
|
||||
// cuando su borde inferior también llegó (quedó enteramente debajo).
|
||||
// 0 when the title's top edge reaches the bottom of the bar, 1 when its
|
||||
// bottom edge got there too (it ended up entirely underneath).
|
||||
const next = clamp01((BAR_HEIGHT - top) / (height || BAR_HEIGHT))
|
||||
// Los títulos de grupo llegan asíncrono y pueden cambiar de alto entre
|
||||
// renders: sin este umbral se re-renderiza en cada frame de scroll.
|
||||
// Group titles arrive asynchronously and can change height between
|
||||
// renders: without this threshold it re-renders on every scroll frame.
|
||||
setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next))
|
||||
}
|
||||
|
||||
@@ -48,8 +48,8 @@ export function useLargeTitleCollapse() {
|
||||
window.addEventListener('scroll', schedule, { passive: true })
|
||||
window.addEventListener('resize', schedule)
|
||||
|
||||
// El nombre del grupo se carga después del primer render y la webfont puede
|
||||
// cambiar el alto del título: el rango de colapso depende de esa medida.
|
||||
// The group name loads after the first render and the webfont can change
|
||||
// the title's height: the collapse range depends on that measurement.
|
||||
const observer = new ResizeObserver(schedule)
|
||||
observer.observe(title)
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en
|
||||
lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el
|
||||
service worker precachea todo lo emitido, casi 1 MB que nunca se descarga.
|
||||
El archivo .woff2 sí viene del paquete, con hash y cache immutable. */
|
||||
/* Self-hosted Inter variable. We declare only latin and latin-ext by hand
|
||||
instead of importing @fontsource's wght.css: that one brings all 7 subsets
|
||||
and the service worker precaches everything emitted, almost 1 MB that never
|
||||
gets downloaded. The .woff2 file does come from the package, hashed with an
|
||||
immutable cache. */
|
||||
@font-face {
|
||||
font-family: "Inter Variable";
|
||||
font-style: normal;
|
||||
@@ -25,7 +26,7 @@
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme inline {
|
||||
/* Escala de marca (identidad fija, igual a la landing) */
|
||||
/* Brand scale (fixed identity, same as the landing) */
|
||||
--color-brand-50: var(--brand-50);
|
||||
--color-brand-100: var(--brand-100);
|
||||
--color-brand-200: var(--brand-200);
|
||||
@@ -38,12 +39,12 @@
|
||||
--color-brand-900: var(--brand-900);
|
||||
--color-brand-950: var(--brand-950);
|
||||
|
||||
/* Colores de la gráfica del isotipo/logotipo */
|
||||
/* Colors sampled from the logo mark */
|
||||
--color-brand-night: var(--brand-night);
|
||||
--color-brand-celeste: var(--brand-celeste);
|
||||
--color-brand-cloud: var(--brand-cloud);
|
||||
|
||||
/* Tokens semánticos (conmutan con tema claro/oscuro) */
|
||||
/* Semantic tokens (switch with the light/dark theme) */
|
||||
--color-background: var(--background);
|
||||
--color-surface: var(--surface);
|
||||
--color-primary: var(--primary);
|
||||
@@ -70,14 +71,14 @@
|
||||
--color-attendance-attention: var(--attendance-attention);
|
||||
--color-attendance-ok: var(--attendance-ok);
|
||||
|
||||
/* Border radius por defecto */
|
||||
/* Default border radius */
|
||||
--radius-xl: 0.75rem;
|
||||
|
||||
/* Tipografía (igual que la landing) */
|
||||
/* @fontsource-variable/inter registra la familia como "Inter Variable" */
|
||||
/* Typography (same as the landing) */
|
||||
/* @fontsource-variable/inter registers the family as "Inter Variable" */
|
||||
--font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
|
||||
|
||||
/* Animaciones */
|
||||
/* Animations */
|
||||
--animate-fade-in: fade-in 0.2s ease-out;
|
||||
--animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
|
||||
@@ -101,7 +102,7 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Escala de marca */
|
||||
/* Brand scale */
|
||||
--brand-50: #eef4ff;
|
||||
--brand-100: #dbe6fe;
|
||||
--brand-200: #bfd3fe;
|
||||
@@ -117,17 +118,17 @@
|
||||
--brand-celeste: #93b4fd;
|
||||
--brand-cloud: #eef4ff;
|
||||
|
||||
/* Tema claro */
|
||||
/* Light theme */
|
||||
--background: #ffffff;
|
||||
--surface: #ffffff;
|
||||
--primary: #0f172a;
|
||||
--primary-soft: #f1f5f9;
|
||||
--foreground: #475569;
|
||||
/* Texto secundario sobre superficies suaves (tarjetas). En tema claro el
|
||||
gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre
|
||||
`background`, así que acá no hay que mover nada: mismo valor, mismo
|
||||
contrato. El token existe igual para que "secundario" sea un nombre y no
|
||||
una coincidencia de color. */
|
||||
/* Secondary text on soft surfaces (cards). In the light theme the
|
||||
`foreground` gray already scores 6.9:1 on `primary-soft` and 7.6:1 on
|
||||
`background`, so there's nothing to move here: same value, same contract.
|
||||
The token exists anyway so "secondary" is a name and not a color
|
||||
coincidence. */
|
||||
--secondary: #475569;
|
||||
--accent: #2544ea;
|
||||
--accent-strong: #1d33d8;
|
||||
@@ -140,18 +141,18 @@
|
||||
--success-soft: #ecfdf5;
|
||||
--warning: #b45309;
|
||||
--warning-soft: #fffbeb;
|
||||
/* naranja: escalón de severidad para la misma familia de alertas (aviso por
|
||||
asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la
|
||||
tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */
|
||||
/* Orange: severity step for the same alert family (attendance and capacity
|
||||
warnings). It scores 4.9:1 on `warning-strong-soft` and 4.4:1 on the card,
|
||||
so it works for text and for a subtle border. */
|
||||
--warning-strong: #c2410c;
|
||||
--warning-strong-soft: #fff7ed;
|
||||
--danger: #f43f5e;
|
||||
--danger-soft: #fff1f2;
|
||||
/* Rojo legible como TEXTO. `--danger` da 3.35:1 sobre la tarjeta en tema
|
||||
claro, así que como texto no llega al 4.5:1 de AA (sí sirve como relleno,
|
||||
donde el mínimo es 3:1). Es el mismo patrón que `accent` / `accent-fg`: un
|
||||
color para superficies grandes y su versión legible para rotular. Este
|
||||
#be123c da 5.74:1 sobre la tarjeta y 5.72:1 sobre `danger-soft`. */
|
||||
/* Red legible as TEXT. In the light theme `--danger` scores 3.35:1 on the
|
||||
card, so as text it misses AA's 4.5:1 (it does work as a fill, where the
|
||||
minimum is 3:1). Same pattern as `accent` / `accent-fg`: one color for
|
||||
large surfaces and a legible version of it for labels. This #be123c scores
|
||||
5.74:1 on the card and 5.72:1 on `danger-soft`. */
|
||||
--danger-fg: #be123c;
|
||||
--attendance-high: #d63b3b;
|
||||
--attendance-attention: #f5a623;
|
||||
@@ -161,16 +162,16 @@
|
||||
.dark {
|
||||
color-scheme: dark;
|
||||
|
||||
/* Tema oscuro (paleta slate/brand de la landing) */
|
||||
/* Dark theme (slate/brand palette from the landing) */
|
||||
--background: #020617;
|
||||
--surface: #0f172a;
|
||||
--primary: #f1f5f9;
|
||||
--primary-soft: #1e293b;
|
||||
--foreground: #94a3b8;
|
||||
/* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la
|
||||
tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior.
|
||||
El salto importa en las superficies suaves, que son las que dominan las
|
||||
tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */
|
||||
/* Secondary goes one step up from `foreground`: 7.1:1 on the card (#1e293b)
|
||||
and 9.8:1 on the background, against 5.7:1 for the previous gray. The step
|
||||
matters on soft surfaces, which are what dominates list cards: supporting
|
||||
text there is what gets lost the most. */
|
||||
--secondary: #a8b6c8;
|
||||
--accent: #2544ea;
|
||||
--accent-strong: #1d33d8;
|
||||
@@ -183,15 +184,15 @@
|
||||
--success-soft: color-mix(in srgb, var(--success) 15%, transparent);
|
||||
--warning: #fcd34d;
|
||||
--warning-soft: color-mix(in srgb, var(--warning) 15%, transparent);
|
||||
/* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el
|
||||
mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo
|
||||
translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */
|
||||
/* In dark the "orange" has to gain lightness to reach the same contrast as
|
||||
its light version: #fb923c scores 4.7:1 on the badge's translucent
|
||||
background, against 4.1:1 for the #f97316 of the standard palette. */
|
||||
--warning-strong: #fb923c;
|
||||
--warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent);
|
||||
--danger: #fb7185;
|
||||
--danger-soft: color-mix(in srgb, var(--danger) 15%, transparent);
|
||||
/* En oscuro `#fb7185` ya da 5.44:1 sobre la tarjeta: legible como texto y de
|
||||
sobra como relleno, así que acá no hay que mover nada. */
|
||||
/* In dark `#fb7185` already scores 5.44:1 on the card: legible as text and
|
||||
more than enough as a fill, so there's nothing to move here. */
|
||||
--danger-fg: var(--danger);
|
||||
}
|
||||
|
||||
@@ -205,14 +206,14 @@
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
/* iOS (Safari y standalone) hace auto-zoom al enfocar un control de
|
||||
formulario con font-size < 16px, y al cerrar el teclado no restaura el
|
||||
scale: la app queda con zoom. El `Input` ya sube a 16px en mobile
|
||||
(`text-base sm:text-sm`); esto es la red de seguridad para textareas,
|
||||
selects o inputs crudos que se agreguen más adelante.
|
||||
El 639px calza con el breakpoint `sm` de Tailwind. El `!important` es
|
||||
a propósito: sin él, una clase `text-sm` en un input futuro ganaría por
|
||||
especificidad y reintroduciría el bug sin avisar. */
|
||||
/* iOS (Safari and standalone) auto-zooms when a form control with font-size
|
||||
< 16px is focused, and on keyboard close it doesn't restore the scale:
|
||||
the app is left zoomed in. `Input` already goes to 16px on mobile
|
||||
(`text-base sm:text-sm`); this is the safety net for textareas, selects or
|
||||
raw inputs added later.
|
||||
The 639px matches Tailwind's `sm` breakpoint. The `!important` is on
|
||||
purpose: without it a `text-sm` class on a future input would win on
|
||||
specificity and reintroduce the bug without warning. */
|
||||
@media (max-width: 639px) {
|
||||
input,
|
||||
textarea,
|
||||
|
||||
@@ -80,7 +80,7 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
problem = body as ProblemDetails
|
||||
}
|
||||
} catch {
|
||||
// Sin cuerpo JSON: usamos el error genérico.
|
||||
// No JSON body: we use the generic error.
|
||||
}
|
||||
throw new ApiError(res.status, problem)
|
||||
}
|
||||
@@ -108,9 +108,9 @@ export const createGroup = (payload: CreateFirstGroup) =>
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
/* La pantalla de grupos no tiene paginación: se pide el máximo permitido para
|
||||
que ningún grupo quede fuera de la lista, y la zona horaria del browser para
|
||||
que el backend ordene por la próxima clase en la hora local de la persona. */
|
||||
/* The groups screen has no pagination: we ask for the maximum allowed so no
|
||||
group is left out of the listing, and for the browser time zone so the
|
||||
backend sorts by the next class in the person's local time. */
|
||||
const GROUPS_PAGE_SIZE = 100
|
||||
|
||||
export const getGroups = () => {
|
||||
@@ -222,7 +222,7 @@ export const removeGroupAttendee = (
|
||||
},
|
||||
)
|
||||
|
||||
// — Día a Día: clases y asistencia —
|
||||
// — Day to day: classes and attendance —
|
||||
|
||||
export const getClassesToday = () =>
|
||||
apiFetch<ClassTodayList>(`/api/v1/classes/today${timeZoneParam()}`)
|
||||
@@ -251,7 +251,7 @@ export const publicNotifyAbsence = (payload: PublicNotifyAbsence) =>
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
// — Analíticas y gestión de riesgo —
|
||||
// — Analytics and risk management —
|
||||
|
||||
export const getGroupAnalytics = (groupId: string) =>
|
||||
apiFetch<GroupAnalytics>(`/api/v1/groups/${groupId}/analytics`)
|
||||
|
||||
@@ -18,11 +18,11 @@ export function normalizePhone(rawPhone: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea texto CSV con soporte para:
|
||||
* - Delimitadores automáticos (coma, punto y coma, tabulador)
|
||||
* - Comillas y comillas escapadas ("")
|
||||
* Parses CSV text with support for:
|
||||
* - Automatic delimiters (comma, semicolon, tab)
|
||||
* - Quotes and escaped quotes ("")
|
||||
* - UTF-8 BOM
|
||||
* - Saltos de línea CRLF o LF
|
||||
* - CRLF or LF line breaks
|
||||
*/
|
||||
export function parseCsvContent(content: string): string[][] {
|
||||
const cleanContent = content.replace(/^\uFEFF/, '');
|
||||
@@ -30,7 +30,7 @@ export function parseCsvContent(content: string): string[][] {
|
||||
|
||||
if (lines.length === 0) return [];
|
||||
|
||||
// Detectar delimitador basado en la primera línea
|
||||
// Detect the delimiter from the first line
|
||||
const firstLine = lines[0];
|
||||
const commaCount = (firstLine.match(/,/g) || []).length;
|
||||
const semicolonCount = (firstLine.match(/;/g) || []).length;
|
||||
@@ -56,7 +56,7 @@ export function parseCsvContent(content: string): string[][] {
|
||||
if (char === '"') {
|
||||
if (insideQuote && line[i + 1] === '"') {
|
||||
currentCell += '"';
|
||||
i++; // Saltear comilla escapada
|
||||
i++; // Skip the escaped quote
|
||||
} else {
|
||||
insideQuote = !insideQuote;
|
||||
}
|
||||
@@ -75,8 +75,8 @@ export function parseCsvContent(content: string): string[][] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea un archivo XLSX de Excel extrayendo sharedStrings y sheet1.xml
|
||||
* utilizando DecompressionStream nativo del navegador sin dependencias externas.
|
||||
* Parses an Excel XLSX file by extracting sharedStrings and sheet1.xml with
|
||||
* the browser's native DecompressionStream, without external dependencies.
|
||||
*/
|
||||
export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]> {
|
||||
const view = new DataView(buffer);
|
||||
@@ -112,7 +112,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
|
||||
entries.set(fileName, new Uint8Array(decompressed));
|
||||
}
|
||||
} catch {
|
||||
// Ignorar archivos que no se puedan descomprimir
|
||||
// Ignore files that can't be decompressed
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
|
||||
offset = dataStart + compressedSize;
|
||||
}
|
||||
|
||||
// Parsear strings compartidos
|
||||
// Parse the shared strings
|
||||
const sharedStringsData = entries.get('xl/sharedStrings.xml');
|
||||
const sharedStrings: string[] = [];
|
||||
if (sharedStringsData) {
|
||||
@@ -138,7 +138,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
|
||||
}
|
||||
}
|
||||
|
||||
// Parsear sheet1.xml
|
||||
// Parse sheet1.xml
|
||||
const sheetData = entries.get('xl/worksheets/sheet1.xml');
|
||||
if (!sheetData) {
|
||||
throw new Error('No se pudo encontrar la hoja de cálculo principal en el archivo Excel.');
|
||||
@@ -174,7 +174,7 @@ export async function parseXlsxContent(buffer: ArrayBuffer): Promise<string[][]>
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza una matriz 2D en objetos de contactos con detección inteligente de columnas.
|
||||
* Normalizes a 2D matrix into contact objects with smart column detection.
|
||||
*/
|
||||
export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[] {
|
||||
if (rawRows.length === 0) return [];
|
||||
@@ -219,7 +219,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
|
||||
}
|
||||
}
|
||||
|
||||
// Fallbacks posicionales si no se detectaron encabezados explícitos
|
||||
// Positional fallbacks when no explicit headers were detected
|
||||
if (!hasHeader) {
|
||||
firstNameCol = 0;
|
||||
lastNameCol = 1;
|
||||
@@ -230,7 +230,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
|
||||
}
|
||||
|
||||
if (phoneCol === -1) {
|
||||
// Buscar la primera columna que parezca un número telefónico
|
||||
// Look for the first column that looks like a phone number
|
||||
for (let c = 0; c < (rawRows[1]?.length ?? 0); c++) {
|
||||
const sample = rawRows[1][c];
|
||||
if (/^[\d\s+\-()]{6,}$/.test(sample)) {
|
||||
@@ -291,7 +291,7 @@ export function normalizeRowsToContacts(rawRows: string[][]): ParsedContactRow[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Descarga una plantilla de ejemplo en formato CSV para la carga masiva.
|
||||
* Downloads a sample template in CSV format for the bulk upload.
|
||||
*/
|
||||
export function downloadAttendeeTemplateCsv() {
|
||||
const csvContent =
|
||||
|
||||
@@ -51,18 +51,18 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
|
||||
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
|
||||
}
|
||||
|
||||
/* Un importe se escribe con el país de la persona: su moneda y su regional
|
||||
(separadores, posición del símbolo), sin conversión — el importe lo fija
|
||||
quien creó el grupo y no se toca. El país sale de la zona horaria del
|
||||
sistema y, si no se conoce, del idioma del browser (ver countryOf). Sin
|
||||
país conocido se pinta con el símbolo $ genérico, nunca con un código
|
||||
inventado. La firma acepta moneda y locale para forzarlas (tests, print)
|
||||
sin tocar los call sites. */
|
||||
/* An amount is written with the person's country: its currency and its regional
|
||||
format (separators, symbol position), with no conversion — the amount is set
|
||||
by whoever created the group and is never touched. The country comes from the
|
||||
system time zone and, when it's unknown, from the browser language (see
|
||||
countryOf). With no known country we fall back to the generic $ symbol,
|
||||
never to an invented code. The signature takes a currency and a locale to
|
||||
force them (tests, print) without touching the call sites. */
|
||||
|
||||
/* La configuración regional del browser manda en cómo se pintan los datos.
|
||||
Se lee en cada llamada (es un accessor barato) para que un cambio de idioma
|
||||
del sistema se refleje sin recargar; lo caro es construir el formatter, así
|
||||
que esos se memorizan por locale/moneda. */
|
||||
/* The browser's regional settings decide how the data is rendered. It's read
|
||||
on every call (it's a cheap accessor) so a system language change shows up
|
||||
without a reload; building the formatter is the expensive part, so those are
|
||||
memoized per locale/currency. */
|
||||
type BrowserNavigator = { language?: string; languages?: readonly string[] }
|
||||
|
||||
function browserLocale(): string | undefined {
|
||||
@@ -78,14 +78,14 @@ export function formatPrice(
|
||||
locale?: string,
|
||||
): string {
|
||||
if (price == null) return '—'
|
||||
// Importes enteros sin decimales ($50.000); con centavos se respetan.
|
||||
// Whole amounts with no decimals ($50.000); cents are kept when present.
|
||||
const hasCents = !Number.isInteger(price)
|
||||
const browser = locale ?? browserLocale()
|
||||
const country = countryOf(browser)
|
||||
const resolvedCurrency = currency ?? currencyForRegion(country)
|
||||
// Los separadores y la posición del símbolo siguen al país: un browser en
|
||||
// inglés en Argentina tiene que ver $50.000, no ARS 50,000. Con la locale
|
||||
// pasada explícita no se toca nada (tests, print).
|
||||
// Separators and symbol position follow the country: an English browser in
|
||||
// Argentina has to see $50.000, not ARS 50,000. When the locale is passed
|
||||
// explicitly nothing is touched (tests, print).
|
||||
const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser
|
||||
const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}`
|
||||
|
||||
@@ -103,27 +103,28 @@ export function formatPrice(
|
||||
return tidyCurrencySpacing(formatter.format(price))
|
||||
}
|
||||
|
||||
/* Intl separa el símbolo de la moneda con un espacio duro: "$ 50.000" se lee
|
||||
como dos tokens sueltos. Lo quitamos solo cuando separa símbolo de número;
|
||||
entre dígitos y código ("50.000 ARS") el no-break space evita el corte. */
|
||||
/* Intl separates the currency symbol with a hard space: "$ 50.000" reads as two
|
||||
loose tokens. We strip it only when it separates symbol from number; between
|
||||
digits and the code ("50.000 ARS") the non-breaking space prevents the
|
||||
break. */
|
||||
const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu
|
||||
|
||||
function tidyCurrencySpacing(value: string): string {
|
||||
return value.replace(SYMBOL_GAP, '$1')
|
||||
}
|
||||
|
||||
/* ── Teléfonos ──────────────────────────────────────────────────────────────
|
||||
/* ── Phones ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Presentación, nunca persistencia: los links wa.me siguen usando los dígitos
|
||||
crudos. El formato sale de la región del propio número cuando su prefijo de
|
||||
país es reconocible; si el número es nacional, manda la región del browser
|
||||
(y si esa región no la conocemos, la de la app: AR). Si nada encaja se cae
|
||||
a E.164 (+331234567890) o al valor original, siempre preferible a un número
|
||||
inventado. */
|
||||
Presentation, never persistence: the wa.me links still use the raw digits.
|
||||
The format comes from the region of the number itself when its country
|
||||
prefix is recognizable; if the number is national, the browser's region wins
|
||||
(and if we don't know that region, the app's: AR). If nothing matches we fall
|
||||
back to E.164 (+331234567890) or to the original value, always preferable to
|
||||
an invented number. */
|
||||
|
||||
type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX'
|
||||
|
||||
/** Prefijos de país que sabemos agrupar. */
|
||||
/** Country prefixes we know how to group. */
|
||||
const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [
|
||||
{ region: 'AR', code: '54' },
|
||||
{ region: 'ES', code: '34' },
|
||||
@@ -141,15 +142,15 @@ export function formatPhoneDisplay(
|
||||
|
||||
const hasPlus = raw.startsWith('+')
|
||||
let digits = raw.replace(/\D/g, '')
|
||||
// "0054…" es el mismo indicio internacional que "+54…".
|
||||
// "0054…" is the same international hint as "+54…".
|
||||
const hasDoubleZero = !hasPlus && raw.startsWith('00')
|
||||
if (hasDoubleZero) digits = digits.slice(2)
|
||||
if (digits.length < 6) return raw
|
||||
|
||||
const withCallingCode = formatWithCallingCode(digits)
|
||||
if (withCallingCode) return withCallingCode
|
||||
// Número de una región que no agrupamos: al menos se separa en bloques de a
|
||||
// 3 para que no se lea como un muro de dígitos. El `+` se conserva si lo había.
|
||||
// Number from a region we don't group: at least it's split into groups of 3
|
||||
// so it doesn't read like a wall of digits. The `+` is kept if there was one.
|
||||
if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}`
|
||||
|
||||
return (
|
||||
@@ -158,7 +159,7 @@ export function formatPhoneDisplay(
|
||||
)
|
||||
}
|
||||
|
||||
/** Bloques de a 3 desde la derecha: el sobrante de 1-2 dígitos queda a la izquierda. */
|
||||
/** Groups of 3 from the right: the leftover 1-2 digits stay on the left. */
|
||||
function groupByThrees(digits: string): string {
|
||||
const groups: string[] = []
|
||||
let rest = digits
|
||||
@@ -170,7 +171,7 @@ function groupByThrees(digits: string): string {
|
||||
return groups.join(' ')
|
||||
}
|
||||
|
||||
/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */
|
||||
/** Tries the country prefix only if what follows fits its rules. */
|
||||
function formatWithCallingCode(digits: string): string | null {
|
||||
for (const { region, code } of COUNTRY_CALLING_CODES) {
|
||||
if (!digits.startsWith(code)) continue
|
||||
@@ -180,12 +181,12 @@ function formatWithCallingCode(digits: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/** Región ISO → región con reglas propias. CA comparte NANP con US. */
|
||||
/** ISO region → region with its own rules. CA shares NANP with US. */
|
||||
function appRegion(region: string | undefined): PhoneRegion {
|
||||
if (region === 'US' || region === 'CA') return 'US'
|
||||
if (region === 'ES') return 'ES'
|
||||
if (region === 'MX') return 'MX'
|
||||
// Sin región reconocible seguimos siendo una app de Argentina.
|
||||
// With no recognizable region we are still an Argentine app.
|
||||
return 'AR'
|
||||
}
|
||||
|
||||
@@ -210,12 +211,12 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
|
||||
let national = digits
|
||||
let isMobile = false
|
||||
|
||||
// Móvil argentino: 9 + 10 dígitos nacionales.
|
||||
// Argentine mobile: 9 + 10 national digits.
|
||||
if (national.length === 11 && national.startsWith('9')) {
|
||||
national = national.slice(1)
|
||||
isMobile = true
|
||||
}
|
||||
// 0 de trunk nacional: además implica que el número es argentino.
|
||||
// National trunk 0: it also implies the number is Argentine.
|
||||
if (national.startsWith('0') && national.length >= 9) {
|
||||
national = national.slice(1)
|
||||
withCountry = true
|
||||
@@ -229,8 +230,8 @@ function formatArNational(digits: string, withCountry: boolean): string | null {
|
||||
|
||||
function groupArNational(digits: string): string {
|
||||
if (digits.length === 10) {
|
||||
// 11 es el único área de 2 dígitos (Gran Buenos Aires); el resto se
|
||||
// agrupa 4-2-4, que es el patrón de las áreas de 4 dígitos.
|
||||
// 11 is the only 2-digit area code (Gran Buenos Aires); the rest group
|
||||
// 4-2-4, which is the pattern for 4-digit area codes.
|
||||
return digits.startsWith('11')
|
||||
? `${digits.slice(0, 2)} ${digits.slice(2, 6)}-${digits.slice(6)}`
|
||||
: `${digits.slice(0, 4)} ${digits.slice(4, 6)}-${digits.slice(6)}`
|
||||
@@ -240,31 +241,31 @@ function groupArNational(digits: string): string {
|
||||
return digits
|
||||
}
|
||||
|
||||
/** NANP (US/CA): 10 dígitos con área e intercambio que arrancan en 2–9. */
|
||||
/** NANP (US/CA): 10 digits with area and exchange starting in 2–9. */
|
||||
function formatUsNational(digits: string): string | null {
|
||||
if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1)
|
||||
if (digits.length !== 10) return null
|
||||
if (digits[0] === '0' || digits[0] === '1' || digits[3] === '0' || digits[3] === '1') return null
|
||||
// Convención doméstica: el "1" del país no se escribe.
|
||||
// Domestic convention: the country "1" is not written.
|
||||
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`
|
||||
}
|
||||
|
||||
/** España: 9 dígitos (móvil 6/7, fijo 8/9) agrupados 3-2-2-2. */
|
||||
/** Spain: 9 digits (mobile 6/7, landline 8/9) grouped 3-2-2-2. */
|
||||
function formatEsNational(digits: string, withCountry: boolean): string | null {
|
||||
if (digits.length !== 9 || !'6789'.includes(digits[0])) return null
|
||||
const local = `${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 7)} ${digits.slice(7)}`
|
||||
return withCountry ? `+34 ${local}` : local
|
||||
}
|
||||
|
||||
/** México: 10 dígitos agrupados 2-4-4. */
|
||||
/** Mexico: 10 digits grouped 2-4-4. */
|
||||
function formatMxNational(digits: string, withCountry: boolean): string | null {
|
||||
if (digits.length !== 10 || digits[0] === '0' || digits[0] === '1') return null
|
||||
const local = `${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`
|
||||
return withCountry ? `+52 ${local}` : local
|
||||
}
|
||||
|
||||
// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez
|
||||
// de "Vence día 10": se lee como una promesa, no como un dato suelto.
|
||||
// The due date is worded as a phrase ("Vence el día 10 de cada mes") instead of
|
||||
// "Vence día 10": it reads as a promise, not as a bare fact.
|
||||
export function formatBillingMeta(
|
||||
billingType: BillingType | null,
|
||||
dueDay: number | null,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/* Rutas "immersive": las que arman su propia barra de navegación con
|
||||
`LargeTitle` (título grande que colapsa) y por eso no muestran el header
|
||||
global con logo + toggle de tema + avatar.
|
||||
/* "Immersive" routes: the ones that build their own navigation bar with
|
||||
`LargeTitle` (a large title that collapses) and therefore don't show the
|
||||
global header with logo + theme toggle + avatar.
|
||||
|
||||
El patrón se resuelve a mano y no con `matchRoute` porque las dos rutas
|
||||
llevan parámetros (`matchRoute` los exige) y porque las rutas hijas NO son
|
||||
immersive aunque compartan prefijo: `/groups/:id/attendees/new` sigue usando
|
||||
el header global. */
|
||||
The pattern is resolved by hand and not with `matchRoute` because the two
|
||||
routes carry params (`matchRoute` requires them) and because child routes are
|
||||
NOT immersive even when they share a prefix: `/groups/:id/attendees/new`
|
||||
still uses the global header. */
|
||||
|
||||
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||
['groups', ':id'],
|
||||
@@ -13,9 +13,9 @@ const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||
['class', ':id', 'attendance'],
|
||||
]
|
||||
|
||||
/* Rutas estáticas que ocupan el lugar de un parámetro. Sin esta lista
|
||||
`/groups/new` (crear grupo) se tomaría por una ficha de grupo y perdería el
|
||||
header global. */
|
||||
/* Static routes that sit where a param would go. Without this list
|
||||
`/groups/new` (create group) would be taken for a group detail page and would
|
||||
lose the global header. */
|
||||
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
|
||||
|
||||
export function isImmersiveRoute(pathname: string) {
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
/* De dónde es la persona y cómo se le escriben los números.
|
||||
/* Where the person is from and how their numbers get written.
|
||||
|
||||
El idioma del browser dice en qué idioma se está, no en qué país se está:
|
||||
con "en-US" a alguien en Argentina lo trata como estadounidense, y con
|
||||
"es-419" no dice ningún país. La zona horaria —que sí expone el sistema—
|
||||
es la señal del país real; el idioma solo define cuando la zona no se
|
||||
conoce. Con el país resuelto salen la moneda (REGION_CURRENCY) y la
|
||||
regional con la que se formatea (REGION_LOCALE), para que un browser en
|
||||
inglés en Argentina vea $50.000 y no ARS 50,000.
|
||||
The browser language says what language you're in, not what country you're
|
||||
in: with "en-US" it treats someone in Argentina as American, and with
|
||||
"es-419" it says no country at all. The time zone — which the system does
|
||||
expose — is the signal for the real country; the language only decides when
|
||||
the time zone is unknown. With the country resolved you get the currency
|
||||
(REGION_CURRENCY) and the locale it's formatted with (REGION_LOCALE), so an
|
||||
English browser in Argentina sees $50.000 and not ARS 50,000.
|
||||
|
||||
Estos mapas son dato a mano (Intl no expone región → moneda ni región →
|
||||
locale). Solo definen cómo se PINTA un importe: el valor persistido no
|
||||
cambia ni se convierte. Si el país no está en ninguno, formatPrice cae al
|
||||
símbolo $ genérico. */
|
||||
These maps are hand-written data (Intl exposes neither region → currency nor
|
||||
region → locale). They only define how an amount is RENDERED: the persisted
|
||||
value doesn't change and isn't converted. If the country is in neither map,
|
||||
formatPrice falls back to the generic $ symbol. */
|
||||
|
||||
export const REGION_CURRENCY: Record<string, string> = {
|
||||
// Norteamérica
|
||||
// North America
|
||||
CA: 'CAD',
|
||||
US: 'USD',
|
||||
|
||||
// Latinoamérica y Caribe
|
||||
// Latin America and the Caribbean
|
||||
AR: 'ARS',
|
||||
BO: 'BOB',
|
||||
BR: 'BRL',
|
||||
@@ -40,7 +40,7 @@ export const REGION_CURRENCY: Record<string, string> = {
|
||||
UY: 'UYU',
|
||||
VE: 'VES',
|
||||
|
||||
// Zona euro
|
||||
// Eurozone
|
||||
AT: 'EUR',
|
||||
BE: 'EUR',
|
||||
HR: 'EUR',
|
||||
@@ -62,7 +62,7 @@ export const REGION_CURRENCY: Record<string, string> = {
|
||||
SI: 'EUR',
|
||||
ES: 'EUR',
|
||||
|
||||
// Fuera de la zona euro
|
||||
// Outside the eurozone
|
||||
CH: 'CHF',
|
||||
GB: 'GBP',
|
||||
CZ: 'CZK',
|
||||
@@ -75,15 +75,15 @@ export const REGION_CURRENCY: Record<string, string> = {
|
||||
UA: 'UAH',
|
||||
}
|
||||
|
||||
/** Regional con la que se formatea para cada país. México y Argentina usan
|
||||
separadores distintos (1,234.56 vs 1.234,56), así que el locale va con el
|
||||
país y no solo con el idioma. */
|
||||
/** Locale each country is formatted with. Mexico and Argentina use different
|
||||
separators (1,234.56 vs 1.234,56), so the locale follows the country and not
|
||||
just the language. */
|
||||
export const REGION_LOCALE: Record<string, string> = {
|
||||
// Norteamérica
|
||||
// North America
|
||||
CA: 'en-CA',
|
||||
US: 'en-US',
|
||||
|
||||
// Latinoamérica y Caribe
|
||||
// Latin America and the Caribbean
|
||||
AR: 'es-AR',
|
||||
BO: 'es-BO',
|
||||
BR: 'pt-BR',
|
||||
@@ -105,7 +105,7 @@ export const REGION_LOCALE: Record<string, string> = {
|
||||
UY: 'es-UY',
|
||||
VE: 'es-VE',
|
||||
|
||||
// Zona euro
|
||||
// Eurozone
|
||||
AT: 'de-AT',
|
||||
BE: 'nl-BE',
|
||||
HR: 'hr-HR',
|
||||
@@ -127,7 +127,7 @@ export const REGION_LOCALE: Record<string, string> = {
|
||||
SI: 'sl-SI',
|
||||
ES: 'es-ES',
|
||||
|
||||
// Fuera de la zona euro
|
||||
// Outside the eurozone
|
||||
CH: 'de-CH',
|
||||
GB: 'en-GB',
|
||||
CZ: 'cs-CZ',
|
||||
@@ -140,16 +140,16 @@ export const REGION_LOCALE: Record<string, string> = {
|
||||
UA: 'uk-UA',
|
||||
}
|
||||
|
||||
/* Zona horaria IANA → región ISO 3166-1 alpha-2.
|
||||
/* IANA time zone → ISO 3166-1 alpha-2 region.
|
||||
|
||||
Cobertura: las zonas de los países de arriba, agrupadas por prefijo
|
||||
(America/Argentina/*) o por la ciudad en la zona (Sao_Paulo). Cubre las
|
||||
zonas principales; una zona desconocida cae al país del idioma. */
|
||||
Coverage: the time zones of the countries above, grouped by prefix
|
||||
(America/Argentina/*) or by the city in the zone (Sao_Paulo). It covers the
|
||||
main zones; an unknown zone falls back to the country of the language. */
|
||||
export const TIMEZONE_REGION: Record<string, string> = {
|
||||
// ── Latinoamérica ─────────────────────────────────────────────────────────
|
||||
// ── Latin America ─────────────────────────────────────────────────────────
|
||||
'America/Argentina/': 'AR',
|
||||
// Chromium/ICU reporta en la forma legacy (sin el prefijo "Argentina/") las
|
||||
// zonas argentinas más comunes: America/Argentina/Buenos_Aires → America/Buenos_Aires.
|
||||
// Chromium/ICU reports the most common Argentine zones in the legacy form
|
||||
// (without the "Argentina/" prefix): America/Argentina/Buenos_Aires → America/Buenos_Aires.
|
||||
'America/Buenos_Aires': 'AR',
|
||||
'America/Catamarca': 'AR',
|
||||
'America/Cordoba': 'AR',
|
||||
@@ -182,7 +182,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
|
||||
'America/Santo_Domingo': 'DO',
|
||||
'America/Puerto_Rico': 'PR',
|
||||
|
||||
// ── Norteamérica ─────────────────────────────────────────────────────────
|
||||
// ── North America ─────────────────────────────────────────────────────────
|
||||
'America/New_York': 'US',
|
||||
'America/Detroit': 'US',
|
||||
'America/Chicago': 'US',
|
||||
@@ -199,7 +199,7 @@ export const TIMEZONE_REGION: Record<string, string> = {
|
||||
'America/Regina': 'CA',
|
||||
'America/St_Johns': 'CA',
|
||||
|
||||
// ── Europa ───────────────────────────────────────────────────────────────
|
||||
// ── Europe ───────────────────────────────────────────────────────────────
|
||||
'Europe/Madrid': 'ES',
|
||||
'Atlantic/Canary': 'ES',
|
||||
'Atlantic/Faeroe': 'ES',
|
||||
@@ -244,8 +244,8 @@ export function regionForTimezone(timezone: string | undefined): string | undefi
|
||||
return prefix ? TIMEZONE_REGION[prefix] : undefined
|
||||
}
|
||||
|
||||
/** Región del locale (es-MX → MX). Un locale sin país se maximiza, pero solo
|
||||
como último recurso: countryOf prefiere la zona horaria. */
|
||||
/** Region of the locale (es-MX → MX). A locale without a country is
|
||||
maximized, but only as a last resort: countryOf prefers the time zone. */
|
||||
export function regionOf(locale: string | undefined): string | undefined {
|
||||
if (!locale || typeof Intl.Locale === 'undefined') return undefined
|
||||
try {
|
||||
@@ -255,9 +255,9 @@ export function regionOf(locale: string | undefined): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/** País de la persona: el de la zona horaria, y si no se conoce, el del
|
||||
idioma. `en` sin país no se maximiza a US a propósito: un usuario en
|
||||
México con el browser en inglés caería en dólares. */
|
||||
/** The person's country: the one from the time zone and, when unknown, the one
|
||||
from the language. A bare `en` is deliberately not maximized to US: a user in
|
||||
Mexico with an English browser would end up in dollars. */
|
||||
export function countryOf(locale: string | undefined): string | undefined {
|
||||
return regionForTimezone(browserTimezone()) ?? regionOf(locale)
|
||||
}
|
||||
|
||||
@@ -10,14 +10,14 @@ export default defineConfig({
|
||||
react(),
|
||||
tailwindcss(),
|
||||
VitePWA({
|
||||
// `autoUpdate` activa skipWaiting + clientsClaim: el SW nuevo toma el
|
||||
// control en el próximo load sin pedirle nada al usuario.
|
||||
// `autoUpdate` turns on skipWaiting + clientsClaim: the new SW takes
|
||||
// control on the next load without asking the user for anything.
|
||||
registerType: 'autoUpdate',
|
||||
// El registro se hace desde PwaProvider para poder avisar cuando la app
|
||||
// ya está lista para operar sin conexión.
|
||||
// Registration is done from PwaProvider so we can tell the user when the
|
||||
// app is ready to work offline.
|
||||
injectRegister: null,
|
||||
// Los iconos ya entran por `workbox.globPatterns`; con
|
||||
// `includeManifestIcons` se listarían dos veces en el precache.
|
||||
// The icons already come in through `workbox.globPatterns`; with
|
||||
// `includeManifestIcons` they would be listed twice in the precache.
|
||||
includeManifestIcons: false,
|
||||
manifest: {
|
||||
name: 'Gruperly',
|
||||
@@ -48,24 +48,26 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
workbox: {
|
||||
// El woff2 de Inter se importa desde node_modules: Vite lo emite a
|
||||
// assets/ con hash y entra al precache para que la app abra offline.
|
||||
// Inter's woff2 is imported from node_modules: Vite emits it to
|
||||
// assets/ with a hash and it goes into the precache so the app opens
|
||||
// offline.
|
||||
globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'],
|
||||
// Solo el script del SW queda fuera: precachearlo cachearía la versión
|
||||
// vieja. El runtime `workbox-<hash>.js` sí se precachea a propósito, así
|
||||
// el SW puede arrancar sin red. No usar `**/workbox-*.js`: ese patrón
|
||||
// también matchea `workbox-window.*.js`, que es el módulo cliente que
|
||||
// importa `virtual:pwa-register` y sin él falla el registro.
|
||||
// Only the SW script is left out: precaching it would cache the old
|
||||
// version. The `workbox-<hash>.js` runtime *is* precached on purpose, so
|
||||
// the SW can boot without network. Do not use `**/workbox-*.js`: that
|
||||
// pattern also matches `workbox-window.*.js`, which is the client module
|
||||
// that imports `virtual:pwa-register` and without it registration fails.
|
||||
globIgnores: ['**/sw.js'],
|
||||
// App shell para toda navegación, incluidas las rutas profundas
|
||||
// /join/$token y /report-absence/$token.
|
||||
// App shell for every navigation, including the deep routes
|
||||
// /join/$token and /report-absence/$token.
|
||||
navigateFallback: '/index.html',
|
||||
navigateFallbackDenylist: [/^\/api\//],
|
||||
cleanupOutdatedCaches: true,
|
||||
runtimeCaching: [
|
||||
{
|
||||
// La API nunca se cachea: son datos de cobros y una respuesta
|
||||
// vieja sería peor que un error. Offline carga el shell, no los datos.
|
||||
// The API is never cached: it holds payment data and a stale
|
||||
// response is worse than an error. Offline loads the shell, not
|
||||
// the data.
|
||||
urlPattern: ({ url, request }) => request.method !== 'GET' || url.pathname.startsWith('/api/'),
|
||||
handler: 'NetworkOnly',
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user