feat(api): add timezone support for group fetching and increase page size
feat(attendance): refactor attendance summary logic and update tests feat(analytics): extend GroupRiskSummary schema with absence and attendance counts feat(groups): enhance group schema with attendee and waitlist counts chore(skills): add frontend design skill with guidelines and license feat(attendee-detail): implement AttendeePhoneLine component for phone display feat(groups): create AttendanceBadge and CapacityIndicator components for group cards feat(groups): add card utility functions for attendance alerts and capacity summaries test(groups): implement tests for attendance alert and capacity summary logic
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { forwardRef, type HTMLAttributes } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral'
|
||||
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' | 'info'
|
||||
|
||||
export type BadgeProps = HTMLAttributes<HTMLSpanElement> & {
|
||||
variant?: BadgeVariant
|
||||
@@ -12,6 +12,11 @@ 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. */
|
||||
info: 'bg-accent-soft text-accent-fg',
|
||||
}
|
||||
|
||||
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useId, useState } from 'react'
|
||||
import { Check, ChevronDown, Copy, MessageCircle } from 'lucide-react'
|
||||
import { Check, Copy, MessageCircle } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ACTION_BUTTON_CLASS } from './actionButton'
|
||||
import { SECTION_TITLE_CLASS, Section } from './Section'
|
||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||
import { Section } from './Section'
|
||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||
|
||||
export function AbsenceLinkSection() {
|
||||
@@ -25,66 +25,52 @@ export function AbsenceLinkSection() {
|
||||
|
||||
return (
|
||||
<Section
|
||||
title={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen((value) => !value)}
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={panelId}
|
||||
className={cn(
|
||||
SECTION_TITLE_CLASS,
|
||||
'flex min-h-11 w-full items-center gap-1.5 text-left',
|
||||
)}
|
||||
>
|
||||
Link de ausencias
|
||||
<ChevronDown
|
||||
className={cn('size-4 transition-transform', isOpen && 'rotate-180')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
}
|
||||
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. */}
|
||||
<div id={panelId} hidden={!isOpen}>
|
||||
<div className="pt-1">
|
||||
<p className="text-sm text-foreground">
|
||||
Mandales este link para que avisen cuando no puedan venir.
|
||||
</p>
|
||||
<div className="mt-2.5 flex flex-col gap-2 sm:flex-row">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(url)}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||
>
|
||||
<Copy className="size-4" aria-hidden="true" />
|
||||
Copiar link
|
||||
</button>
|
||||
{shareUrl ? (
|
||||
<a
|
||||
href={shareUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
Enviar por WhatsApp
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
<p
|
||||
aria-live="polite"
|
||||
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
|
||||
<p className="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. */}
|
||||
<div className="mt-2.5 flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(url)}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="size-3.5" aria-hidden="true" />
|
||||
Link copiado
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
<Copy className="size-4" aria-hidden="true" />
|
||||
Copiar link
|
||||
</button>
|
||||
{shareUrl ? (
|
||||
<a
|
||||
href={shareUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
|
||||
className={PRIMARY_ACTION_CLASS}
|
||||
>
|
||||
<MessageCircle className="size-4" aria-hidden="true" />
|
||||
Enviar por WhatsApp
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
<p
|
||||
aria-live="polite"
|
||||
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="size-3.5" aria-hidden="true" />
|
||||
Link copiado
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import { cn } from '../../lib/utils'
|
||||
import {
|
||||
attendanceStatusClass,
|
||||
attendanceStatusLabel,
|
||||
attendanceSummaryLabel,
|
||||
attendanceSummary,
|
||||
formatSessionShortDate,
|
||||
HISTORY_LIMIT,
|
||||
HISTORY_PREVIEW,
|
||||
@@ -67,14 +67,15 @@ export function AttendeeAttendanceSection() {
|
||||
const visible = visibleSessions(sessions, showAll)
|
||||
const hasMore = sessions.length > HISTORY_PREVIEW
|
||||
const isCapped = sessions.length >= HISTORY_LIMIT
|
||||
const summary = attendanceSummary(visible)
|
||||
|
||||
return (
|
||||
<Section title="Asistencia" trailing={attendanceSummaryLabel(visible)}>
|
||||
<Section title="Asistencia" trailing={summary.label}>
|
||||
<ul className="divide-y divide-border/60">
|
||||
{visible.map((session) => {
|
||||
const Icon = iconFor(session.status)
|
||||
return (
|
||||
<li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2.5">
|
||||
<li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2">
|
||||
<span className="truncate text-sm text-primary">
|
||||
{formatSessionShortDate(session.startsAt)}
|
||||
</span>
|
||||
@@ -92,6 +93,12 @@ 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. */}
|
||||
{summary.unmarkedLabel ? (
|
||||
<p className="pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
|
||||
) : null}
|
||||
|
||||
{showAll && isCapped ? (
|
||||
<p className="pt-2 text-xs text-foreground">
|
||||
El historial guarda las últimas {HISTORY_LIMIT} clases.
|
||||
@@ -104,7 +111,7 @@ export function AttendeeAttendanceSection() {
|
||||
variant="ghost"
|
||||
onClick={() => setShowAll((value) => !value)}
|
||||
aria-expanded={showAll}
|
||||
className="h-11 gap-1 px-2 text-sm text-accent hover:text-accent-strong"
|
||||
className="h-11 gap-1 px-2 text-sm text-accent-fg hover:text-primary"
|
||||
>
|
||||
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
|
||||
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
|
||||
|
||||
@@ -16,6 +16,9 @@ export function AttendeeContactActions() {
|
||||
|
||||
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. */}
|
||||
<a
|
||||
href={`https://wa.me/${digits}`}
|
||||
target="_blank"
|
||||
@@ -23,7 +26,7 @@ export function AttendeeContactActions() {
|
||||
aria-label={`Abrir WhatsApp con ${label}`}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||
>
|
||||
<MessageCircle className="size-4 text-accent" aria-hidden="true" />
|
||||
<MessageCircle className="size-4 text-accent-fg" aria-hidden="true" />
|
||||
WhatsApp
|
||||
</a>
|
||||
<a
|
||||
@@ -31,7 +34,7 @@ export function AttendeeContactActions() {
|
||||
aria-label={`Llamar a ${label}`}
|
||||
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
|
||||
>
|
||||
<Phone className="size-4 text-accent" aria-hidden="true" />
|
||||
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
||||
Llamar
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -1,64 +1,37 @@
|
||||
import { Check, Copy, Mail } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { Mail } from 'lucide-react'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { Section } from './Section'
|
||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||
|
||||
const ROW_CLASS =
|
||||
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg 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.
|
||||
*
|
||||
* 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). */
|
||||
export function AttendeeContactSection() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
|
||||
if (!attendee) return null
|
||||
|
||||
const phone = attendee.phone
|
||||
const phoneLabel = formatPhoneDisplay(phone)
|
||||
const { email, notes } = attendee
|
||||
// Sin datos no hay sección: no se dibujan filas con "Sin email"/"Sin notas".
|
||||
if (!phoneLabel && !email && !notes) return null
|
||||
if (!email && !notes) return null
|
||||
|
||||
return (
|
||||
<Section title="Contacto">
|
||||
<div className="divide-y divide-border/60">
|
||||
{phone && phoneLabel ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(phone)}
|
||||
className={cn(ROW_CLASS, 'min-w-0 flex-1 text-left')}
|
||||
>
|
||||
<span className="truncate text-base text-primary">{phoneLabel}</span>
|
||||
<span className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-foreground">
|
||||
{copied ? (
|
||||
<Check className="size-4 text-success" aria-hidden="true" />
|
||||
) : (
|
||||
<Copy className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
{copied ? 'Copiado' : 'Copiar'}
|
||||
</span>
|
||||
</button>
|
||||
{/* La confirmación visible no se anuncia sola: va en una región viva
|
||||
aparte para no ensuciar el nombre accesible del botón. */}
|
||||
<span aria-live="polite" className="sr-only">
|
||||
{copied ? 'Teléfono copiado al portapapeles' : ''}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{email ? (
|
||||
<a href={`mailto:${email}`} className={ROW_CLASS}>
|
||||
<span className="truncate text-base text-primary">{email}</span>
|
||||
<span className="truncate text-sm text-primary">{email}</span>
|
||||
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
{notes ? (
|
||||
<p className="whitespace-pre-line py-2.5 text-sm leading-relaxed text-primary">
|
||||
{notes}
|
||||
</p>
|
||||
<p className="whitespace-pre-line py-2 text-sm leading-relaxed text-primary">{notes}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { AttendeeActionsMenu } from './AttendeeActionsMenu'
|
||||
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
|
||||
import { AttendeeContactActions } from './AttendeeContactActions'
|
||||
import { AttendeeContactSection } from './AttendeeContactSection'
|
||||
import { AttendeePhoneLine } from './AttendeePhoneLine'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||
import { formatMemberSince } from './attendance'
|
||||
@@ -36,7 +37,7 @@ export function AttendeeDetailView() {
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mt-4 px-0 text-accent hover:bg-transparent hover:text-accent-strong"
|
||||
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
|
||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||
>
|
||||
Volver al grupo
|
||||
@@ -67,15 +68,17 @@ export function AttendeeDetailView() {
|
||||
<p className="mt-1 whitespace-nowrap text-sm text-foreground">
|
||||
Miembro desde {formatMemberSince(attendee.createdAt)}
|
||||
</p>
|
||||
<AttendeePhoneLine />
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="mt-3">
|
||||
<AttendeeContactActions />
|
||||
</div>
|
||||
|
||||
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
|
||||
arriba de Asistencia; el layout no se toca. */}
|
||||
<div className="mt-6 space-y-5">
|
||||
arriba de Asistencia; cada sección lleva su propio aire, así que el
|
||||
layout no se toca. */}
|
||||
<div className="mt-5">
|
||||
<AttendeeAttendanceSection />
|
||||
<AttendeeContactSection />
|
||||
<AbsenceLinkSection />
|
||||
|
||||
45
apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx
Normal file
45
apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../lib/format'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||
|
||||
/** Teléfono como segunda línea del subtítulo.
|
||||
*
|
||||
* 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. */
|
||||
export function AttendeePhoneLine() {
|
||||
const { attendee } = useAttendeeDetail()
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
|
||||
const phone = attendee?.phone
|
||||
const label = formatPhoneDisplay(phone)
|
||||
if (!phone || !label) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copy(phone)}
|
||||
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. */}
|
||||
{copied ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
|
||||
>
|
||||
<Check className="size-3.5" />
|
||||
Número copiado
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
<span aria-live="polite" className="sr-only">
|
||||
{copied ? 'Número copiado al portapapeles' : ''}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,40 +1,82 @@
|
||||
import { useId } from 'react'
|
||||
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. */
|
||||
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. */
|
||||
const TOGGLE_ROW_CLASS = cn(
|
||||
SECTION_TITLE_CLASS,
|
||||
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg text-left text-primary',
|
||||
'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',
|
||||
)
|
||||
|
||||
type SectionProps = {
|
||||
/** Título de la sección. Un string por lo general; un botón cuando la
|
||||
* sección se despliega desde el propio título (ver Link de ausencias). */
|
||||
/** Título de la sección. Un string por lo general. */
|
||||
title: ReactNode
|
||||
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
|
||||
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. */
|
||||
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).
|
||||
*
|
||||
* La pantalla se arma apilando secciones en este orden, así que sumar una
|
||||
* nueva (Pagos, por ejemplo) es insertar otro bloque y nada más. */
|
||||
export function Section({ title, trailing, children }: SectionProps) {
|
||||
* 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. */
|
||||
export function Section({ title, trailing, toggle, children }: SectionProps) {
|
||||
const headingId = useId()
|
||||
|
||||
return (
|
||||
<section aria-labelledby={headingId} className="border-t border-border/70 pt-5">
|
||||
<section aria-labelledby={headingId} className="border-t border-border/70 py-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 id={headingId} className={SECTION_TITLE_CLASS}>
|
||||
{title}
|
||||
</h2>
|
||||
{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).
|
||||
<h2 id={headingId} className="min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={toggle.isOpen}
|
||||
aria-controls={toggle.panelId}
|
||||
onClick={toggle.onToggle}
|
||||
className={TOGGLE_ROW_CLASS}
|
||||
>
|
||||
<span className="truncate">{title}</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-4 shrink-0 transition-transform',
|
||||
toggle.isOpen && 'rotate-180',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
</h2>
|
||||
) : (
|
||||
<h2 id={headingId} className={SECTION_TITLE_CLASS}>
|
||||
{title}
|
||||
</h2>
|
||||
)}
|
||||
{trailing ? (
|
||||
<div className="shrink-0 text-xs font-semibold tabular-nums text-foreground">
|
||||
{trailing}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-2.5">{children}</div>
|
||||
<div className="mt-2">{children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,3 +6,10 @@
|
||||
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
|
||||
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. */
|
||||
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'
|
||||
|
||||
@@ -70,8 +70,34 @@ export function visibleSessions(
|
||||
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
|
||||
}
|
||||
|
||||
/** "3 de 5 clases", contando solo las sesiones que se están mostrando. */
|
||||
export function attendanceSummaryLabel(sessions: AttendanceSession[]): string {
|
||||
const present = sessions.filter((session) => session.status === 'PRESENT').length
|
||||
return `${present} de ${classCountLabel(sessions.length)}`
|
||||
/** 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. */
|
||||
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. */
|
||||
label: string
|
||||
/** "2 sin registrar", o `null` si no hay clases sin registro. */
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
|
||||
const marked = markedSessions(sessions)
|
||||
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }
|
||||
|
||||
const present = marked.filter((session) => session.status === 'PRESENT').length
|
||||
const unmarked = sessions.length - marked.length
|
||||
return {
|
||||
label: `${present} de ${classCountLabel(marked.length)}`,
|
||||
unmarkedLabel: unmarked > 0 ? `${unmarked} sin registrar` : null,
|
||||
}
|
||||
}
|
||||
|
||||
45
apps/web/src/features/groups/AttendanceBadge.tsx
Normal file
45
apps/web/src/features/groups/AttendanceBadge.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { TriangleAlert } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import type { AttendanceAlert } from './card'
|
||||
|
||||
/**
|
||||
* Badge compacto de alerta de asistencia: ícono de advertencia + la cantidad
|
||||
* de miembros afectados.
|
||||
*
|
||||
* El número solo no se explica: en el caso grave se le suma el motivo corto
|
||||
* ("bajo 50%", "con faltas"), porque un "⚠ 6" suelto al lado de "12/20 miembros"
|
||||
* se lee como otro dato del cupo. El caso leve se queda con el número —la
|
||||
* tarjeta es una lista, no un informe— y la frase entera vive en el `title`
|
||||
* y en el nombre accesible.
|
||||
*
|
||||
* Nunca lleva relleno sólido: los dos casos son translúcidos, y lo que los
|
||||
* diferencia es el tono (ámbar `warning` vs naranja `warning-strong`) y ese
|
||||
* texto extra. Contraste del texto sobre su propio fondo: 7.0:1 en oscuro y
|
||||
* 4.8:1 en claro.
|
||||
*
|
||||
* El badge NO usa el `Tooltip` del repo: ese envuelve al disparador en un
|
||||
* `<button>` y acá el disparador es el padre, un link que ocupa toda la
|
||||
* tarjeta (un botón dentro de un link no es HTML válido y rompe la
|
||||
* navegación). En su lugar el texto completo viaja como `aria-label` (con
|
||||
* `role="img"`, que reemplaza lo visible por la frase al calcular el nombre
|
||||
* accesible del enlace) y como `title` para el puntero de ratón.
|
||||
*/
|
||||
export function AttendanceBadge({ alert }: { alert: AttendanceAlert }) {
|
||||
const severe = alert.severity === 'high'
|
||||
|
||||
return (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={alert.label}
|
||||
title={alert.label}
|
||||
className={cn(
|
||||
'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium tabular-nums',
|
||||
severe ? 'bg-warning-strong-soft text-warning-strong' : 'bg-warning-soft text-warning',
|
||||
)}
|
||||
>
|
||||
<TriangleAlert className="size-3 shrink-0" aria-hidden="true" />
|
||||
{alert.count}
|
||||
{severe ? <span>{alert.short}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
72
apps/web/src/features/groups/CapacityIndicator.tsx
Normal file
72
apps/web/src/features/groups/CapacityIndicator.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { Users } from 'lucide-react'
|
||||
import { Badge } from '../../components/ui'
|
||||
import { capacitySummary } from './card'
|
||||
|
||||
/**
|
||||
* Bloque de metadatos de la tarjeta: texto de ocupación, barrita fina y el
|
||||
* badge neutro de lista de espera. Va con `shrink-0` porque la fila de arriba
|
||||
* hace wrap: si algo tiene que bajar de línea, que sea el badge de alerta,
|
||||
* no un número de cupo recortado.
|
||||
*
|
||||
* El texto "12/20 miembros" es el que se lee de verdad y el que queda en el
|
||||
* nombre accesible del enlace; la barrita está para que la proporcion se
|
||||
* escanee de un vistazo sin tener que restar. Por eso el track va al 30% y no
|
||||
* al 20%: así se ve la parte que falta (1.9:1 contra la tarjeta) sin que el
|
||||
* relleno pierda su contraste contra el fondo de la barra (3.8:1).
|
||||
*
|
||||
* Nada de esto se pinta de amarillo: el amarillo es solo para la alerta de
|
||||
* asistencia, así que el cupo lleno se lee por el "20/20" y, cuando hay gente
|
||||
* esperando, por el badge. Los colores salen de `accent-fg`, que es la tinta
|
||||
* de acento legible (7.1:1 en oscuro, 6.2:1 en claro); el `accent` directo
|
||||
* sobre la tarjeta oscura da 2.2:1 y no alcanza el mínimo de 3:1.
|
||||
*/
|
||||
export function CapacityIndicator({
|
||||
attendeesCount,
|
||||
capacity,
|
||||
waitlistCount,
|
||||
}: {
|
||||
attendeesCount: number
|
||||
capacity: number | null
|
||||
waitlistCount: number
|
||||
}) {
|
||||
const { label, occupancy, hasCapacity, isFull, waitlistCount: waiting } = capacitySummary(
|
||||
attendeesCount,
|
||||
capacity,
|
||||
waitlistCount,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<Users className="size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
||||
|
||||
<span className="shrink-0 text-sm tabular-nums text-secondary">{label}</span>
|
||||
|
||||
{hasCapacity ? (
|
||||
/* Va `aria-hidden` a propósito: el texto de al lado ya dice "12/20
|
||||
miembros" y es el que tiene que leerse (y annonce el enlace entero).
|
||||
Anunciarlo también como progressbar solo sumaba "12 de 20 lugares
|
||||
ocupados" al nombre accesible de la tarjeta, que es toda la card. */
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="h-1.5 w-14 shrink-0 overflow-hidden rounded-full bg-accent-fg/30"
|
||||
>
|
||||
<span
|
||||
className="block h-full rounded-full bg-accent-fg transition-[width] duration-300 ease-out"
|
||||
style={{ width: `${Math.round(occupancy * 100)}%` }}
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{waiting > 0 ? (
|
||||
<Badge
|
||||
variant="info"
|
||||
title={`${waiting} ${waiting === 1 ? 'persona' : 'personas'} en lista de espera`}
|
||||
>
|
||||
{waiting} en espera
|
||||
</Badge>
|
||||
) : null}
|
||||
|
||||
{isFull && waiting === 0 ? <span className="sr-only">Cupo completo</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,82 +1,93 @@
|
||||
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { CalendarClock, Users } from 'lucide-react'
|
||||
import { Badge, Button, Tooltip } from '../../components/ui'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
|
||||
import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { CalendarClock, ChevronRight } from 'lucide-react'
|
||||
import { formatPrice, formatSchedule } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { RISK_HINT, RISK_LABELS } from './constants'
|
||||
import { AttendanceBadge } from './AttendanceBadge'
|
||||
import { CapacityIndicator } from './CapacityIndicator'
|
||||
import { attendanceAlert, billingSuffix } from './card'
|
||||
|
||||
/* Toda la card es el link al grupo: nombre, horario y cupo quedan dentro, así
|
||||
que el nombre accesible del enlace ya los anuncia y no hace falta un
|
||||
aria-label aparte. La superficie va rellena (la misma `primary-soft` que la
|
||||
ficha del grupo) porque el borde fino sobre el fondo se perdía en tema
|
||||
oscuro.
|
||||
|
||||
El borde derecho es un riel rígido de tres pistas —`1fr · auto · 1rem`— en
|
||||
vez de posiciones absolutas: el precio y la flecha comparten el mismo
|
||||
track, así que su límite derecho es idéntico en todas las tarjetas sin
|
||||
importar cuánto mida el nombre o el precio. El precio se alinea con la
|
||||
primera línea (junto al nombre) y la flecha también, para que la fila se
|
||||
lea como una sola cosa.
|
||||
|
||||
La fila de metadatos hace wrap: con cupo de dos dígitos, gente en espera y
|
||||
la alerta, no entra en 360px y preferimos que el badge baje de línea antes
|
||||
que recortar un número. El bloque de cupo va con `shrink-0` para que sea
|
||||
siempre el último en caer. */
|
||||
|
||||
export function GroupCard({
|
||||
group,
|
||||
riskLevel,
|
||||
risk,
|
||||
}: {
|
||||
group: GroupDto
|
||||
riskLevel: GroupRiskLevel
|
||||
group: GroupListItem
|
||||
risk: GroupRiskSummary | undefined
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const hasSchedule = (group.days?.length ?? 0) > 0
|
||||
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
|
||||
const days = group.days ?? []
|
||||
const hasSchedule = days.length > 0
|
||||
const hasPrice = group.price != null
|
||||
const suffix = billingSuffix(group.billingType)
|
||||
const alert = attendanceAlert(risk, group.attendeesCount)
|
||||
// La misma regla que usa el badge para el color: cuando media matrícula o
|
||||
// más está atrasada, la tarjeta entera se marca. El anillo va `inset` (no
|
||||
// agrega borde ni cambia el alto) y al 40% porque un trazo fuerte rompe el
|
||||
// tono de la lista — es refuerzo visual, el que se lee sin color es el
|
||||
// badge, que ya pasa 4.5:1.
|
||||
const severe = alert?.severity === 'high'
|
||||
|
||||
return (
|
||||
<article className="rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/40">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3>
|
||||
{group.description ? (
|
||||
<p className="mt-0.5 truncate text-sm text-foreground/60">{group.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
{hasRisk ? (
|
||||
// Mismo tooltip que en el detalle: el badge es corto y la
|
||||
// explicación (abandono, no cobranza) la da el tooltip.
|
||||
<Tooltip content={RISK_HINT} tooltipClassName="left-auto right-0">
|
||||
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
'size-2 rounded-full',
|
||||
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{RISK_LABELS[riskLevel]}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Badge variant="success">Activo</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasSchedule ? (
|
||||
<dl className="mt-4 space-y-2 text-sm">
|
||||
<div className="flex items-center gap-2 text-foreground/70">
|
||||
<CalendarClock className="size-4 shrink-0 text-accent" />
|
||||
<span>{formatSchedule(group.days ?? [], group.time)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-foreground/70">
|
||||
<Users className="size-4 shrink-0 text-accent" />
|
||||
<span>
|
||||
Cupo {group.capacity ?? '—'} miembros
|
||||
{group.price != null
|
||||
? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}`
|
||||
: ''}
|
||||
{group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
</dl>
|
||||
) : (
|
||||
<p className="mt-4 text-sm text-foreground/50">Aún sin plan de cobro configurado.</p>
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId: group.id }}
|
||||
className={cn(
|
||||
'block rounded-xl bg-primary-soft p-4 transition-colors duration-150 ease-out hover:bg-accent-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:bg-accent-soft/60',
|
||||
severe && 'ring-1 ring-warning-strong/40 ring-inset',
|
||||
)}
|
||||
>
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto_1rem] items-start gap-x-2">
|
||||
<h3 className="col-start-1 row-start-1 truncate text-base font-semibold text-primary">
|
||||
{group.name}
|
||||
</h3>
|
||||
|
||||
<div className="mt-4 flex items-center justify-end gap-2 border-t border-border pt-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void navigate({ to: `/groups/${group.id}` })}
|
||||
>
|
||||
Gestionar Miembros
|
||||
</Button>
|
||||
{hasPrice ? (
|
||||
<p className="col-start-2 row-start-1 whitespace-nowrap text-base font-semibold tabular-nums text-primary">
|
||||
{formatPrice(group.price)}
|
||||
{suffix ? (
|
||||
<span className="text-sm font-medium text-secondary">{suffix}</span>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ChevronRight
|
||||
className="col-start-3 row-start-1 mt-1 size-4 shrink-0 text-secondary/50"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<p className="col-start-1 row-start-2 mt-1 flex min-w-0 items-center gap-2 text-sm text-secondary">
|
||||
<CalendarClock className="size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
||||
<span className="truncate">
|
||||
{hasSchedule ? formatSchedule(days, group.time) : 'Sin horario definido'}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div className="col-span-3 row-start-3 mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5">
|
||||
<CapacityIndicator
|
||||
attendeesCount={group.attendeesCount}
|
||||
capacity={group.capacity}
|
||||
waitlistCount={group.waitlistCount}
|
||||
/>
|
||||
{alert ? <AttendanceBadge alert={alert} /> : null}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2, Plus } from 'lucide-react'
|
||||
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { getGroups, getGroupsRiskOverview } from '../../lib/api'
|
||||
import { GroupCard } from './GroupCard'
|
||||
@@ -17,25 +17,30 @@ export function GroupsView() {
|
||||
})
|
||||
|
||||
const riskByGroup = new Map(
|
||||
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]),
|
||||
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item]),
|
||||
)
|
||||
|
||||
return (
|
||||
<section>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
||||
<p className="mt-2 text-sm text-foreground/60">Tus grupos de cobranza.</p>
|
||||
</div>
|
||||
<Button variant="primary" onClick={() => void navigate({ to: '/groups/new' })}>
|
||||
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
||||
{/* `h-11` arriba del `md` del primitivo: son 40px y el mínimo táctil es
|
||||
44. Se sube acá y no en `Button` porque cambiar la altura del
|
||||
primitivo mueve todas las pantallas de la app de un golpe. */}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="h-11"
|
||||
onClick={() => void navigate({ to: '/groups/new' })}
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Crear
|
||||
Nuevo grupo
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{groupsQuery.isPending ? (
|
||||
<div className="mt-8 flex items-center justify-center py-16">
|
||||
<Loader2 className="size-6 animate-spin text-foreground/40" />
|
||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||
<span className="sr-only">Cargando grupos</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -49,33 +54,38 @@ export function GroupsView() {
|
||||
) : null}
|
||||
|
||||
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? (
|
||||
<div className="mt-8 rounded-xl border border-dashed border-border bg-surface px-4 py-12 text-center">
|
||||
<p className="font-medium text-primary">Todavía no tenés grupos</p>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
Crea tu primer grupo para empezar a cobrar.
|
||||
/* 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. */
|
||||
<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" />
|
||||
</span>
|
||||
<p className="mt-4 text-base font-semibold text-primary">Todavía no tenés grupos</p>
|
||||
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
|
||||
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="mt-5"
|
||||
className="mt-6 h-11"
|
||||
onClick={() => void navigate({ to: '/groups/new' })}
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Crear tu primer grupo
|
||||
Crear primer grupo
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? (
|
||||
<div className="mt-6 grid gap-4">
|
||||
<div className="mt-6 grid gap-3">
|
||||
{groupsQuery.data.data.map((group) => (
|
||||
<GroupCard
|
||||
key={group.id}
|
||||
group={group}
|
||||
riskLevel={riskByGroup.get(group.id) ?? 'NONE'}
|
||||
risk={riskByGroup.get(group.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
129
apps/web/src/features/groups/card.ts
Normal file
129
apps/web/src/features/groups/card.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import type { BillingType, GroupRiskSummary } 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.
|
||||
|
||||
La API manda dos contadores disjuntos por grupo (`absenceStreakCount` y
|
||||
`lowAttendanceCount`): miembros que acumulan 2+ faltas seguidas sin
|
||||
justificar, o que cruzan el mínimo mensual de asistencia. Ver
|
||||
`apps/backend/src/modules/analytics/lib/risk.ts`. */
|
||||
|
||||
export type AttendanceAlert = {
|
||||
/** Miembros que disparan la regla. Es el número que va en el badge. */
|
||||
count: number
|
||||
/** Frase entera: "4 miembros con asistencia menor al 50%". Va como nombre accesible y title. */
|
||||
label: string
|
||||
severity: AttendanceSeverity
|
||||
/** Texto corto que acompaña al número cuando el caso es grave: "bajo 50%", "con faltas". */
|
||||
short: string
|
||||
}
|
||||
|
||||
/* Umbral de severidad: desde la mitad de los miembros el problema ya no es de
|
||||
una persona suelta sino del grupo, y por eso el badge cambia de color y la
|
||||
tarjeta se tiñe. Antes de ese umbral alcanza con marcarlo sin robarle el
|
||||
foco a la tarjeta. Se compara contra la matrícula, no contra el cupo: el
|
||||
cupo puede no estar definido o ser mucho mayor que la cantidad real de
|
||||
miembros. */
|
||||
const PROMINENT_SHARE = 0.5
|
||||
|
||||
export type AttendanceSeverity = 'low' | 'high'
|
||||
|
||||
/**
|
||||
* Única fuente de la regla de severidad: la usan la tarjeta (para el borde) y
|
||||
* el badge (para el color y el texto), así que no pueden desincronizarse.
|
||||
*/
|
||||
export function getAttendanceSeverity(
|
||||
affectedCount: number,
|
||||
attendeesCount: number,
|
||||
): AttendanceSeverity {
|
||||
if (attendeesCount <= 0) return 'low'
|
||||
return affectedCount / attendeesCount >= PROMINENT_SHARE ? 'high' : 'low'
|
||||
}
|
||||
|
||||
/**
|
||||
* Qué alerta de asistencia corresponde al grupo, si alguna.
|
||||
*
|
||||
* Cuando hay miembros de los dos tipos solo se reporta el de faltas seguidas:
|
||||
* es la señal más accionable (alguien se está yendo) y en un badge chico una
|
||||
* sola frase alcanza para explicar el ícono. La ficha del grupo y las
|
||||
* estadísticas sí muestran las dos.
|
||||
*/
|
||||
export function attendanceAlert(
|
||||
risk: GroupRiskSummary | undefined,
|
||||
attendeesCount: number,
|
||||
): AttendanceAlert | null {
|
||||
const reason = dominantReason(risk)
|
||||
if (!reason || attendeesCount <= 0) return null
|
||||
|
||||
return {
|
||||
count: reason.count,
|
||||
label: `${membersLabel(reason.count)} ${reason.text}`,
|
||||
severity: getAttendanceSeverity(reason.count, attendeesCount),
|
||||
short: reason.short,
|
||||
}
|
||||
}
|
||||
|
||||
/* `short` es el texto que se suma al número cuando el caso es grave: el número
|
||||
solo no dice por qué, y la versión larga se reserva para el title y para el
|
||||
nombre accesible. El detalle entero vive en la ficha del grupo. */
|
||||
function dominantReason(
|
||||
risk: GroupRiskSummary | undefined,
|
||||
): { count: number; short: string; text: string } | null {
|
||||
if (!risk) return null
|
||||
|
||||
if (risk.absenceStreakCount > 0) {
|
||||
return {
|
||||
count: risk.absenceStreakCount,
|
||||
short: 'con faltas',
|
||||
text: 'con faltas seguidas',
|
||||
}
|
||||
}
|
||||
if (risk.lowAttendanceCount > 0) {
|
||||
return {
|
||||
count: risk.lowAttendanceCount,
|
||||
short: 'bajo 50%',
|
||||
text: 'con asistencia menor al 50%',
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export type CapacitySummary = {
|
||||
/** "4/5 miembros", o "1 miembro" cuando el grupo no tiene cupo definido. */
|
||||
label: string
|
||||
/** 0..1, para la barrita de ocupación. 0 cuando no hay cupo. */
|
||||
occupancy: number
|
||||
hasCapacity: boolean
|
||||
isFull: boolean
|
||||
waitlistCount: number
|
||||
}
|
||||
|
||||
export function capacitySummary(
|
||||
attendeesCount: number,
|
||||
capacity: number | null,
|
||||
waitlistCount: number,
|
||||
): CapacitySummary {
|
||||
const hasCapacity = capacity != null
|
||||
|
||||
return {
|
||||
// Con cupo la unidad es el lugar ("1/5 miembros"), así que el plural no
|
||||
// depende de cuánta gente haya: depende del denominador.
|
||||
label: hasCapacity ? `${attendeesCount}/${capacity} miembros` : membersLabel(attendeesCount),
|
||||
occupancy: hasCapacity && capacity > 0 ? Math.min(attendeesCount / capacity, 1) : 0,
|
||||
hasCapacity,
|
||||
isFull: hasCapacity && attendeesCount >= capacity,
|
||||
waitlistCount,
|
||||
}
|
||||
}
|
||||
|
||||
/** Sufijo del precio según cómo se cobra: "/mes" o "/clase". */
|
||||
export function billingSuffix(billingType: BillingType | null): string | null {
|
||||
if (billingType === 'MONTHLY') return '/mes'
|
||||
if (billingType === 'PER_CLASS') return '/clase'
|
||||
return null
|
||||
}
|
||||
|
||||
function membersLabel(count: number): string {
|
||||
return count === 1 ? '1 miembro' : `${count} miembros`
|
||||
}
|
||||
@@ -8,4 +8,8 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
|
||||
/* 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. */
|
||||
export const RISK_HINT =
|
||||
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
|
||||
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
|
||||
|
||||
/* El motivo concreto ("4 miembros con faltas seguidas") ya no se calcula acá:
|
||||
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. */
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-soft: var(--primary-soft);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-strong: var(--accent-strong);
|
||||
--color-accent-soft: var(--accent-soft);
|
||||
@@ -60,6 +61,8 @@
|
||||
--color-success-soft: var(--success-soft);
|
||||
--color-warning: var(--warning);
|
||||
--color-warning-soft: var(--warning-soft);
|
||||
--color-warning-strong: var(--warning-strong);
|
||||
--color-warning-strong-soft: var(--warning-strong-soft);
|
||||
--color-danger: var(--danger);
|
||||
--color-danger-soft: var(--danger-soft);
|
||||
|
||||
@@ -116,6 +119,12 @@
|
||||
--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: #475569;
|
||||
--accent: #2544ea;
|
||||
--accent-strong: #1d33d8;
|
||||
--accent-soft: #eef4ff;
|
||||
@@ -127,6 +136,11 @@
|
||||
--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. */
|
||||
--warning-strong: #c2410c;
|
||||
--warning-strong-soft: #fff7ed;
|
||||
--danger: #f43f5e;
|
||||
--danger-soft: #fff1f2;
|
||||
}
|
||||
@@ -140,6 +154,11 @@
|
||||
--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: #a8b6c8;
|
||||
--accent: #2544ea;
|
||||
--accent-strong: #1d33d8;
|
||||
--accent-soft: color-mix(in srgb, var(--brand-500) 15%, transparent);
|
||||
@@ -151,6 +170,11 @@
|
||||
--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. */
|
||||
--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);
|
||||
}
|
||||
|
||||
@@ -46,6 +46,8 @@ import type {
|
||||
UpdateStudentStatusResult,
|
||||
} from '@gruperly/shared'
|
||||
|
||||
import { browserTimezone } from './region'
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000'
|
||||
|
||||
export class ApiError extends Error {
|
||||
@@ -106,15 +108,23 @@ export const createGroup = (payload: CreateFirstGroup) =>
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const getGroups = () => apiFetch<GroupList>('/api/v1/groups')
|
||||
/* 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. */
|
||||
const GROUPS_PAGE_SIZE = 100
|
||||
|
||||
export const getGroups = () => {
|
||||
const params = new URLSearchParams({ pageSize: String(GROUPS_PAGE_SIZE) })
|
||||
const timeZone = browserTimezone()
|
||||
if (timeZone) {
|
||||
params.set('timeZone', timeZone)
|
||||
}
|
||||
return apiFetch<GroupList>(`/api/v1/groups?${params.toString()}`)
|
||||
}
|
||||
|
||||
function timeZoneParam(): string {
|
||||
try {
|
||||
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
const timeZone = browserTimezone()
|
||||
return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : ''
|
||||
}
|
||||
|
||||
export const getHomeSummary = () =>
|
||||
|
||||
Reference in New Issue
Block a user