Compare commits
7 Commits
0f02331dfc
...
e9b44caf54
| Author | SHA1 | Date | |
|---|---|---|---|
| e9b44caf54 | |||
|
|
581cf2f2b2 | ||
|
|
81ed5747f3 | ||
|
|
8ccff20473 | ||
|
|
9520763ec3 | ||
|
|
5ef393fa64 | ||
|
|
45a1f50231 |
954
.interface-design/group-detail-redesign.html
Normal file
954
.interface-design/group-detail-redesign.html
Normal file
@@ -0,0 +1,954 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Gruperly — Rediseño detalle de grupo (2 estados)</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/lucide@0.469.0/dist/umd/lucide.min.js"></script>
|
||||
<style type="text/tailwindcss">
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-surface: var(--surface);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-soft: var(--primary-soft);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-strong: var(--accent-strong);
|
||||
--color-accent-soft: var(--accent-soft);
|
||||
--color-accent-fg: var(--accent-fg);
|
||||
--color-border: var(--border);
|
||||
--color-on-accent: var(--on-accent);
|
||||
--color-success: var(--success);
|
||||
--color-success-soft: var(--success-soft);
|
||||
--color-warning: var(--warning);
|
||||
--color-warning-soft: var(--warning-soft);
|
||||
--color-danger: var(--danger);
|
||||
--color-danger-soft: var(--danger-soft);
|
||||
--radius-xl: 0.75rem;
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
--animate-fade-in: fade-in 0.2s ease-out;
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--background: #020617;
|
||||
--surface: #0f172a;
|
||||
--primary: #f1f5f9;
|
||||
--primary-soft: #1e293b;
|
||||
--foreground: #94a3b8;
|
||||
--accent: #2544ea;
|
||||
--accent-strong: #1d33d8;
|
||||
--accent-soft: color-mix(in srgb, #3b63f5 15%, transparent);
|
||||
--accent-fg: #93b4fd;
|
||||
--border: #1e293b;
|
||||
--on-accent: #ffffff;
|
||||
--success: #34d399;
|
||||
--success-soft: color-mix(in srgb, #34d399 15%, transparent);
|
||||
--warning: #fcd34d;
|
||||
--warning-soft: color-mix(in srgb, #fcd34d 15%, transparent);
|
||||
--danger: #fb7185;
|
||||
--danger-soft: color-mix(in srgb, #fb7185 15%, transparent);
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: var(--background);
|
||||
}
|
||||
</style>
|
||||
<style>
|
||||
.frames {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 32px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.frame {
|
||||
width: 390px;
|
||||
}
|
||||
.screen {
|
||||
background: var(--background);
|
||||
border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
|
||||
border-radius: 24px;
|
||||
padding: 16px 12px 24px;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Botón (equivalente a components/ui/button.tsx, clases ya fusionadas) */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
border-radius: 0.75rem;
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
padding: 0 16px;
|
||||
height: 44px;
|
||||
cursor: pointer;
|
||||
border: 0;
|
||||
font-family: inherit;
|
||||
}
|
||||
.btn-outline {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
color: var(--primary);
|
||||
}
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--primary);
|
||||
}
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 44px;
|
||||
border-radius: 9999px;
|
||||
border: 1px solid var(--border);
|
||||
padding: 0 14px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
background: var(--surface);
|
||||
color: color-mix(in srgb, var(--foreground) 80%, transparent);
|
||||
cursor: pointer;
|
||||
}
|
||||
.chip-active {
|
||||
border-color: transparent;
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.05);
|
||||
}
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
padding: 2px 6px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.pill-warn {
|
||||
background: var(--warning-soft);
|
||||
color: var(--warning);
|
||||
}
|
||||
.pill-neutral {
|
||||
background: var(--primary-soft);
|
||||
color: color-mix(in srgb, var(--foreground) 60%, transparent);
|
||||
}
|
||||
.pill-on-accent {
|
||||
background: color-mix(in srgb, var(--on-accent) 25%, transparent);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
.label-cell {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.02em;
|
||||
color: color-mix(in srgb, var(--foreground) 70%, transparent);
|
||||
}
|
||||
.avatar {
|
||||
display: flex;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
}
|
||||
.row {
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
|
||||
cursor: pointer;
|
||||
}
|
||||
.row:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
text-align: left;
|
||||
font-size: 14px;
|
||||
}
|
||||
th {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: color-mix(in srgb, var(--foreground) 80%, transparent);
|
||||
padding: 0 12px 8px;
|
||||
}
|
||||
td {
|
||||
padding: 10px 12px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.truncate {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tabular {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
svg.lucide {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.icon-20 svg.lucide,
|
||||
svg.icon-20 {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
.icon-40 svg.lucide,
|
||||
svg.icon-40 {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="antialiased">
|
||||
<div class="mx-auto max-w-[1780px] px-6 py-8">
|
||||
<header class="mb-8 max-w-3xl">
|
||||
<p class="text-xs font-semibold uppercase tracking-wide text-accent-fg">
|
||||
Gruperly · /groups/$groupId
|
||||
</p>
|
||||
<h1 class="mt-1 text-2xl font-bold text-primary">Rediseño del detalle de grupo</h1>
|
||||
<p class="mt-2 text-sm leading-relaxed text-foreground/80">
|
||||
Dos pestañas (<strong class="text-primary">Miembros</strong> ·
|
||||
<strong class="text-primary">Pendientes</strong>), tarjeta de info con lectura
|
||||
Horario → Cupo → Cobro, un solo foco primario por estado y objetivos táctiles de 44px.
|
||||
Tema oscuro, tokens reales de <code class="text-accent-fg">apps/web/src/index.css</code>.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="frames">
|
||||
<!-- ═══════════════ ESTADO 1 · MIEMBROS ═══════════════ -->
|
||||
<div class="frame">
|
||||
<p class="mb-2 text-sm font-semibold text-primary">
|
||||
1 · Con miembros + pre-inscripciones — pestaña “Miembros”
|
||||
</p>
|
||||
<div class="screen">
|
||||
<section class="space-y-5">
|
||||
<!-- Header -->
|
||||
<div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||
Tai chi para principiantes. Trae ropa cómoda.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Acciones: dos outline + "Agregar" ghost (no compite) -->
|
||||
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||
</button>
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
|
||||
</button>
|
||||
<button class="btn btn-ghost btn-block col-span-2">
|
||||
<i data-lucide="user-plus" class="text-accent"></i
|
||||
><span>Agregar Miembros</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tarjeta de info: Horario → Cupo → Cobro -->
|
||||
<div
|
||||
class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4"
|
||||
>
|
||||
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Horario</p>
|
||||
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3">
|
||||
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Miembros & Cupo</p>
|
||||
<p
|
||||
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||
>
|
||||
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||
</p>
|
||||
<div
|
||||
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||
>
|
||||
<div class="h-full w-3/4 rounded-full bg-accent"></div>
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||
<div
|
||||
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||
>
|
||||
$
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Cobro</p>
|
||||
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Listados -->
|
||||
<div class="rounded-2xl bg-primary-soft p-2">
|
||||
<div class="space-y-2 p-2">
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="flex w-full flex-wrap items-center gap-2">
|
||||
<button class="chip chip-active">
|
||||
<i data-lucide="users"></i><span>Miembros</span
|
||||
><span class="pill pill-on-accent">3</span>
|
||||
</button>
|
||||
<button class="chip">
|
||||
<i data-lucide="inbox"></i><span>Pendientes</span
|
||||
><span class="pill pill-warn">3</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative w-full">
|
||||
<i
|
||||
data-lucide="search"
|
||||
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||
></i>
|
||||
<input
|
||||
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-foreground/80">
|
||||
Listado de todos los miembros incorporados al grupo.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||
<table>
|
||||
<thead>
|
||||
<tr class="border-b border-border/70">
|
||||
<th scope="col" class="w-[48%]">Nombre</th>
|
||||
<th scope="col">Teléfono</th>
|
||||
<th scope="col" class="w-9 px-1"><span class="sr-only">Detalle</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">A</div>
|
||||
<span class="min-w-0 truncate font-medium text-primary">Ana López</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 1234 5678</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">C</div>
|
||||
<span class="min-w-0 truncate font-medium text-primary"
|
||||
>Carlos Mendoza</span
|
||||
>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 2345 6789</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">L</div>
|
||||
<span class="min-w-0 truncate font-medium text-primary"
|
||||
>Lucía Hernández</span
|
||||
>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 3456 7890</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||
Un solo tono activo: el chip “Miembros”. “Agregar Miembros” es
|
||||
<code class="text-foreground/80">ghost</code> — disponible, no dominante. Cupo
|
||||
escaneable como <strong class="text-primary">3/4</strong> + barra.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════ ESTADO 1 · PENDIENTES ═══════════════ -->
|
||||
<div class="frame">
|
||||
<p class="mb-2 text-sm font-semibold text-primary">
|
||||
1 · Con miembros + pre-inscripciones — pestaña “Pendientes”
|
||||
</p>
|
||||
<div class="screen">
|
||||
<section class="space-y-5">
|
||||
<div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||
Tai chi para principiantes. Trae ropa cómoda.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||
</button>
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="share-2" class="text-accent"></i><span>Compartir Link</span>
|
||||
</button>
|
||||
<button class="btn btn-ghost btn-block col-span-2">
|
||||
<i data-lucide="user-plus" class="text-accent"></i
|
||||
><span>Agregar Miembros</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Horario</p>
|
||||
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3">
|
||||
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Miembros & Cupo</p>
|
||||
<p
|
||||
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||
>
|
||||
<span>3</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||
</p>
|
||||
<div
|
||||
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||
>
|
||||
<div class="h-full w-3/4 rounded-full bg-accent"></div>
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm text-foreground">1 lugar libre · 1 en espera</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||
<div
|
||||
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||
>
|
||||
$
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Cobro</p>
|
||||
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl bg-primary-soft p-2">
|
||||
<div class="space-y-2 p-2">
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="flex w-full flex-wrap items-center gap-2">
|
||||
<button class="chip">
|
||||
<i data-lucide="users"></i><span>Miembros</span
|
||||
><span class="pill pill-neutral">3</span>
|
||||
</button>
|
||||
<button class="chip chip-active">
|
||||
<i data-lucide="inbox"></i><span>Pendientes</span
|
||||
><span class="pill pill-on-accent">3</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative w-full">
|
||||
<i
|
||||
data-lucide="search"
|
||||
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||
></i>
|
||||
<input
|
||||
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-foreground/80">
|
||||
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
|
||||
un cupo libre.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||
<!-- Pre-inscripciones -->
|
||||
<section>
|
||||
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
|
||||
<i data-lucide="user-check" class="shrink-0 text-accent"></i>
|
||||
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
|
||||
Pre-inscripciones
|
||||
</h3>
|
||||
<span class="pill pill-warn ml-auto">2</span>
|
||||
</div>
|
||||
<div class="pt-1">
|
||||
<table>
|
||||
<thead>
|
||||
<tr class="border-b border-border/70">
|
||||
<th scope="col" class="w-[46%]">Nombre</th>
|
||||
<th scope="col">Teléfono</th>
|
||||
<th scope="col" class="hidden w-9 px-1 sm:table-cell"
|
||||
><span class="sr-only">Detalle</span></th
|
||||
>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">J</div>
|
||||
<div class="min-w-0">
|
||||
<p class="truncate font-medium text-primary">Jorge Ramírez</p>
|
||||
<p class="truncate text-xs text-foreground/70">
|
||||
jorge.r@correo.mx
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 4567 8901</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">S</div>
|
||||
<div class="min-w-0">
|
||||
<p class="truncate font-medium text-primary">Sofía Torres</p>
|
||||
<p class="truncate text-xs text-foreground/70">
|
||||
sofia.t@correo.mx
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 5678 9012</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Lista de espera -->
|
||||
<section>
|
||||
<div class="flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3">
|
||||
<i data-lucide="clock" class="shrink-0 text-accent"></i>
|
||||
<h3 class="text-xs font-semibold uppercase tracking-wide text-foreground/70">
|
||||
Lista de espera
|
||||
</h3>
|
||||
<span class="pill pill-neutral ml-auto">1</span>
|
||||
</div>
|
||||
<div class="pt-1">
|
||||
<table>
|
||||
<thead>
|
||||
<tr class="border-b border-border/70">
|
||||
<th scope="col" class="w-[48%]">Nombre</th>
|
||||
<th scope="col">Teléfono</th>
|
||||
<th scope="col" class="w-9 px-1"
|
||||
><span class="sr-only">Detalle</span></th
|
||||
>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="row">
|
||||
<td>
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<div class="avatar">D</div>
|
||||
<div class="min-w-0">
|
||||
<p class="truncate font-medium text-primary">Diego Peña</p>
|
||||
<p class="truncate text-xs text-foreground/70">
|
||||
Prefiere horario de 19:00
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="min-w-0 text-foreground/80">
|
||||
<span class="block truncate tabular">55 6789 0123</span>
|
||||
</td>
|
||||
<td class="w-9 px-1 text-foreground/50">
|
||||
<i data-lucide="chevron-right" class="ml-auto block"></i>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||
“Pendientes” agrupa Pre-inscripciones (pill ámbar = requiere decisión) y Lista de
|
||||
espera como secciones apiladas — sin una tercera pestaña.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════ ESTADO 2 · VACÍO (MIEMBROS) ═══════════════ -->
|
||||
<div class="frame">
|
||||
<p class="mb-2 text-sm font-semibold text-primary">
|
||||
2 · Estado vacío — pestaña “Miembros” (sin miembros ni pre-inscripciones)
|
||||
</p>
|
||||
<div class="screen">
|
||||
<section class="space-y-5">
|
||||
<div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||
Tai chi para principiantes. Trae ropa cómoda.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
|
||||
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tarjeta vacía: 0/4 -->
|
||||
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Horario</p>
|
||||
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3">
|
||||
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Miembros & Cupo</p>
|
||||
<p
|
||||
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||
>
|
||||
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||
</p>
|
||||
<div
|
||||
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||
>
|
||||
<div class="h-full w-0 rounded-full bg-accent"></div>
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||
<div
|
||||
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||
>
|
||||
$
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Cobro</p>
|
||||
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl bg-primary-soft p-2">
|
||||
<div class="space-y-2 p-2">
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="flex w-full flex-wrap items-center gap-2">
|
||||
<button class="chip chip-active">
|
||||
<i data-lucide="users"></i><span>Miembros</span>
|
||||
</button>
|
||||
<button class="chip">
|
||||
<i data-lucide="inbox"></i><span>Pendientes</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative w-full">
|
||||
<i
|
||||
data-lucide="search"
|
||||
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||
></i>
|
||||
<input
|
||||
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-foreground/80">
|
||||
Listado de todos los miembros incorporados al grupo.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<i
|
||||
data-lucide="users"
|
||||
class="icon-40 mx-auto mb-2 block text-foreground/40"
|
||||
></i>
|
||||
<p class="text-sm font-semibold text-primary">
|
||||
Todavía no hay miembros en este grupo
|
||||
</p>
|
||||
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Puedes compartir el enlace de invitación único o agregar miembros de forma
|
||||
manual o masiva.
|
||||
</p>
|
||||
<div class="mt-4 flex flex-col gap-2.5">
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
|
||||
</button>
|
||||
<button class="btn btn-primary btn-block">
|
||||
<i data-lucide="plus"></i><span>Agregar Miembros</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||
Exactamente <strong class="text-primary">un primario</strong>: “Agregar Miembros” en el
|
||||
empty state. El header no repite Compartir/Agregar —solo queda Estadísticas—, así que
|
||||
no compiten dos CTA idénticos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════ ESTADO 2 · VACÍO (PENDIENTES) ═══════════════ -->
|
||||
<div class="frame">
|
||||
<p class="mb-2 text-sm font-semibold text-primary">
|
||||
2 · Estado vacío — pestaña “Pendientes”
|
||||
</p>
|
||||
<div class="screen">
|
||||
<section class="space-y-5">
|
||||
<div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-bold leading-tight text-primary">Tai Chi Martes</h1>
|
||||
<p class="mt-1.5 text-sm leading-relaxed text-foreground/80">
|
||||
Tai chi para principiantes. Trae ropa cómoda.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-success-soft px-2.5 py-0.5 text-[11px] font-medium text-success"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-success"></span>Activo
|
||||
</span>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full bg-warning-soft px-2.5 py-0.5 text-[11px] font-medium text-warning"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-warning"></span>Riesgo moderado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Grupo vacío: el header no repite Compartir/Agregar; los lleva el empty state. -->
|
||||
<div class="mt-4 grid grid-cols-2 gap-2.5">
|
||||
<button class="btn btn-outline btn-block">
|
||||
<i data-lucide="bar-chart-3" class="text-accent"></i><span>Estadísticas</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divide-y divide-border/70 rounded-2xl bg-primary-soft p-4">
|
||||
<div class="flex items-start gap-3 py-3 first:pt-0">
|
||||
<i data-lucide="calendar-clock" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Horario</p>
|
||||
<p class="mt-1 text-base font-semibold leading-snug text-primary">Martes</p>
|
||||
<p class="mt-0.5 text-sm tabular text-foreground">18:00 - 19:30</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3">
|
||||
<i data-lucide="users" class="icon-20 mt-0.5 shrink-0 text-accent"></i>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Miembros & Cupo</p>
|
||||
<p
|
||||
class="mt-1 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular text-primary"
|
||||
>
|
||||
<span>0</span><span class="text-base font-medium text-foreground/70">/4</span>
|
||||
</p>
|
||||
<div
|
||||
class="mt-2 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||
>
|
||||
<div class="h-full w-0 rounded-full bg-accent"></div>
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm text-foreground">4 lugares libres</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-3 py-3 last:pb-0">
|
||||
<div
|
||||
class="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"
|
||||
>
|
||||
$
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="label-cell">Cobro</p>
|
||||
<p class="mt-1 text-base font-semibold tabular text-primary">$450.00</p>
|
||||
<p class="mt-0.5 text-sm text-foreground">Vence el día 10 de cada mes</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl bg-primary-soft p-2">
|
||||
<div class="space-y-2 p-2">
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="flex w-full flex-wrap items-center gap-2">
|
||||
<button class="chip">
|
||||
<i data-lucide="users"></i><span>Miembros</span>
|
||||
</button>
|
||||
<button class="chip chip-active">
|
||||
<i data-lucide="inbox"></i><span>Pendientes</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative w-full">
|
||||
<i
|
||||
data-lucide="search"
|
||||
class="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/70"
|
||||
></i>
|
||||
<input
|
||||
class="h-11 w-full rounded-lg border border-transparent bg-surface pl-9 pr-3 text-base text-primary shadow-xs placeholder:text-foreground/80 focus:outline-none"
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-foreground/80">
|
||||
Pre-inscripciones que esperan tu aprobación y personas en lista de espera por
|
||||
un cupo libre.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-surface p-1 shadow-xs">
|
||||
<div class="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<i
|
||||
data-lucide="inbox"
|
||||
class="icon-40 mx-auto mb-2 block text-foreground/40"
|
||||
></i>
|
||||
<p class="text-sm font-semibold text-primary">No hay pendientes</p>
|
||||
<p class="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Las pre-inscripciones que lleguen por el enlace compartido y las personas en
|
||||
lista de espera aparecerán aquí para que las revises.
|
||||
</p>
|
||||
<div class="mt-4 flex justify-center">
|
||||
<button class="btn btn-primary btn-block">
|
||||
<i data-lucide="share-2"></i><span>Compartir Enlace</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<p class="mt-3 text-xs leading-relaxed text-foreground/70">
|
||||
Cada pestaña vacía explica qué aparecerá ahí y ofrece
|
||||
<strong class="text-primary">una</strong> acción primaria concreta.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="mt-10 max-w-3xl border-t border-border pt-6 text-xs leading-relaxed text-foreground/70">
|
||||
<p>
|
||||
<strong class="text-primary">Jerarquía de la tarjeta:</strong> label 11px · dato 16px ·
|
||||
cupo 24px (único hero). Orden de lectura: Horario → Cupo → Cobro.
|
||||
<strong class="text-primary">Objetivos táctiles:</strong> chips, botones y buscador a
|
||||
44px; filas de tabla ~56px. <strong class="text-primary">Badges</strong> “Activo” y
|
||||
“Riesgo moderado” conservados.
|
||||
</p>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.addEventListener('load', () => {
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
.interface-design/group-detail-redesign.png
Normal file
BIN
.interface-design/group-detail-redesign.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 314 KiB |
136
.interface-design/system.md
Normal file
136
.interface-design/system.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# Gruperly — sistema de interfaz (apps/web)
|
||||
|
||||
Aplicado en el rediseño de `/groups/$groupId` (sept 2026). Fuente de verdad de tokens:
|
||||
`apps/web/src/index.css` (`@theme`). Ojo: `stack.md` trae tokens viejos (accent `#1e90ff`);
|
||||
el accent real es **`#2544ea`**.
|
||||
|
||||
## Dirección y sensación
|
||||
|
||||
Herramienta diaria de un profesor/organizador que abre la pantalla para responder tres
|
||||
preguntas: ¿quién está? ¿quién falta? ¿qué cobro?. Sensación: **calma operativa** — densa
|
||||
pero escaneable, nada grita salvo lo que requiere decisión. Tema oscuro slate + un solo
|
||||
accent azul; copy en español, verbos en infinitivo.
|
||||
|
||||
## Profundidad y espaciado
|
||||
|
||||
- **Estrategia de depth**: cambios de superficie + bordes de baja opacidad. Sombras solo
|
||||
`shadow-xs` en tarjetas/paneles. Nada de drop shadows marcados.
|
||||
- **Unidad base 4px.** Densidad: padding de componente 8–16px, separación entre bloques
|
||||
`space-y-5 sm:space-y-6` (20/24px).
|
||||
- **Radius**: default `rounded-xl` (0.75rem). Concéntrico: contenedor `rounded-2xl` (16px) +
|
||||
padding 8px → interior `rounded-lg` (8px). Chips y pills: `rounded-full`.
|
||||
|
||||
## Jerarquía tipográfica (ratio ~1.25)
|
||||
|
||||
| nivel | valor | uso |
|
||||
| --- | --- | --- |
|
||||
| label | 11px semibold uppercase `tracking-wide` `text-foreground/70` | títulos de celda/sección |
|
||||
| body | 14px (`text-sm`) `text-foreground/80` | descripciones, filas |
|
||||
| value | 16px semibold `text-primary` (`text-base`) | dato principal de una celda |
|
||||
| hero | 24px semibold `tracking-tight` `tabular-nums` | **solo uno por bloque** (hoy: el cupo `1/4`) |
|
||||
| micro | 10–12px | pills de conteo (`text-[10px] font-bold`), captions |
|
||||
|
||||
- Cuatro niveles de color de texto: `text-primary` → `text-foreground` → `/70` → `/50`.
|
||||
- **Todo dato numérico lleva `tabular-nums`** (contadores, teléfonos, precios, fechas).
|
||||
|
||||
## Patrón focal
|
||||
|
||||
**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header
|
||||
de grupo no tiene ningún `primary` (Estadísticas y Compartir son `outline` y **Agregar es
|
||||
`ghost`**: con miembros en el grupo deja de competir con el listado) y el `primary` vive en
|
||||
el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo.
|
||||
|
||||
**Objetivos táctiles ≥ 44px** en esta pantalla: chips (`min-h-11`), botones del header y del
|
||||
empty state (`h-11`), buscador (`h-11`). Filas de tabla ~56px.
|
||||
|
||||
Preview visual de los dos estados (con miembros + vacío):
|
||||
`group-detail-redesign.html` / `.png` (mismo directorio).
|
||||
|
||||
## Componentes (valores exactos)
|
||||
|
||||
### Chip de sección — `detail/SectionChips.tsx`
|
||||
- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist).
|
||||
- Chip: `min-h-11 rounded-full border px-3.5 text-xs font-semibold gap-1.5`,
|
||||
activo `border-transparent bg-accent text-on-accent shadow-xs`,
|
||||
inactivo `border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary`,
|
||||
focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`.
|
||||
- Pill de conteo: `px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums`;
|
||||
**oculto si el conteo es 0**; atención `bg-warning-soft text-warning`;
|
||||
neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`.
|
||||
- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta.
|
||||
|
||||
### Encabezado de pantalla — `components/layout/LargeTitle.tsx`
|
||||
- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de
|
||||
navegación que se opaca y recibe el título en versión chica.
|
||||
- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md`
|
||||
y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con
|
||||
`BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`.
|
||||
- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`,
|
||||
con `text-balance` para nombres largos.
|
||||
- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es
|
||||
duplicado visual del `h1`).
|
||||
- El progreso sale de la posición del título en cada frame (`rAF` agrupa los
|
||||
eventos de scroll), no de una transición: por eso se siente pegado al dedo. El
|
||||
estado vive dentro de `LargeTitle` para que `children` no se re-renderice en
|
||||
cada frame.
|
||||
- La barra se monta en una caja que el layout pone arriba de `<main>`
|
||||
(`ImmersiveBarHost`): un `sticky` está limitado a la caja de su padre, y el
|
||||
padre natural (el bloque del feature) es corto.
|
||||
- Sólo en tres rutas: `isImmersiveRoute` (`lib/immersive-routes.ts`): ficha de
|
||||
grupo, sus estadísticas y la asistencia. Ahí no se renderiza el header global
|
||||
y el sidebar pasa a `top-0 h-dvh`.
|
||||
- El link "volver" vive en la barra como `leading` y sigue `hidden lg:inline-flex`.
|
||||
- En las pantallas de un grupo (ficha y estadísticas) el título grande es **el
|
||||
nombre del grupo**, no el de la sección: la barra colapsada tiene que decir
|
||||
sobre qué se está mirando. "Estadísticas" va como subtítulo (label 11px
|
||||
uppercase + body), no como título.
|
||||
|
||||
### Acciones de cabecera — `detail/GroupHeader.tsx`
|
||||
- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan
|
||||
debajo, en el flujo normal.
|
||||
- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros:
|
||||
`variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px).
|
||||
- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** —
|
||||
Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado.
|
||||
- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`.
|
||||
- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`,
|
||||
en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra.
|
||||
|
||||
### Tarjeta de info — `detail/GroupInfoCard.tsx`
|
||||
- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil,
|
||||
`md:grid md:grid-cols-3 md:divide-x md:divide-y-0`.
|
||||
- Celda: `flex items-start gap-3 py-3 first:pt-0 last:pb-0 md:py-0` + `md:pr-6` / `md:px-6` / `md:pl-6`.
|
||||
- Barra de cupo: `h-1.5 max-w-[9rem] rounded-full bg-accent/15`, fill `bg-accent`
|
||||
(o `bg-warning` si `total >= capacity`), `transition-[width] duration-300 ease-out`,
|
||||
con `role="progressbar"` + `aria-valuetext`.
|
||||
|
||||
### Sección de listados — `detail/MembersWaitlistSection.tsx`
|
||||
- Externo `rounded-2xl bg-primary-soft p-2`; interno `space-y-2 p-2 sm:p-3`.
|
||||
- Panel de contenido: `rounded-lg bg-surface p-1 shadow-xs sm:p-2`.
|
||||
- Fila header: chips + buscador (`sm:w-72 lg:shrink-0`), apilados hasta `lg`.
|
||||
- Sub-encabezado de sección apilada (`PendingView.tsx`):
|
||||
`flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3`,
|
||||
título label 11px, pill a la derecha con `ml-auto`; tabla envuelta en `pt-1`.
|
||||
|
||||
### Empty state
|
||||
`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` ·
|
||||
título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` ·
|
||||
acciones: **una** `primary` + el resto `outline`, todas `h-11`.
|
||||
|
||||
### Tablas — `detail/*Table.tsx`
|
||||
`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5`
|
||||
con `border-b border-border/70 last:border-b-0 hover:bg-primary-soft/60` ·
|
||||
avatar `size-9 rounded-full bg-accent/10 text-xs font-semibold text-accent` ·
|
||||
columnas secundarias con `hidden sm:table-cell` (en móvil manda el teléfono).
|
||||
|
||||
### Botón — `components/ui/button.tsx`
|
||||
`rounded-xl font-medium h-10 px-4 text-sm` · `active:scale-[0.96] motion-reduce:active:scale-100` ·
|
||||
focus `ring-2 ring-accent` · variantes `primary` (`bg-accent`/`hover:bg-accent-strong`),
|
||||
`outline`, `ghost`.
|
||||
|
||||
## Convenciones que sostienen el sistema
|
||||
|
||||
- Sin Radix/shadcn instalado: primitivos propios en `components/ui/` + `cn()` (clsx + tailwind-merge).
|
||||
- Sin botón "volver" en mobile: `hidden lg:inline-flex`.
|
||||
- Elementos fijos abajo: `env(safe-area-inset-bottom)` en el padding.
|
||||
- Los controles nuevos deben pasar el squint test: si dos cosas brillan, sobra una.
|
||||
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||
- `src/logger.ts` — pino + pino-pretty.
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`).
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza.
|
||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||
@@ -54,6 +54,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
|
||||
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
|
||||
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
|
||||
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
|
||||
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
|
||||
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
|
||||
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "group_pre_registrations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"fullName" TEXT NOT NULL,
|
||||
"phone" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -20,6 +20,7 @@ model Group {
|
||||
attendees Attendee[]
|
||||
payments Payment[]
|
||||
waitlist GroupWaitlistEntry[]
|
||||
preRegistrations GroupPreRegistration[]
|
||||
classSessions ClassSession[]
|
||||
|
||||
@@map("groups")
|
||||
@@ -157,6 +158,30 @@ enum WaitlistStatus {
|
||||
DECLINED
|
||||
}
|
||||
|
||||
enum PreRegistrationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([groupId, phone])
|
||||
@@index([groupId])
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { ApproveGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/approve', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new ApproveGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ApproveGroupPreRegistrationResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
toGroupWaitlistEntryDto,
|
||||
} from '../../../group-waitlist/lib/helpers';
|
||||
import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote';
|
||||
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
export class ApproveGroupPreRegistration {
|
||||
constructor(private readonly deps: ApproveGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<ApproveGroupPreRegistrationResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const record = entry as unknown as GroupPreRegistrationRecord;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx): Promise<Result<ApproveGroupPreRegistrationResult, ProblemDetails>> => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
tx,
|
||||
groupResult.value,
|
||||
{
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
},
|
||||
);
|
||||
|
||||
if (promoteResult.ok) {
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
return ok({
|
||||
outcome: 'added',
|
||||
attendee: promoteResult.value,
|
||||
waitlistEntry: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (promoteResult.error.code !== 'group_capacity_reached') {
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
const existingWaitlistEntry = await tx.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: record.groupId, phone: record.phone },
|
||||
});
|
||||
const waitlistEntryRecord = existingWaitlistEntry
|
||||
? (existingWaitlistEntry as unknown as GroupWaitlistEntryRecord)
|
||||
: ((await tx.groupWaitlistEntry.create({
|
||||
data: {
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
},
|
||||
})) as unknown as GroupWaitlistEntryRecord);
|
||||
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'waitlisted',
|
||||
attendee: null,
|
||||
waitlistEntry: toGroupWaitlistEntryDto(waitlistEntryRecord),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
type GroupPreRegistrationQuery,
|
||||
GroupPreRegistrationQuerySchema,
|
||||
} from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListGroupPreRegistrations } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/preregistrations', validate.query(GroupPreRegistrationQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const query = c.req.valid('query') as GroupPreRegistrationQuery;
|
||||
const useCase = new ListGroupPreRegistrations();
|
||||
const result = await useCase.execute(groupId, user.id, query);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
GroupPreRegistrationList,
|
||||
GroupPreRegistrationQuery,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '../../../group-waitlist/lib/helpers';
|
||||
import {
|
||||
type GroupPreRegistrationRecord,
|
||||
toGroupPreRegistrationDto,
|
||||
} from '../../lib/helpers';
|
||||
|
||||
type ListGroupPreRegistrationsDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class ListGroupPreRegistrations {
|
||||
constructor(private readonly deps: ListGroupPreRegistrationsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
userId: string,
|
||||
query: GroupPreRegistrationQuery,
|
||||
): Promise<Result<GroupPreRegistrationList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupForUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const where = { groupId, status: query.status ?? ('PENDING' as const) };
|
||||
const [records, total] = await Promise.all([
|
||||
db.groupPreRegistration.findMany({
|
||||
where,
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.groupPreRegistration.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map(
|
||||
(record) => toGroupPreRegistrationDto(record as unknown as GroupPreRegistrationRecord),
|
||||
),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { RejectGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/reject', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new RejectGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ProblemDetails,
|
||||
RejectGroupPreRegistrationResult,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '../../../group-waitlist/lib/helpers';
|
||||
import { type GroupPreRegistrationRecord, toGroupPreRegistrationDto } from '../../lib/helpers';
|
||||
|
||||
type RejectGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class RejectGroupPreRegistration {
|
||||
constructor(private readonly deps: RejectGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<RejectGroupPreRegistrationResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await db.groupPreRegistration.update({
|
||||
where: { id: entry.id },
|
||||
data: { status: 'REJECTED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
entry: toGroupPreRegistrationDto(updated as unknown as GroupPreRegistrationRecord),
|
||||
});
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as groupPreRegistrationRoutes } from './routes';
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { GroupPreRegistrationDto } from '@gruperly/shared';
|
||||
|
||||
export type GroupPreRegistrationRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
status: GroupPreRegistrationDto['status'];
|
||||
reviewedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export function toGroupPreRegistrationDto(
|
||||
record: GroupPreRegistrationRecord,
|
||||
): GroupPreRegistrationDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
status: record.status,
|
||||
reviewedAt: record.reviewedAt ? record.reviewedAt.toISOString() : null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import approveRoute from './features/approve/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import rejectRoute from './features/reject/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', approveRoute);
|
||||
routes.route('/', rejectRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -6,6 +6,7 @@ import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createGroupRoute from './features/create/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
@@ -24,6 +25,7 @@ routes.route('/', bulkCreateAttendeesRoute);
|
||||
routes.route('/', getByIdRoute);
|
||||
routes.route('/', addToGroupWaitlistRoute);
|
||||
routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', groupPreRegistrationRoutes);
|
||||
routes.route('/', analyticsRoutes);
|
||||
routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export type JoinViaInviteResult = {
|
||||
status: 'registered' | 'waitlisted';
|
||||
status: 'pre_registered';
|
||||
message: string;
|
||||
attendee: AttendeeDto | null;
|
||||
attendee: null;
|
||||
};
|
||||
|
||||
export class JoinViaInvite {
|
||||
@@ -53,50 +53,63 @@ export class JoinViaInvite {
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
const email = payload.email?.trim() || null;
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
where: { groupId: group.id, status: 'ACTIVE' },
|
||||
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existingPreRegistration?.status === 'REJECTED') {
|
||||
await db.groupPreRegistration.update({
|
||||
where: { id: existingPreRegistration.id },
|
||||
data: { status: 'PENDING', fullName, email, reviewedAt: null },
|
||||
});
|
||||
|
||||
if (currentCount >= group.capacity) {
|
||||
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: group.id, phone },
|
||||
});
|
||||
|
||||
if (!existingWaitlistEntry) {
|
||||
await db.groupWaitlistEntry.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return ok({
|
||||
status: 'waitlisted',
|
||||
message:
|
||||
'El grupo está completo. Fuiste agregado a la lista de espera. Te contactaremos cuando haya un lugar disponible.',
|
||||
attendee: null,
|
||||
});
|
||||
}
|
||||
return ok({
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
|
||||
const created = await db.attendee.create({
|
||||
if (existingPreRegistration) {
|
||||
const message =
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'Tu inscripción para este grupo ya fue aprobada.'
|
||||
: 'Ya enviaste una solicitud de inscripción para este grupo. Está pendiente de revisión por el profesor.';
|
||||
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: message,
|
||||
code:
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'pre_registration_already_approved'
|
||||
: 'pre_registration_already_pending',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await db.groupPreRegistration.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
status: 'registered',
|
||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
||||
message: 'Inscripción realizada con éxito',
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,10 @@ const db = {
|
||||
create: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
groupPreRegistration: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -83,18 +84,18 @@ describe('public invitations routes', () => {
|
||||
});
|
||||
|
||||
describe('POST /invitations/:token/join', () => {
|
||||
it('registers a new attendee successfully', async () => {
|
||||
it('creates a pending pre-registration instead of an attendee', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue({
|
||||
id: 'att-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.create.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
email: 'lucia@test.com',
|
||||
phone: '+5491122334455',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
} as never);
|
||||
@@ -112,9 +113,11 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.message).toBe('Inscripción realizada con éxito');
|
||||
expect(body.attendee.fullName).toBe('Lucía Méndez');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.message).toContain('solicitud de inscripción');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
@@ -141,7 +144,7 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid inputs (missing required name/phone)', async () => {
|
||||
@@ -157,21 +160,67 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('adds to the waitlist when the group is full', async () => {
|
||||
it('returns 409 when a pre-registration is already pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.count.mockResolvedValue(15); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue({
|
||||
id: 'wl-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'PENDING',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_pending');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already approved', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'APPROVED',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_approved');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivates a rejected pre-registration back to pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
status: 'REJECTED',
|
||||
reviewedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
@@ -187,15 +236,15 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.status).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
status: 'PENDING',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
reviewedAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
365
apps/backend/test/preregistrations.test.ts
Normal file
365
apps/backend/test/preregistrations.test.ts
Normal file
@@ -0,0 +1,365 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupPreRegistration: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {
|
||||
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const teacherId = 'teacher-1';
|
||||
const mockGroup = {
|
||||
id: 'group-1',
|
||||
name: 'Taller de Pintura',
|
||||
description: null,
|
||||
createdById: teacherId,
|
||||
inviteToken: 'valid-token-123',
|
||||
createdAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
days: ['MONDAY'],
|
||||
time: '18:00',
|
||||
capacity: 20,
|
||||
price: 1500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 10,
|
||||
members: [],
|
||||
};
|
||||
|
||||
const preRegistration = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
createdAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
notifyToken: 'notify-1',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'wl-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('group pre-registrations', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/preregistrations', () => {
|
||||
it('lists pending pre-registrations in FIFO order with pagination', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([
|
||||
preRegistration({ id: 'pre-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }),
|
||||
preRegistration({ id: 'pre-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }),
|
||||
] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(2);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/preregistrations');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.data).toHaveLength(2);
|
||||
expect(data.data[0].fullName).toBe('Ana García');
|
||||
expect(data.data[0].status).toBe('PENDING');
|
||||
expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 });
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'PENDING' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by status when provided', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations?status=REJECTED',
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'REJECTED' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects user without access to the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/preregistrations');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/approve', () => {
|
||||
it('adds the person to the group when there is free capacity', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue(attendee() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('added');
|
||||
expect(body.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(body.waitlistEntry).toBeNull();
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('moves the person to the waitlist when the group is full', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.waitlistEntry.fullName).toBe('Martín Gómez');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses an existing waitlist entry instead of duplicating it', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the phone already belongs to a member', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the pre-registration does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/missing/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects approval from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/reject', () => {
|
||||
it('marks the pre-registration as rejected', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.entry.status).toBe('REJECTED');
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'REJECTED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects rejection from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,8 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"icons": "bun run scripts/generate-icons.ts",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "^1.7.2",
|
||||
|
||||
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
82
apps/web/src/components/layout/LargeTitle.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
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: 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. */
|
||||
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. */
|
||||
barTrailing?: ReactNode
|
||||
/** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) {
|
||||
const { titleRef, progress } = useLargeTitleCollapse()
|
||||
const barHost = useImmersiveBarHost()
|
||||
|
||||
return (
|
||||
<>
|
||||
{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. */}
|
||||
<div
|
||||
className="absolute inset-0 border-b border-border bg-background/80 backdrop-blur-md"
|
||||
style={{ opacity: progress }}
|
||||
/>
|
||||
{leading}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="relative min-w-0 flex-1 truncate text-base font-semibold text-primary"
|
||||
style={{ opacity: progress, transform: `translateY(${(1 - progress) * 12}px)` }}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
{barTrailing ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="relative flex shrink-0 items-center"
|
||||
style={{ opacity: progress }}
|
||||
>
|
||||
{barTrailing}
|
||||
</span>
|
||||
) : null}
|
||||
</div>,
|
||||
barHost,
|
||||
)
|
||||
: null}
|
||||
|
||||
<h1
|
||||
ref={titleRef}
|
||||
className="text-balance text-[2.125rem] font-bold leading-[1.1] tracking-tight text-primary sm:text-[2.5rem]"
|
||||
>
|
||||
{title}
|
||||
</h1>
|
||||
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +1,39 @@
|
||||
import { useLocation } from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider'
|
||||
import { isImmersiveRoute } from '../../lib/immersive-routes'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { Header } from './Header'
|
||||
import { Sidebar } from './Sidebar'
|
||||
import { BottomNav } from './BottomNav'
|
||||
|
||||
export function RootLayout({ children }: { children: ReactNode }) {
|
||||
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh w-full">
|
||||
<Header />
|
||||
{/* 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. */}
|
||||
{immersive ? null : <Header />}
|
||||
|
||||
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||
<Sidebar />
|
||||
<Sidebar immersive={immersive} />
|
||||
|
||||
{/* pb-24 deja lugar para la BottomNav; en iOS standalone hay que sumar
|
||||
el inset del home indicator o el contenido queda debajo. */}
|
||||
<main className="min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] pt-4 lg:px-0 lg:pb-8 lg:pt-8">
|
||||
{children}
|
||||
</main>
|
||||
<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. */}
|
||||
<main
|
||||
className={cn(
|
||||
'min-w-0 flex-1 px-4 pb-[calc(6rem+env(safe-area-inset-bottom))] lg:px-0 lg:pb-8',
|
||||
immersive ? 'pt-0' : 'pt-4 lg:pt-8',
|
||||
)}
|
||||
>
|
||||
{immersive ? <ImmersiveBarHost /> : null}
|
||||
{children}
|
||||
</main>
|
||||
</ImmersiveBarProvider>
|
||||
</div>
|
||||
|
||||
<BottomNav />
|
||||
|
||||
@@ -3,11 +3,19 @@ import { cn } from '../../lib/utils'
|
||||
import { Logo } from '../brand'
|
||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||
|
||||
export function Sidebar() {
|
||||
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<aside className="sticky top-16 hidden h-[calc(100dvh-4rem)] w-64 shrink-0 flex-col border-r border-border bg-surface px-4 py-6 lg:flex">
|
||||
// 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.
|
||||
<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 to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export { RootLayout } from './RootLayout'
|
||||
export { Header } from './Header'
|
||||
export { LargeTitle } from './LargeTitle'
|
||||
export { ThemeToggle } from './ThemeToggle'
|
||||
export { PublicHeader } from './PublicHeader'
|
||||
export { PublicFooter } from './PublicFooter'
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
export { Avatar, type AvatarProps } from './avatar'
|
||||
export { Button, type ButtonProps, type ButtonVariant, type ButtonSize } from './button'
|
||||
export { Badge, type BadgeProps, type BadgeVariant } from './badge'
|
||||
export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button'
|
||||
export { Input, type InputProps } from './input'
|
||||
export { Label, type LabelProps } from './label'
|
||||
export { Modal, type ModalProps } from './modal'
|
||||
export { ToastProvider, useToast, type ToastType, type Toast } from './toast'
|
||||
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
|
||||
export { Tooltip, type TooltipProps } from './tooltip'
|
||||
|
||||
|
||||
67
apps/web/src/components/ui/tooltip.tsx
Normal file
67
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
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. */
|
||||
content: ReactNode
|
||||
/** Contenido del disparador. Queda dentro de un <button> para ser accesible. */
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** Posicionamiento alternativo del globo (por defecto: abajo, anclado a la derecha en 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.
|
||||
*/
|
||||
export function Tooltip({ content, children, className, tooltipClassName }: TooltipProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const id = useId()
|
||||
|
||||
const show = () => setOpen(true)
|
||||
const hide = () => setOpen(false)
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex">
|
||||
<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.
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType === 'mouse') show()
|
||||
}}
|
||||
onPointerLeave={(e) => {
|
||||
if (e.pointerType === 'mouse') hide()
|
||||
}}
|
||||
onFocus={show}
|
||||
onBlur={hide}
|
||||
onClick={show}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') hide()
|
||||
}}
|
||||
className={cn(
|
||||
'inline-flex cursor-help rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<span
|
||||
id={id}
|
||||
role="tooltip"
|
||||
className={cn(
|
||||
'absolute top-full left-0 z-50 mt-1.5 w-max max-w-[min(16rem,calc(100vw_-_2rem))] rounded-lg border border-border bg-surface px-2.5 py-2 text-xs leading-snug text-foreground shadow-sm animate-fade-in sm:left-auto sm:right-0',
|
||||
tooltipClassName,
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
42
apps/web/src/context/ImmersiveBarProvider.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
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.
|
||||
|
||||
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. */
|
||||
|
||||
type ImmersiveBarValue = {
|
||||
host: HTMLElement | null
|
||||
hostRef: (element: HTMLElement | null) => void
|
||||
}
|
||||
|
||||
const ImmersiveBarContext = createContext<ImmersiveBarValue>({
|
||||
host: null,
|
||||
hostRef: () => undefined,
|
||||
})
|
||||
|
||||
export function ImmersiveBarProvider({ children }: { children: ReactNode }) {
|
||||
const [host, setHost] = useState<HTMLElement | null>(null)
|
||||
const hostRef = useCallback((element: HTMLElement | null) => setHost(element), [])
|
||||
|
||||
return (
|
||||
<ImmersiveBarContext.Provider value={{ host, hostRef }}>{children}</ImmersiveBarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** Caja de la barra: primer hijo de `<main>`, en las rutas immersive. */
|
||||
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. */
|
||||
export function useImmersiveBarHost() {
|
||||
return useContext(ImmersiveBarContext).host
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { useAttendance } from './AttendanceProvider'
|
||||
import { StudentRow } from './StudentRow'
|
||||
@@ -16,15 +17,43 @@ export function ClassAttendanceView() {
|
||||
isSaving,
|
||||
} = useAttendance()
|
||||
|
||||
const total = sessionInfo?.students.length ?? 0
|
||||
|
||||
return (
|
||||
<section>
|
||||
<Link
|
||||
to="/"
|
||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||
{/* 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. */}
|
||||
<LargeTitle
|
||||
title={sessionInfo?.groupName ?? 'Asistencia'}
|
||||
leading={
|
||||
<Link
|
||||
to="/"
|
||||
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span>Volver al inicio</span>
|
||||
</Link>
|
||||
}
|
||||
barTrailing={
|
||||
total > 0 ? (
|
||||
<Badge variant="success" className="text-[11px] tabular-nums">
|
||||
{presentCount}/{total}
|
||||
</Badge>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span>Volver al inicio</span>
|
||||
</Link>
|
||||
{sessionInfo ? (
|
||||
<div className="mt-2 flex items-center justify-between gap-3">
|
||||
<p className="text-sm text-foreground/60">
|
||||
{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}
|
||||
</p>
|
||||
<Badge variant="success" className="shrink-0 text-xs tabular-nums">
|
||||
{presentCount}/{total} presentes
|
||||
</Badge>
|
||||
</div>
|
||||
) : null}
|
||||
</LargeTitle>
|
||||
|
||||
{studentsPending ? (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
@@ -43,19 +72,7 @@ export function ClassAttendanceView() {
|
||||
|
||||
{sessionInfo ? (
|
||||
<>
|
||||
<header className="sticky top-16 z-30 -mx-4 border-b border-border bg-background/95 px-4 py-3 backdrop-blur lg:mx-0 lg:rounded-xl lg:border lg:px-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="truncate text-lg font-bold text-primary">{sessionInfo.groupName}</h1>
|
||||
<p className="text-xs text-foreground/60">{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}</p>
|
||||
</div>
|
||||
<Badge variant="success" className="shrink-0 text-sm">
|
||||
{presentCount}/{sessionInfo.students.length} presentes
|
||||
</Badge>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{sessionInfo.students.length === 0 ? (
|
||||
{total === 0 ? (
|
||||
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
@@ -70,7 +87,7 @@ export function ClassAttendanceView() {
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{sessionInfo.students.length > 0 ? (
|
||||
{total > 0 ? (
|
||||
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
||||
<Button
|
||||
variant="primary"
|
||||
@@ -87,4 +104,4 @@ export function ClassAttendanceView() {
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { CalendarClock, Users } from 'lucide-react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { Badge, Button, Tooltip } from '../../components/ui'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { RISK_LABELS } from './constants'
|
||||
import { RISK_HINT, RISK_LABELS } from './constants'
|
||||
|
||||
export function GroupCard({
|
||||
group,
|
||||
@@ -28,16 +28,20 @@ export function GroupCard({
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
{hasRisk ? (
|
||||
<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>
|
||||
// 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>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Link, useParams } from '@tanstack/react-router'
|
||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
||||
import type { GroupDto, StudentAtRiskDto } from '@gruperly/shared'
|
||||
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
||||
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||
import { Badge, Button, useToast } from '../../../components/ui'
|
||||
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
||||
import { KpiCard } from './KpiCard'
|
||||
@@ -77,124 +78,144 @@ export function AnalyticsView() {
|
||||
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
const groupName = riskQuery.data?.groupName
|
||||
|
||||
if (analyticsQuery.isPending || riskQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) {
|
||||
return (
|
||||
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
||||
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-4"
|
||||
onClick={() => {
|
||||
void analyticsQuery.refetch()
|
||||
void riskQuery.refetch()
|
||||
}}
|
||||
>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 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.
|
||||
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
||||
const groupName = riskQuery.data?.groupName ?? cachedGroupName
|
||||
const analytics = analyticsQuery.data
|
||||
const atRisk = riskQuery.data?.data ?? []
|
||||
|
||||
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.
|
||||
const showContent = !isPending && !hasFailed && Boolean(analytics)
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||
{/* 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. */}
|
||||
<LargeTitle
|
||||
title={groupName ?? 'Grupo'}
|
||||
leading={
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
Volver al grupo
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
Volver a {groupName ?? 'el grupo'}
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-primary">Estadísticas</h1>
|
||||
<p className="mt-2 text-sm text-foreground/60">
|
||||
Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}.
|
||||
</p>
|
||||
</div>
|
||||
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
||||
Últimos 30 días
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<KpiCard
|
||||
icon={<Percent className="size-5" />}
|
||||
label="Asistencia promedio"
|
||||
value={`${analytics.attendanceRate}%`}
|
||||
hint="últimos 30 días"
|
||||
/>
|
||||
<KpiCard
|
||||
icon={<CalendarCheck className="size-5" />}
|
||||
label="Asistencias del mes"
|
||||
value={analytics.totalPresent.toLocaleString('es-MX')}
|
||||
hint={`${analytics.totalClasses} clases dictadas`}
|
||||
/>
|
||||
<KpiCard
|
||||
icon={<DoorOpen className="size-5" />}
|
||||
label="Cupos recuperados"
|
||||
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
||||
hint="por ausencias avisadas"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-accent" />
|
||||
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
||||
{atRisk.length > 0 ? (
|
||||
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
||||
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
||||
</p>
|
||||
|
||||
{atRisk.length === 0 ? (
|
||||
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
||||
{/* "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. */}
|
||||
<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">
|
||||
Estadísticas
|
||||
</p>
|
||||
<p className="mt-0.5 text-pretty text-sm text-foreground/80">
|
||||
Asistencia y gestión de riesgo
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-4 space-y-3">
|
||||
{atRisk.map((student) => (
|
||||
<AtRiskStudentCard
|
||||
key={student.attendeeId}
|
||||
student={student}
|
||||
menuOpen={menuOpenFor === student.attendeeId}
|
||||
onToggleMenu={() =>
|
||||
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
||||
}
|
||||
onViewHistory={() => setHistoryStudent(student)}
|
||||
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
||||
onRequestStatusAction={(action) => {
|
||||
setStatusAction(action)
|
||||
setMenuOpenFor(null)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
||||
Últimos 30 días
|
||||
</span>
|
||||
</div>
|
||||
</LargeTitle>
|
||||
|
||||
{isPending ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{hasFailed ? (
|
||||
<div className="mt-6 rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
||||
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-4"
|
||||
onClick={() => {
|
||||
void analyticsQuery.refetch()
|
||||
void riskQuery.refetch()
|
||||
}}
|
||||
>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showContent && analytics ? (
|
||||
<>
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<KpiCard
|
||||
icon={<Percent className="size-5" />}
|
||||
label="Asistencia promedio"
|
||||
value={`${analytics.attendanceRate}%`}
|
||||
hint="últimos 30 días"
|
||||
/>
|
||||
<KpiCard
|
||||
icon={<CalendarCheck className="size-5" />}
|
||||
label="Asistencias del mes"
|
||||
value={analytics.totalPresent.toLocaleString('es-MX')}
|
||||
hint={`${analytics.totalClasses} clases dictadas`}
|
||||
/>
|
||||
<KpiCard
|
||||
icon={<DoorOpen className="size-5" />}
|
||||
label="Cupos recuperados"
|
||||
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
||||
hint="por ausencias avisadas"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="size-5 text-accent" />
|
||||
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
||||
{atRisk.length > 0 ? (
|
||||
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
||||
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
||||
</p>
|
||||
|
||||
{atRisk.length === 0 ? (
|
||||
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
||||
<p className="mt-1 text-sm text-foreground/60">
|
||||
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-4 space-y-3">
|
||||
{atRisk.map((student) => (
|
||||
<AtRiskStudentCard
|
||||
key={student.attendeeId}
|
||||
student={student}
|
||||
menuOpen={menuOpenFor === student.attendeeId}
|
||||
onToggleMenu={() =>
|
||||
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
||||
}
|
||||
onViewHistory={() => setHistoryStudent(student)}
|
||||
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
||||
onRequestStatusAction={(action) => {
|
||||
setStatusAction(action)
|
||||
setMenuOpenFor(null)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<AttendeeHistoryModal
|
||||
student={historyStudent}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
||||
import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react'
|
||||
import { Avatar, Badge, Button } from '../../../components/ui'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
|
||||
export type StatusAction = { student: StudentAtRiskDto; status: 'PAUSED' | 'DROPPED' } | null
|
||||
|
||||
@@ -32,8 +32,10 @@ export function AtRiskStudentCard({
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
||||
<p className="mt-0.5 text-xs text-foreground/50">
|
||||
{student.phone ?? 'Sin teléfono'} · {student.monthlyAttendanceRate}% de asistencia
|
||||
mensual
|
||||
{student.phone
|
||||
? `${formatPhoneDisplay(student.phone)} · `
|
||||
: 'Sin teléfono · '}
|
||||
{student.monthlyAttendanceRate}% de asistencia mensual
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@@ -3,4 +3,9 @@ import type { GroupRiskLevel } from '@gruperly/shared'
|
||||
export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
|
||||
HIGH: 'Riesgo alto',
|
||||
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. */
|
||||
export const RISK_HINT =
|
||||
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
UserMinus,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '../../../components/ui'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
|
||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||
import { DetailRow } from './DetailRow'
|
||||
@@ -97,7 +98,7 @@ export function AttendeeDetailPage() {
|
||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||
{attendee.phone ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-primary">{attendee.phone}</span>
|
||||
<span className="text-primary">{formatPhoneDisplay(attendee.phone)}</span>
|
||||
<a
|
||||
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
|
||||
target="_blank"
|
||||
@@ -136,7 +137,7 @@ export function AttendeeDetailPage() {
|
||||
{attendee.guardianPhone ? (
|
||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-primary">{attendee.guardianPhone}</span>
|
||||
<span className="text-primary">{formatPhoneDisplay(attendee.guardianPhone)}</span>
|
||||
<a
|
||||
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
|
||||
target="_blank"
|
||||
|
||||
@@ -4,23 +4,27 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type {
|
||||
AttendeeDto,
|
||||
GroupDto,
|
||||
GroupPreRegistrationDto,
|
||||
GroupWaitlistEntryDto,
|
||||
GroupRiskLevel,
|
||||
} from '@gruperly/shared'
|
||||
import { useToast } from '../../../components/ui'
|
||||
import {
|
||||
ApiError,
|
||||
approveGroupPreRegistration,
|
||||
getGroup,
|
||||
getGroupAttendees,
|
||||
getGroupPreRegistrations,
|
||||
getGroupsRiskOverview,
|
||||
getGroupWaitlist,
|
||||
getInviteToken,
|
||||
promoteGroupWaitlistEntry,
|
||||
rejectGroupPreRegistration,
|
||||
removeGroupWaitlistEntry,
|
||||
} from '../../../lib/api'
|
||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||
|
||||
export type ListSection = 'members' | 'waitlist'
|
||||
export type ListSection = 'members' | 'pending'
|
||||
|
||||
type GroupDetailContextValue = {
|
||||
groupId: string
|
||||
@@ -34,6 +38,9 @@ type GroupDetailContextValue = {
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
preRegistrations: GroupPreRegistrationDto[]
|
||||
preRegistrationsTotal: number
|
||||
preRegistrationsPending: boolean
|
||||
hasFreeCapacity: boolean
|
||||
inviteUrl: string | undefined
|
||||
invitePending: boolean
|
||||
@@ -51,12 +58,18 @@ type GroupDetailContextValue = {
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
||||
selectedPreRegistration: GroupPreRegistrationDto | null
|
||||
setSelectedPreRegistration: (entry: GroupPreRegistrationDto | null) => void
|
||||
isSubmittingRemoval: boolean
|
||||
isSubmittingPromotion: boolean
|
||||
isSubmittingWaitlistRemoval: boolean
|
||||
isSubmittingApproval: boolean
|
||||
isSubmittingRejection: boolean
|
||||
isRegeneratingInvite: boolean
|
||||
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
||||
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
||||
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||
regenerateInvite: () => void
|
||||
copyInviteLink: () => Promise<void>
|
||||
copyWhatsappMessage: () => Promise<void>
|
||||
@@ -70,11 +83,19 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
const toast = useToast()
|
||||
|
||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||
const [listSection, setListSection] = useState<ListSection>('members')
|
||||
const [listSection, setListSectionState] = useState<ListSection>('members')
|
||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||
const [searchFilter, setSearchFilter] = useState('')
|
||||
|
||||
// La búsqueda pertenece a la vista que la abrió: al cambiar de pestaña se
|
||||
// limpia para no heredar un filtro sin coincidencias.
|
||||
const setListSection = (value: ListSection) => {
|
||||
setListSectionState(value)
|
||||
setSearchFilter('')
|
||||
}
|
||||
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ['group', groupId],
|
||||
queryFn: () => getGroup(groupId),
|
||||
@@ -105,17 +126,30 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const preRegistrationsQuery = useQuery({
|
||||
queryKey: ['group-preregistrations', groupId],
|
||||
queryFn: () => getGroupPreRegistrations(groupId, 1, 100),
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const group = groupQuery.data
|
||||
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
||||
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
||||
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||
const preRegistrations = useMemo(
|
||||
() => preRegistrationsQuery.data?.data ?? [],
|
||||
[preRegistrationsQuery.data],
|
||||
)
|
||||
const preRegistrationsTotal =
|
||||
preRegistrationsQuery.data?.pagination?.total ?? preRegistrations.length
|
||||
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
||||
|
||||
const invalidateGroupQueries = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-preregistrations', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||
}
|
||||
|
||||
@@ -161,10 +195,56 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
},
|
||||
})
|
||||
|
||||
const approvePreRegistrationMutation = useMutation({
|
||||
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||
approveGroupPreRegistration(groupId, entry.id),
|
||||
onSuccess: (result, entry) => {
|
||||
setSelectedPreRegistration(null)
|
||||
toast.success(
|
||||
result.outcome === 'added'
|
||||
? `${entry.fullName} ahora es miembro del grupo.`
|
||||
: `${entry.fullName} fue agregado a la lista de espera: el grupo está completo.`,
|
||||
)
|
||||
invalidateGroupQueries()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
if (err instanceof ApiError) {
|
||||
if (err.problem?.code === 'attendee_already_registered') {
|
||||
toast.error('Ya hay un miembro con ese teléfono en el grupo. Puedes rechazar la pre-inscripción.')
|
||||
return
|
||||
}
|
||||
if (err.problem?.code === 'pre_registration_already_reviewed') {
|
||||
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||
invalidateGroupQueries()
|
||||
return
|
||||
}
|
||||
}
|
||||
toast.error(err.message || 'No se pudo aprobar la pre-inscripción.')
|
||||
},
|
||||
})
|
||||
|
||||
const rejectPreRegistrationMutation = useMutation({
|
||||
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||
rejectGroupPreRegistration(groupId, entry.id),
|
||||
onSuccess: (_result, entry) => {
|
||||
setSelectedPreRegistration(null)
|
||||
toast.success(`La pre-inscripción de ${entry.fullName} fue rechazada.`)
|
||||
invalidateGroupQueries()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
if (err instanceof ApiError && err.problem?.code === 'pre_registration_already_reviewed') {
|
||||
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||
invalidateGroupQueries()
|
||||
return
|
||||
}
|
||||
toast.error(err.message || 'No se pudo rechazar la pre-inscripción.')
|
||||
},
|
||||
})
|
||||
|
||||
const inviteUrl = inviteTokenQuery.data?.inviteUrl
|
||||
const whatsappMessage =
|
||||
group && inviteUrl
|
||||
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tus datos de inscripción en el siguiente enlace:\n${inviteUrl}`
|
||||
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:\n${inviteUrl}`
|
||||
: ''
|
||||
const whatsappShareUrl = whatsappMessage
|
||||
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
||||
@@ -215,6 +295,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
firstWaitlistEntry,
|
||||
preRegistrations,
|
||||
preRegistrationsTotal,
|
||||
preRegistrationsPending: preRegistrationsQuery.isPending,
|
||||
hasFreeCapacity,
|
||||
inviteUrl,
|
||||
invitePending: inviteTokenQuery.isPending,
|
||||
@@ -235,9 +318,13 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
},
|
||||
selectedWaitlistEntry,
|
||||
setSelectedWaitlistEntry,
|
||||
selectedPreRegistration,
|
||||
setSelectedPreRegistration,
|
||||
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
||||
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
||||
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
||||
isSubmittingApproval: approvePreRegistrationMutation.isPending,
|
||||
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
|
||||
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
||||
promoteEntry: (entry) => {
|
||||
setSelectedWaitlistEntry(null)
|
||||
@@ -247,6 +334,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
setSelectedWaitlistEntry(null)
|
||||
removeWaitlistEntryMutation.mutate(entry)
|
||||
},
|
||||
approvePreRegistration: (entry) => {
|
||||
approvePreRegistrationMutation.mutate(entry)
|
||||
},
|
||||
rejectPreRegistration: (entry) => {
|
||||
rejectPreRegistrationMutation.mutate(entry)
|
||||
},
|
||||
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
||||
copyInviteLink,
|
||||
copyWhatsappMessage,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { GroupHeader } from './GroupHeader'
|
||||
import { GroupInfoCard } from './GroupInfoCard'
|
||||
import { InviteLinkModal } from './InviteLinkModal'
|
||||
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
||||
import { PreRegistrationDetailModal } from './PreRegistrationDetailModal'
|
||||
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
||||
@@ -60,6 +61,7 @@ export function GroupDetailView() {
|
||||
onConfirm={confirmRemoveAttendee}
|
||||
/>
|
||||
<WaitlistEntryDetailModal />
|
||||
<PreRegistrationDetailModal />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,88 +1,123 @@
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
||||
import { Badge, Button } from '../../../components/ui'
|
||||
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { RISK_LABELS } from '../constants'
|
||||
import { RISK_HINT, RISK_LABELS } from '../constants'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function GroupHeader() {
|
||||
const { group, groupId, riskLevel, openInviteModal } = useGroupDetail()
|
||||
const {
|
||||
group,
|
||||
groupId,
|
||||
riskLevel,
|
||||
openInviteModal,
|
||||
attendeesTotal,
|
||||
attendeesPending,
|
||||
preRegistrationsTotal,
|
||||
preRegistrationsPending,
|
||||
waitlistTotal,
|
||||
waitlistPending,
|
||||
} = useGroupDetail()
|
||||
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.
|
||||
const listLoading = attendeesPending || preRegistrationsPending || waitlistPending
|
||||
const isEmptyGroup =
|
||||
!listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Link
|
||||
to="/groups"
|
||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||
<LargeTitle
|
||||
title={group?.name ?? ''}
|
||||
leading={
|
||||
<Link
|
||||
to="/groups"
|
||||
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span>Volver a grupos</span>
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<span>Volver a grupos</span>
|
||||
</Link>
|
||||
|
||||
{/* El título se queda con el ancho completo: los estados bajan a su propia
|
||||
fila compacta en vez de competir con el nombre por el espacio. */}
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0 sm:max-w-2xl">
|
||||
<h1 className="text-balance text-2xl font-bold leading-tight text-primary sm:text-[1.75rem]">
|
||||
{group?.name}
|
||||
</h1>
|
||||
{group?.description ? (
|
||||
<p className="mt-1.5 text-sm leading-relaxed text-foreground/80">{group.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 sm:shrink-0 sm:justify-end">
|
||||
{/* 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. */}
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<Badge variant="success" className="gap-1.5 text-[11px]">
|
||||
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
|
||||
Activo
|
||||
</Badge>
|
||||
{hasRisk ? (
|
||||
<Badge
|
||||
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
|
||||
className="gap-1.5 text-[11px]"
|
||||
>
|
||||
<span
|
||||
className={cn('size-1.5 rounded-full', riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{RISK_LABELS[riskLevel]}
|
||||
</Badge>
|
||||
// El badge no puede llevar texto largo sin ensuciar el header: la
|
||||
// explicación (riesgo de abandono, no de cobranza) vive en el tooltip.
|
||||
<Tooltip content={RISK_HINT}>
|
||||
<Badge
|
||||
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
|
||||
className="gap-1.5 text-[11px]"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'size-1.5 rounded-full',
|
||||
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{RISK_LABELS[riskLevel]}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{group?.description ? (
|
||||
<p className="mt-2 text-pretty text-sm leading-relaxed text-foreground/80">
|
||||
{group.description}
|
||||
</p>
|
||||
) : null}
|
||||
</LargeTitle>
|
||||
|
||||
<div className="mt-4 grid grid-cols-2 gap-2.5 sm:mt-5 sm:flex sm:flex-wrap sm:items-center sm:justify-end sm:gap-2.5">
|
||||
{/* `h-11` (44px) para todos: objetivo táctil mínimo. */}
|
||||
{!isEmptyGroup ? (
|
||||
// Un solo primario por pantalla: "Agregar" encabeza la jerarquía y
|
||||
// las acciones de apoyo quedan debajo en outline.
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
|
||||
}
|
||||
className="col-span-2 h-11 w-full justify-center sm:w-auto"
|
||||
>
|
||||
<UserPlus className="size-4" />
|
||||
<span>Agregar miembro</span>
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })}
|
||||
className="w-full justify-center border-border sm:w-auto"
|
||||
className={cn(
|
||||
'h-11 w-full justify-center border-border sm:w-auto',
|
||||
// En grupo vacío es la única acción del header: ocupa la fila entera.
|
||||
isEmptyGroup && 'col-span-2',
|
||||
)}
|
||||
>
|
||||
<BarChart3 className="size-4 text-accent" />
|
||||
<span>Estadísticas</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={openInviteModal}
|
||||
className="w-full justify-center border-border sm:w-auto"
|
||||
>
|
||||
<Share2 className="size-4 text-accent" />
|
||||
<span>
|
||||
Compartir <span className="hidden sm:inline">Link</span>
|
||||
</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
|
||||
}
|
||||
className="col-span-2 w-full justify-center sm:w-auto"
|
||||
>
|
||||
<UserPlus className="size-4" />
|
||||
<span>
|
||||
Agregar <span className="hidden sm:inline">Miembros</span>
|
||||
</span>
|
||||
</Button>
|
||||
{!isEmptyGroup ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={openInviteModal}
|
||||
className="h-11 w-full justify-center border-border sm:w-auto"
|
||||
>
|
||||
<Share2 className="size-4 text-accent" />
|
||||
<span>
|
||||
Compartir <span className="hidden sm:inline">Link</span>
|
||||
</span>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,51 +1,104 @@
|
||||
import { CalendarClock, Users } from 'lucide-react'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../../lib/format'
|
||||
import {
|
||||
formatBillingMeta,
|
||||
formatPrice,
|
||||
WEEK_DAY_FULL_LABELS,
|
||||
} from '../../../lib/format'
|
||||
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. */
|
||||
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'
|
||||
|
||||
export function GroupInfoCard() {
|
||||
const { group, attendees, waitlistTotal } = useGroupDetail()
|
||||
const { group, attendeesTotal, attendeesPending, waitlistTotal } = useGroupDetail()
|
||||
if (!group) return null
|
||||
|
||||
const daysLabel = (group.days ?? []).map((day) => WEEK_DAY_FULL_LABELS[day]).join(', ')
|
||||
const capacity = group.capacity
|
||||
const isFull = capacity != null && attendeesTotal >= capacity
|
||||
const freeSpots = capacity != null ? Math.max(capacity - attendeesTotal, 0) : null
|
||||
const occupancy = capacity ? Math.min(attendeesTotal / capacity, 1) : 0
|
||||
const billingMeta = formatBillingMeta(group.billingType, group.dueDay)
|
||||
|
||||
const capacityMeta = !capacity
|
||||
? 'Sin cupo definido'
|
||||
: isFull
|
||||
? 'Cupo completo'
|
||||
: `${freeSpots} ${freeSpots === 1 ? 'lugar libre' : 'lugares libres'}`
|
||||
const waitlistMeta = waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 rounded-2xl bg-primary-soft p-4 sm:p-5 md:grid-cols-3 md:gap-x-0 md:divide-x md:divide-border/70">
|
||||
<div className="flex items-start gap-3 md:pr-6">
|
||||
<div className="divide-y divide-border/70 rounded-2xl bg-primary-soft p-3.5 sm:p-4 md:grid md:grid-cols-3 md:divide-x md:divide-y-0">
|
||||
<div className={cn(CELL_CLASS, 'md:pr-6')}>
|
||||
<CalendarClock className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-wide text-foreground/80">
|
||||
Horario
|
||||
</p>
|
||||
<p className="mt-0.5 text-sm font-semibold text-primary">
|
||||
{(group.days?.length ?? 0) > 0
|
||||
? formatSchedule(group.days ?? [], group.time)
|
||||
: 'Sin horario definido'}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className={LABEL_CLASS}>Horario</p>
|
||||
<p className="mt-0.5 text-base font-semibold leading-snug text-primary">
|
||||
{daysLabel || 'Sin horario definido'}
|
||||
</p>
|
||||
{daysLabel && group.time ? (
|
||||
<p className="mt-0.5 text-sm tabular-nums text-foreground">{group.time}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 md:px-6">
|
||||
<div className={cn(CELL_CLASS, 'md:px-6')}>
|
||||
<Users className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-wide text-foreground/80">
|
||||
Miembros & Cupo
|
||||
</p>
|
||||
<p className="mt-0.5 text-sm font-semibold tabular-nums text-primary">
|
||||
{attendees.length} inscritos {waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''}
|
||||
{group.capacity ? ` · Cupo de ${group.capacity}` : ''}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className={LABEL_CLASS}>Miembros & Cupo</p>
|
||||
<p className="mt-0.5 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular-nums text-primary">
|
||||
<span>{attendeesPending ? '—' : attendeesTotal}</span>
|
||||
{capacity ? (
|
||||
<span className="text-base font-medium text-foreground/70">/{capacity}</span>
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
{capacity ? (
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label="Ocupación del cupo"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={capacity}
|
||||
aria-valuenow={attendeesPending ? 0 : attendeesTotal}
|
||||
aria-valuetext={`${attendeesTotal} de ${capacity}`}
|
||||
className="mt-1.5 h-1.5 w-full max-w-[9rem] overflow-hidden rounded-full bg-accent/15"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'h-full rounded-full transition-[width] duration-300 ease-out',
|
||||
isFull ? 'bg-warning' : 'bg-accent',
|
||||
)}
|
||||
style={{ width: `${Math.round(occupancy * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!attendeesPending ? (
|
||||
<p className={cn('mt-1 text-sm', isFull ? 'text-warning' : 'text-foreground')}>
|
||||
{capacityMeta}
|
||||
{waitlistMeta}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3 md:pl-6">
|
||||
<div className={cn(CELL_CLASS, 'md:pl-6')}>
|
||||
<div className="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent">
|
||||
$
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-wide text-foreground/80">Cobro</p>
|
||||
<p className="mt-0.5 text-sm font-semibold tabular-nums text-primary">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className={LABEL_CLASS}>Cobro</p>
|
||||
<p className="mt-0.5 text-base font-semibold tabular-nums text-primary">
|
||||
{group.price != null ? formatPrice(group.price) : 'Sin precio'}
|
||||
{group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}
|
||||
{group.dueDay ? ` · Vence día ${group.dueDay}` : ''}
|
||||
</p>
|
||||
{billingMeta && group.price != null ? (
|
||||
<p className="mt-0.5 text-sm text-foreground">{billingMeta}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -74,7 +74,7 @@ export function InviteLinkModal() {
|
||||
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
||||
<strong>{group?.name}</strong>.
|
||||
{'\n\n'}
|
||||
Completa tus datos de inscripción en el siguiente enlace:
|
||||
Completa tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:
|
||||
{'\n'}
|
||||
<span className="break-all text-accent underline">{inviteUrl}</span>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AttendeeDto } from '@gruperly/shared'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
||||
@@ -15,9 +16,9 @@ export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
||||
<table className="w-full table-fixed text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||
<th scope="col" className="w-[54%] px-3 pb-2">Nombre</th>
|
||||
<th scope="col" className="px-3 pb-2">Teléfono</th>
|
||||
<th scope="col" className="w-9 px-1 pb-2">
|
||||
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
|
||||
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
|
||||
<th scope="col" className="w-8 px-1 pb-1.5">
|
||||
<span className="sr-only">Detalle</span>
|
||||
</th>
|
||||
</tr>
|
||||
@@ -26,31 +27,43 @@ export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
||||
{attendees.map((attendee) => (
|
||||
<tr
|
||||
key={attendee.id}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60"
|
||||
tabIndex={0}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
|
||||
onClick={() => openAttendee(attendee.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
openAttendee(attendee.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
|
||||
<td className="px-2 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">
|
||||
{attendee.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
{/* `truncate` solo recorta lo pintado: el texto completo sigue en
|
||||
el DOM para lectores de pantalla, y `title` lo muestra al hover. */}
|
||||
<span className="min-w-0 truncate font-medium text-primary" title={attendee.fullName}>
|
||||
<span
|
||||
className="min-w-0 truncate font-semibold text-primary"
|
||||
title={attendee.fullName}
|
||||
>
|
||||
{attendee.fullName}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="min-w-0 px-3 py-2.5 text-foreground/80">
|
||||
{/* El nombre manda; el teléfono es un dato secundario: un nivel
|
||||
más abajo en la escala de color, en un tamaño menor. */}
|
||||
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70">
|
||||
{attendee.phone ? (
|
||||
<span className="block truncate tabular-nums" title={attendee.phone}>
|
||||
{attendee.phone}
|
||||
{formatPhoneDisplay(attendee.phone)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-foreground/60">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="w-9 px-1 py-2.5 text-foreground/50">
|
||||
<td className="w-8 px-1 py-2 text-foreground/50">
|
||||
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
69
apps/web/src/features/groups/detail/MembersView.tsx
Normal file
69
apps/web/src/features/groups/detail/MembersView.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2, Plus, Share2, Users } from 'lucide-react'
|
||||
import { Button } from '../../../components/ui'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { MembersTable } from './MembersTable'
|
||||
|
||||
export function MembersView() {
|
||||
const { groupId, attendees, attendeesPending, searchFilter, openInviteModal } = useGroupDetail()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const query = searchFilter.trim().toLowerCase()
|
||||
const filtered = query
|
||||
? attendees.filter(
|
||||
(a) =>
|
||||
a.fullName.toLowerCase().includes(query) ||
|
||||
(a.phone && a.phone.includes(query)) ||
|
||||
(a.email && a.email.toLowerCase().includes(query)),
|
||||
)
|
||||
: attendees
|
||||
|
||||
if (attendeesPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-6 animate-spin text-accent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (attendees.length === 0) {
|
||||
return (
|
||||
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<Users className="mx-auto mb-2 size-10 text-foreground/40" />
|
||||
<p className="text-sm font-semibold text-primary">
|
||||
Todavía no hay miembros en este grupo
|
||||
</p>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Puedes compartir el enlace de invitación único o agregar miembros de forma manual o
|
||||
masiva.
|
||||
</p>
|
||||
<div className="mt-4 flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-center sm:gap-3">
|
||||
<Button variant="outline" onClick={openInviteModal} className="h-11 w-full sm:w-auto">
|
||||
<Share2 className="size-4" />
|
||||
Compartir Enlace
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
|
||||
}
|
||||
className="h-11 w-full sm:w-auto"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Agregar Miembros
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return (
|
||||
<div className="py-8 text-center text-sm text-foreground/80">
|
||||
No se encontraron miembros que coincidan con la búsqueda.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <MembersTable attendees={filtered} />
|
||||
}
|
||||
@@ -1,26 +1,12 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Clock, Loader2, Plus, Search, Share2, Users } from 'lucide-react'
|
||||
import { Button, Input } from '../../../components/ui'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { Search } from 'lucide-react'
|
||||
import { Input } from '../../../components/ui'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { MembersTable } from './MembersTable'
|
||||
import { WaitlistTable } from './WaitlistTable'
|
||||
import { MembersView } from './MembersView'
|
||||
import { PendingView } from './PendingView'
|
||||
import { SectionChips } from './SectionChips'
|
||||
|
||||
export function MembersWaitlistSection() {
|
||||
const {
|
||||
groupId, attendees, attendeesTotal, attendeesPending,
|
||||
waitlistEntries, waitlistTotal, waitlistPending,
|
||||
listSection, setListSection, searchFilter, setSearchFilter, openInviteModal,
|
||||
} = useGroupDetail()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const query = searchFilter.toLowerCase()
|
||||
const filteredAttendees = attendees.filter(
|
||||
(a) =>
|
||||
a.fullName.toLowerCase().includes(query) ||
|
||||
(a.phone && a.phone.includes(query)) ||
|
||||
(a.email && a.email.toLowerCase().includes(query)),
|
||||
)
|
||||
const { listSection, searchFilter, setSearchFilter } = useGroupDetail()
|
||||
|
||||
return (
|
||||
// Radios concéntricos: `rounded-2xl` (16px) con `p-2` (8px) deja a las
|
||||
@@ -28,135 +14,32 @@ export function MembersWaitlistSection() {
|
||||
// Sin bordes: el lavado `bg-primary-soft` separa la sección del fondo.
|
||||
<div className="rounded-2xl bg-primary-soft p-2">
|
||||
<div className="space-y-2 p-2 sm:p-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="Listado del grupo"
|
||||
className="flex w-full items-center gap-1 rounded-lg bg-surface p-0.5 shadow-xs sm:w-[26rem]"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={listSection === 'members'}
|
||||
onClick={() => setListSection('members')}
|
||||
className={cn(
|
||||
'flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-semibold transition-[color,background-color,box-shadow] duration-150',
|
||||
listSection === 'members'
|
||||
? 'bg-accent text-on-accent shadow-xs'
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<Users className="size-4 shrink-0" />
|
||||
<span className="whitespace-nowrap">
|
||||
Miembros ({attendeesTotal})
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={listSection === 'waitlist'}
|
||||
onClick={() => setListSection('waitlist')}
|
||||
className={cn(
|
||||
'flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-semibold transition-[color,background-color,box-shadow] duration-150',
|
||||
listSection === 'waitlist'
|
||||
? 'bg-accent text-on-accent shadow-xs'
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<Clock className="size-4 shrink-0" />
|
||||
<span className="whitespace-nowrap">Lista de espera ({waitlistTotal})</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
|
||||
<SectionChips />
|
||||
|
||||
{listSection === 'members' ? (
|
||||
<div className="relative w-full sm:w-64">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
|
||||
<Input
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
value={searchFilter}
|
||||
onChange={(e) => setSearchFilter(e.target.value)}
|
||||
aria-label="Buscar miembros"
|
||||
className="h-10 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="relative w-full sm:w-72 lg:shrink-0">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
|
||||
<Input
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
value={searchFilter}
|
||||
onChange={(e) => setSearchFilter(e.target.value)}
|
||||
aria-label="Buscar en el listado"
|
||||
className="h-11 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs leading-relaxed text-foreground/80">
|
||||
{/* Copia de apoyo: un solo bloque, ancho acotado y sin competir con
|
||||
los datos. Explica la diferencia entre ambos estados. */}
|
||||
<p className="max-w-2xl text-xs leading-snug text-foreground/80">
|
||||
{listSection === 'members'
|
||||
? 'Listado de todos los miembros incorporados al grupo.'
|
||||
: 'Personas que esperan un cupo libre en el grupo. Al pasar a alguien al grupo, se crea automáticamente su registro como miembro.'}
|
||||
: 'Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo libre.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg bg-surface p-1 shadow-xs sm:p-2">
|
||||
{listSection === 'members' ? (
|
||||
<>
|
||||
{attendeesPending ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-6 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!attendeesPending && attendees.length === 0 ? (
|
||||
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<Users className="mx-auto mb-2 size-10 text-foreground/40" />
|
||||
<p className="text-sm font-semibold text-primary">
|
||||
Todavía no hay miembros en este grupo
|
||||
</p>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Puedes compartir el enlace de invitación único o agregar miembros de forma manual o
|
||||
masiva.
|
||||
</p>
|
||||
<div className="mt-4 flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-center sm:gap-3">
|
||||
<Button variant="outline" onClick={openInviteModal} className="w-full sm:w-auto">
|
||||
<Share2 className="size-4" />
|
||||
Compartir Enlace
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
|
||||
}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Agregar Miembros
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{attendees.length > 0 && filteredAttendees.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-foreground/80">
|
||||
No se encontraron miembros que coincidan con la búsqueda.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{filteredAttendees.length > 0 ? <MembersTable attendees={filteredAttendees} /> : null}
|
||||
</>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{waitlistPending ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-6 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!waitlistPending && waitlistEntries.length === 0 ? (
|
||||
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<Clock className="mx-auto mb-2 size-10 text-foreground/40" />
|
||||
<p className="text-sm font-semibold text-primary">No hay nadie en la lista de espera</p>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Cuando el grupo alcance su cupo, las personas podrán sumarse a la espera y podrás
|
||||
pasarlas al grupo desde aquí.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{waitlistEntries.length > 0 ? <WaitlistTable entries={waitlistEntries} /> : null}
|
||||
</div>
|
||||
)}
|
||||
{listSection === 'members' ? <MembersView /> : <PendingView />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
129
apps/web/src/features/groups/detail/PendingView.tsx
Normal file
129
apps/web/src/features/groups/detail/PendingView.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import { Clock, Inbox, Loader2, Share2, UserCheck } from 'lucide-react'
|
||||
import { Button } from '../../../components/ui'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { PreRegistrationsTable } from './PreRegistrationsTable'
|
||||
import { WaitlistTable } from './WaitlistTable'
|
||||
|
||||
export function PendingView() {
|
||||
const {
|
||||
preRegistrations,
|
||||
preRegistrationsPending,
|
||||
waitlistEntries,
|
||||
waitlistPending,
|
||||
searchFilter,
|
||||
openInviteModal,
|
||||
} = useGroupDetail()
|
||||
|
||||
const query = searchFilter.trim().toLowerCase()
|
||||
const matches = (fullName: string, phone: string | null | undefined, email?: string | null) =>
|
||||
!query ||
|
||||
fullName.toLowerCase().includes(query) ||
|
||||
(phone != null && phone.includes(query)) ||
|
||||
(email != null && email.toLowerCase().includes(query))
|
||||
|
||||
const filteredPrereg = preRegistrations.filter((p) => matches(p.fullName, p.phone, p.email))
|
||||
const filteredWaitlist = waitlistEntries.filter((w) => matches(w.fullName, w.phone))
|
||||
|
||||
if (preRegistrationsPending || waitlistPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-6 animate-spin text-accent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const hasAnyEntry = preRegistrations.length > 0 || waitlistEntries.length > 0
|
||||
|
||||
if (!hasAnyEntry && !query) {
|
||||
return (
|
||||
<div className="rounded-lg bg-primary-soft/50 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>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Las pre-inscripciones que lleguen por el enlace compartido y las personas en lista de
|
||||
espera aparecerán aquí para que las revises.
|
||||
</p>
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button variant="primary" onClick={openInviteModal} className="h-11 w-full sm:w-auto">
|
||||
<Share2 className="size-4" />
|
||||
Compartir Enlace
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (filteredPrereg.length === 0 && filteredWaitlist.length === 0) {
|
||||
return (
|
||||
<div className="py-8 text-center text-sm text-foreground/80">
|
||||
No se encontraron pendientes que coincidan con la búsqueda.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const sections = [
|
||||
{
|
||||
key: 'preregistrations',
|
||||
title: 'Pre-inscripciones',
|
||||
icon: UserCheck,
|
||||
attention: true,
|
||||
count: filteredPrereg.length,
|
||||
emptyNote: 'Sin pre-inscripciones pendientes.',
|
||||
table: <PreRegistrationsTable entries={filteredPrereg} />,
|
||||
},
|
||||
{
|
||||
key: 'waitlist',
|
||||
title: 'Lista de espera',
|
||||
icon: Clock,
|
||||
attention: false,
|
||||
count: filteredWaitlist.length,
|
||||
emptyNote: 'Sin nadie en la lista de espera.',
|
||||
table: <WaitlistTable entries={filteredWaitlist} />,
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
{sections.map((section) => {
|
||||
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.
|
||||
if (!hasRows && query) return null
|
||||
|
||||
return (
|
||||
<section key={section.key} aria-labelledby={titleId}>
|
||||
<div className="flex items-center gap-2 border-b border-border/70 px-3 pb-1.5 pt-2">
|
||||
<Icon className="size-4 shrink-0 text-accent" aria-hidden="true" />
|
||||
<h3
|
||||
id={titleId}
|
||||
className="text-xs font-semibold uppercase tracking-wide text-foreground/70"
|
||||
>
|
||||
{section.title}
|
||||
</h3>
|
||||
{hasRows ? (
|
||||
<span
|
||||
className={cn(
|
||||
'ml-auto inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums',
|
||||
section.attention
|
||||
? 'bg-warning-soft text-warning'
|
||||
: 'bg-primary-soft text-foreground/70',
|
||||
)}
|
||||
>
|
||||
{section.count}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{hasRows ? (
|
||||
<div className="pt-0.5">{section.table}</div>
|
||||
) : (
|
||||
<p className="px-3 py-2 text-xs text-foreground/70">{section.emptyNote}</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Ban, Loader2, Mail, MessageCircle, Phone, UserCheck } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { DetailRow } from './DetailRow'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function PreRegistrationDetailModal() {
|
||||
const {
|
||||
selectedPreRegistration,
|
||||
setSelectedPreRegistration,
|
||||
hasFreeCapacity,
|
||||
approvePreRegistration,
|
||||
rejectPreRegistration,
|
||||
isSubmittingApproval,
|
||||
isSubmittingRejection,
|
||||
} = useGroupDetail()
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={selectedPreRegistration !== null}
|
||||
onClose={() => setSelectedPreRegistration(null)}
|
||||
title="Detalle de la pre-inscripción"
|
||||
maxWidth="sm"
|
||||
>
|
||||
{selectedPreRegistration ? (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-accent/10 text-lg font-bold text-accent">
|
||||
{selectedPreRegistration.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-lg font-semibold text-primary">
|
||||
{selectedPreRegistration.fullName}
|
||||
</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
Solicitado el{' '}
|
||||
{new Date(selectedPreRegistration.createdAt).toLocaleDateString('es-ES', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
|
||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-primary">{formatPhoneDisplay(selectedPreRegistration.phone)}</span>
|
||||
<a
|
||||
href={`https://wa.me/${selectedPreRegistration.phone.replace(/\D/g, '')}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
||||
>
|
||||
<MessageCircle className="size-3.5" />
|
||||
<span>WhatsApp</span>
|
||||
</a>
|
||||
</div>
|
||||
</DetailRow>
|
||||
|
||||
{selectedPreRegistration.email ? (
|
||||
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
|
||||
<a
|
||||
href={`mailto:${selectedPreRegistration.email}`}
|
||||
className="text-primary transition-colors hover:text-accent"
|
||||
>
|
||||
{selectedPreRegistration.email}
|
||||
</a>
|
||||
</DetailRow>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{!hasFreeCapacity ? (
|
||||
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-xs text-foreground/70">
|
||||
El grupo alcanzó su cupo de miembros. Si aprobás, esta persona quedará en la lista de
|
||||
espera hasta que se libere un lugar.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-2.5 border-t border-border pt-2">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => approvePreRegistration(selectedPreRegistration)}
|
||||
disabled={isSubmittingApproval || isSubmittingRejection}
|
||||
className="gap-2"
|
||||
>
|
||||
{isSubmittingApproval ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<UserCheck className="size-4" />
|
||||
)}
|
||||
<span>Aprobar</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => rejectPreRegistration(selectedPreRegistration)}
|
||||
disabled={isSubmittingApproval || isSubmittingRejection}
|
||||
className="gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
|
||||
>
|
||||
{isSubmittingRejection ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Ban className="size-4" />
|
||||
)}
|
||||
Rechazar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { GroupPreRegistrationDto } from '@gruperly/shared'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrationDto[] }) {
|
||||
const { setSelectedPreRegistration } = useGroupDetail()
|
||||
|
||||
return (
|
||||
<table className="w-full table-fixed text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
|
||||
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
|
||||
{/* En móvil el teléfono manda: la fecha vive en el detalle. */}
|
||||
<th scope="col" className="hidden px-2 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>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr
|
||||
key={entry.id}
|
||||
tabIndex={0}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
|
||||
onClick={() => setSelectedPreRegistration(entry)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
setSelectedPreRegistration(entry)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td className="px-2 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">
|
||||
{entry.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold text-primary" title={entry.fullName}>
|
||||
{entry.fullName}
|
||||
</p>
|
||||
{entry.email ? (
|
||||
<p className="truncate text-xs text-foreground/70" title={entry.email}>
|
||||
{entry.email}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70">
|
||||
<span className="block truncate tabular-nums" title={entry.phone}>
|
||||
{formatPhoneDisplay(entry.phone)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden min-w-0 px-2 py-2 text-xs text-foreground/70 sm:table-cell">
|
||||
{new Date(entry.createdAt).toLocaleDateString('es-ES', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</td>
|
||||
<td className="w-8 px-1 py-2 text-foreground/50">
|
||||
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AttendeeDto, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||
import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
|
||||
type RemoveAttendeeModalProps = {
|
||||
attendee: AttendeeDto | null
|
||||
@@ -37,7 +38,9 @@ export function RemoveAttendeeModal({
|
||||
<strong className="text-primary">{groupName}</strong>
|
||||
{firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'}
|
||||
{attendee.phone ? (
|
||||
<span className="mt-1 block text-xs text-foreground/50">Teléfono: {attendee.phone}</span>
|
||||
<span className="mt-1 block text-xs text-foreground/50">
|
||||
Teléfono: {formatPhoneDisplay(attendee.phone)}
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
|
||||
78
apps/web/src/features/groups/detail/SectionChips.tsx
Normal file
78
apps/web/src/features/groups/detail/SectionChips.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Inbox, Users } from 'lucide-react'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { type ListSection, useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
const SECTIONS = [
|
||||
{ id: 'members', label: 'Miembros', icon: Users },
|
||||
{ id: 'pending', label: 'Pendientes', icon: Inbox },
|
||||
] as const satisfies ReadonlyArray<{
|
||||
id: ListSection
|
||||
label: string
|
||||
icon: typeof Users
|
||||
}>
|
||||
|
||||
export function SectionChips() {
|
||||
const {
|
||||
listSection,
|
||||
setListSection,
|
||||
attendeesTotal,
|
||||
preRegistrationsTotal,
|
||||
waitlistTotal,
|
||||
} = useGroupDetail()
|
||||
|
||||
const counts: Record<ListSection, number> = {
|
||||
members: attendeesTotal,
|
||||
pending: preRegistrationsTotal + waitlistTotal,
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Listado del grupo"
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
>
|
||||
{SECTIONS.map((section) => {
|
||||
const isActive = listSection === section.id
|
||||
const count = counts[section.id]
|
||||
// Ámbar solo cuando hay algo que decidir: pre-inscripciones por revisar.
|
||||
const isAttention = section.id === 'pending' && preRegistrationsTotal > 0
|
||||
const Icon = section.icon
|
||||
|
||||
return (
|
||||
<button
|
||||
key={section.id}
|
||||
type="button"
|
||||
aria-pressed={isActive}
|
||||
onClick={() => setListSection(section.id)}
|
||||
className={cn(
|
||||
// min-h-11 (44px): objetivo táctil mínimo de iOS/Android.
|
||||
'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',
|
||||
isActive
|
||||
? 'border-transparent bg-accent text-on-accent shadow-xs'
|
||||
: 'border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3.5 shrink-0" />
|
||||
<span className="whitespace-nowrap">{section.label}</span>
|
||||
{count > 0 ? (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums',
|
||||
isActive
|
||||
? 'bg-on-accent/25 text-on-accent'
|
||||
: isAttention
|
||||
? 'bg-warning-soft text-warning'
|
||||
: 'bg-primary-soft text-foreground/70',
|
||||
)}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { DetailRow } from './DetailRow'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
@@ -44,7 +45,7 @@ export function WaitlistEntryDetailModal() {
|
||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||
{selectedWaitlistEntry.phone ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-primary">{selectedWaitlistEntry.phone}</span>
|
||||
<span className="text-primary">{formatPhoneDisplay(selectedWaitlistEntry.phone)}</span>
|
||||
<a
|
||||
href={`https://wa.me/${selectedWaitlistEntry.phone.replace(/\D/g, '')}`}
|
||||
target="_blank"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { formatPhoneDisplay } from '../../../lib/format'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) {
|
||||
@@ -9,9 +10,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
|
||||
<table className="w-full table-fixed text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||
<th scope="col" className="w-[54%] px-3 pb-2">Nombre</th>
|
||||
<th scope="col" className="px-3 pb-2">Teléfono</th>
|
||||
<th scope="col" className="w-9 px-1 pb-2">
|
||||
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
|
||||
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
|
||||
<th scope="col" className="w-8 px-1 pb-1.5">
|
||||
<span className="sr-only">Detalle</span>
|
||||
</th>
|
||||
</tr>
|
||||
@@ -20,16 +21,23 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
|
||||
{entries.map((entry) => (
|
||||
<tr
|
||||
key={entry.id}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60"
|
||||
tabIndex={0}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
|
||||
onClick={() => setSelectedWaitlistEntry(entry)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
setSelectedWaitlistEntry(entry)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
|
||||
<td className="px-2 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">
|
||||
{entry.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium text-primary" title={entry.fullName}>
|
||||
<p className="truncate font-semibold text-primary" title={entry.fullName}>
|
||||
{entry.fullName}
|
||||
</p>
|
||||
{entry.notes ? (
|
||||
@@ -40,16 +48,16 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="min-w-0 px-3 py-2.5 text-foreground/80">
|
||||
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70">
|
||||
{entry.phone ? (
|
||||
<span className="block truncate tabular-nums" title={entry.phone}>
|
||||
{entry.phone}
|
||||
{formatPhoneDisplay(entry.phone)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-foreground/60">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="w-9 px-1 py-2.5 text-foreground/50">
|
||||
<td className="w-8 px-1 py-2 text-foreground/50">
|
||||
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -43,6 +43,11 @@ export function GroupInviteSummary() {
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<p className="mt-3 text-xs leading-relaxed text-foreground/60">
|
||||
Al completar el formulario envías una solicitud de pre-inscripción. El profesor revisará tus
|
||||
datos y te confirmará el lugar.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ export function JoinForm() {
|
||||
className="w-full gap-2 py-2.5 text-sm font-semibold"
|
||||
>
|
||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
<span>Completar Inscripción</span>
|
||||
<span>Enviar Solicitud</span>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -4,11 +4,6 @@ import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import type { GroupInviteInfoDto } from '@gruperly/shared'
|
||||
import { ApiError, getInviteInfo, joinViaInvite } from '../../lib/api'
|
||||
|
||||
type RegisteredAttendee = {
|
||||
fullName: string
|
||||
phone: string | null
|
||||
}
|
||||
|
||||
type JoinGroupContextValue = {
|
||||
token: string
|
||||
group: GroupInviteInfoDto | undefined
|
||||
@@ -23,8 +18,7 @@ type JoinGroupContextValue = {
|
||||
email: string
|
||||
setEmail: (value: string) => void
|
||||
errorMessage: string | null
|
||||
registeredAttendee: RegisteredAttendee | null
|
||||
waitlistMessage: string | null
|
||||
preRegistrationMessage: string | null
|
||||
submit: () => void
|
||||
isSubmitting: boolean
|
||||
}
|
||||
@@ -37,8 +31,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [registeredAttendee, setRegisteredAttendee] = useState<RegisteredAttendee | null>(null)
|
||||
const [waitlistMessage, setWaitlistMessage] = useState<string | null>(null)
|
||||
const [preRegistrationMessage, setPreRegistrationMessage] = useState<string | null>(null)
|
||||
|
||||
const inviteQuery = useQuery({
|
||||
queryKey: ['public-invite', token],
|
||||
@@ -57,16 +50,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
}),
|
||||
onSuccess: (data) => {
|
||||
setErrorMessage(null)
|
||||
if (data.status === 'waitlisted') {
|
||||
setRegisteredAttendee(null)
|
||||
setWaitlistMessage(data.message)
|
||||
return
|
||||
}
|
||||
setWaitlistMessage(null)
|
||||
setRegisteredAttendee({
|
||||
fullName: data.attendee?.fullName ?? `${firstName.trim()} ${lastName.trim()}`.trim(),
|
||||
phone: data.attendee?.phone ?? null,
|
||||
})
|
||||
setPreRegistrationMessage(data.message)
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
if (error instanceof ApiError) {
|
||||
@@ -76,6 +60,16 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
)
|
||||
return
|
||||
}
|
||||
if (error.problem?.code === 'pre_registration_already_pending') {
|
||||
setErrorMessage(
|
||||
'Ya enviaste una solicitud de inscripción para este grupo y está pendiente de revisión. Pronto recibirás novedades.',
|
||||
)
|
||||
return
|
||||
}
|
||||
if (error.problem?.code === 'pre_registration_already_approved') {
|
||||
setErrorMessage('Tu inscripción para este grupo ya fue aprobada.')
|
||||
return
|
||||
}
|
||||
setErrorMessage(error.message || 'Error al procesar la inscripción.')
|
||||
return
|
||||
}
|
||||
@@ -110,8 +104,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
email,
|
||||
setEmail,
|
||||
errorMessage,
|
||||
registeredAttendee,
|
||||
waitlistMessage,
|
||||
preRegistrationMessage,
|
||||
submit,
|
||||
isSubmitting: joinMutation.isPending,
|
||||
}
|
||||
@@ -125,4 +118,4 @@ export function useJoinGroup() {
|
||||
throw new Error('useJoinGroup debe usarse dentro de <JoinGroupProvider>')
|
||||
}
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,11 @@ import { PublicFooter, PublicHeader } from '../../components/layout'
|
||||
import { GroupInviteSummary } from './GroupInviteSummary'
|
||||
import { InvalidInviteCard } from './InvalidInviteCard'
|
||||
import { JoinForm } from './JoinForm'
|
||||
import { JoinSuccessCard } from './JoinSuccessCard'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
import { WaitlistNoticeCard } from './WaitlistNoticeCard'
|
||||
import { PreRegistrationNoticeCard } from './PreRegistrationNoticeCard'
|
||||
|
||||
export function JoinGroupView() {
|
||||
const { group, invitePending, inviteFailed, registeredAttendee, waitlistMessage } = useJoinGroup()
|
||||
const { group, invitePending, inviteFailed, preRegistrationMessage } = useJoinGroup()
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
|
||||
@@ -25,10 +24,9 @@ export function JoinGroupView() {
|
||||
|
||||
{inviteFailed || (!group && !invitePending) ? <InvalidInviteCard /> : null}
|
||||
|
||||
{registeredAttendee ? <JoinSuccessCard /> : null}
|
||||
{waitlistMessage ? <WaitlistNoticeCard /> : null}
|
||||
{preRegistrationMessage ? <PreRegistrationNoticeCard /> : null}
|
||||
|
||||
{!registeredAttendee && !waitlistMessage && group ? (
|
||||
{!preRegistrationMessage && group ? (
|
||||
<div className="space-y-6 rounded-2xl border border-border bg-surface p-6 shadow-xl sm:p-8">
|
||||
<GroupInviteSummary />
|
||||
<JoinForm />
|
||||
@@ -40,4 +38,4 @@ export function JoinGroupView() {
|
||||
<PublicFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { Badge } from '../../components/ui'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
|
||||
export function JoinSuccessCard() {
|
||||
const { group, registeredAttendee } = useJoinGroup()
|
||||
if (!group || !registeredAttendee) return null
|
||||
|
||||
return (
|
||||
<div className="animate-step-enter space-y-5 rounded-2xl border border-success/30 bg-surface p-6 text-center shadow-xl sm:p-8">
|
||||
<div className="mx-auto flex size-16 items-center justify-center rounded-full bg-success-soft text-success">
|
||||
<CheckCircle2 className="size-10" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Badge variant="success" className="mb-2">
|
||||
Registro Confirmado
|
||||
</Badge>
|
||||
<h1 className="text-2xl font-bold text-primary">¡Inscripción Exitosa!</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">
|
||||
Tus datos han sido registrados con éxito en el grupo{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-xl border border-border bg-primary-soft/50 p-4 text-left text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Profesor:</span>
|
||||
<span className="font-semibold text-primary">{group.teacherName}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Alumno:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.fullName}</span>
|
||||
</div>
|
||||
{registeredAttendee.phone ? (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Teléfono registrado:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.phone}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-foreground/60">
|
||||
El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y
|
||||
coordinar los detalles de la clase.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import { Clock } from 'lucide-react'
|
||||
import { Badge } from '../../components/ui'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
|
||||
export function WaitlistNoticeCard() {
|
||||
const { group, waitlistMessage } = useJoinGroup()
|
||||
if (!group || !waitlistMessage) return null
|
||||
export function PreRegistrationNoticeCard() {
|
||||
const { group, preRegistrationMessage } = useJoinGroup()
|
||||
if (!group || !preRegistrationMessage) return null
|
||||
|
||||
return (
|
||||
<div className="animate-step-enter space-y-5 rounded-2xl border border-accent/30 bg-surface p-6 text-center shadow-xl sm:p-8">
|
||||
@@ -14,16 +14,17 @@ export function WaitlistNoticeCard() {
|
||||
|
||||
<div>
|
||||
<Badge variant="neutral" className="mb-2">
|
||||
Lista de Espera
|
||||
Pre-inscripción
|
||||
</Badge>
|
||||
<h1 className="text-2xl font-bold text-primary">Cupo completo</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{waitlistMessage}</p>
|
||||
<h1 className="text-2xl font-bold text-primary">Solicitud enviada</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{preRegistrationMessage}</p>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-foreground/60">
|
||||
El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong>.
|
||||
El profesor revisará tu solicitud para el grupo{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong> y se pondrá en contacto
|
||||
contigo por WhatsApp para confirmarte el lugar.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
65
apps/web/src/hooks/useLargeTitleCollapse.ts
Normal file
65
apps/web/src/hooks/useLargeTitleCollapse.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
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. */
|
||||
const BAR_HEIGHT = 56
|
||||
|
||||
function clamp01(value: number) {
|
||||
if (value < 0) return 0
|
||||
return value > 1 ? 1 : value
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
export function useLargeTitleCollapse() {
|
||||
const titleRef = useRef<HTMLHeadingElement>(null)
|
||||
const [progress, setProgress] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const title = titleRef.current
|
||||
if (!title) return
|
||||
|
||||
let frame = 0
|
||||
|
||||
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).
|
||||
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.
|
||||
setProgress((current) => (Math.abs(current - next) < 0.002 ? current : next))
|
||||
}
|
||||
|
||||
const schedule = () => {
|
||||
if (frame === 0) frame = requestAnimationFrame(measure)
|
||||
}
|
||||
|
||||
measure()
|
||||
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.
|
||||
const observer = new ResizeObserver(schedule)
|
||||
observer.observe(title)
|
||||
|
||||
return () => {
|
||||
if (frame !== 0) cancelAnimationFrame(frame)
|
||||
window.removeEventListener('scroll', schedule)
|
||||
window.removeEventListener('resize', schedule)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { titleRef, progress }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AbsenceDetails,
|
||||
ApproveGroupPreRegistrationResult,
|
||||
AttendeeDto,
|
||||
AttendeeHistory,
|
||||
AttendeeList,
|
||||
@@ -20,6 +21,7 @@ import type {
|
||||
GroupDto,
|
||||
GroupInviteInfoDto,
|
||||
GroupList,
|
||||
GroupPreRegistrationList,
|
||||
GroupRiskSummary,
|
||||
GroupsRiskOverview,
|
||||
GroupWaitlistEntryDto,
|
||||
@@ -36,6 +38,7 @@ import type {
|
||||
ProblemDetails,
|
||||
PromoteGroupWaitlistEntryResult,
|
||||
PublicNotifyAbsence,
|
||||
RejectGroupPreRegistrationResult,
|
||||
RemoveAttendeeResult,
|
||||
RemoveGroupWaitlistEntryResult,
|
||||
SessionStudents,
|
||||
@@ -180,6 +183,23 @@ export const removeGroupWaitlistEntry = (groupId: string, entryId: string) =>
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
export const getGroupPreRegistrations = (groupId: string, page = 1, pageSize = 100) =>
|
||||
apiFetch<GroupPreRegistrationList>(
|
||||
`/api/v1/groups/${groupId}/preregistrations?page=${page}&pageSize=${pageSize}`,
|
||||
)
|
||||
|
||||
export const approveGroupPreRegistration = (groupId: string, entryId: string) =>
|
||||
apiFetch<ApproveGroupPreRegistrationResult>(
|
||||
`/api/v1/groups/${groupId}/preregistrations/${entryId}/approve`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
|
||||
export const rejectGroupPreRegistration = (groupId: string, entryId: string) =>
|
||||
apiFetch<RejectGroupPreRegistrationResult>(
|
||||
`/api/v1/groups/${groupId}/preregistrations/${entryId}/reject`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
|
||||
export const removeGroupAttendee = (
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
|
||||
|
||||
import { countryOf, currencyForRegion, localeForRegion } from './region'
|
||||
|
||||
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
|
||||
MONDAY: 'Lunes',
|
||||
TUESDAY: 'Martes',
|
||||
@@ -49,7 +51,210 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
|
||||
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
|
||||
}
|
||||
|
||||
export function formatPrice(price: number | null): string {
|
||||
/* 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. */
|
||||
|
||||
/* 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. */
|
||||
type BrowserNavigator = { language?: string; languages?: readonly string[] }
|
||||
|
||||
function browserLocale(): string | undefined {
|
||||
const nav = (globalThis as { navigator?: BrowserNavigator }).navigator
|
||||
return nav?.language || nav?.languages?.[0] || undefined
|
||||
}
|
||||
|
||||
const priceFormatters = new Map<string, Intl.NumberFormat>()
|
||||
|
||||
export function formatPrice(
|
||||
price: number | null,
|
||||
currency?: string,
|
||||
locale?: string,
|
||||
): string {
|
||||
if (price == null) return '—'
|
||||
return price.toLocaleString('es-MX', { style: 'currency', currency: 'MXN' })
|
||||
}
|
||||
// Importes enteros sin decimales ($50.000); con centavos se respetan.
|
||||
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).
|
||||
const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser
|
||||
const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}`
|
||||
|
||||
let formatter = priceFormatters.get(key)
|
||||
if (!formatter) {
|
||||
formatter = new Intl.NumberFormat(resolved, {
|
||||
style: 'currency',
|
||||
currency: resolvedCurrency ?? 'USD',
|
||||
currencyDisplay: resolvedCurrency ? 'symbol' : 'narrowSymbol',
|
||||
minimumFractionDigits: hasCents ? 2 : 0,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
priceFormatters.set(key, formatter)
|
||||
}
|
||||
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. */
|
||||
const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu
|
||||
|
||||
function tidyCurrencySpacing(value: string): string {
|
||||
return value.replace(SYMBOL_GAP, '$1')
|
||||
}
|
||||
|
||||
/* ── Teléfonos ──────────────────────────────────────────────────────────────
|
||||
|
||||
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. */
|
||||
|
||||
type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX'
|
||||
|
||||
/** Prefijos de país que sabemos agrupar. */
|
||||
const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [
|
||||
{ region: 'AR', code: '54' },
|
||||
{ region: 'ES', code: '34' },
|
||||
{ region: 'MX', code: '52' },
|
||||
{ region: 'US', code: '1' },
|
||||
]
|
||||
|
||||
export function formatPhoneDisplay(
|
||||
value: string | null | undefined,
|
||||
locale?: string,
|
||||
): string | null {
|
||||
if (value == null) return null
|
||||
const raw = value.trim()
|
||||
if (!raw) return null
|
||||
|
||||
const hasPlus = raw.startsWith('+')
|
||||
let digits = raw.replace(/\D/g, '')
|
||||
// "0054…" es el mismo indicio internacional que "+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
|
||||
if (hasPlus || hasDoubleZero) return `+${digits}`
|
||||
|
||||
return formatNational(digits, appRegion(countryOf(locale ?? browserLocale())), false) ?? raw
|
||||
}
|
||||
|
||||
/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */
|
||||
function formatWithCallingCode(digits: string): string | null {
|
||||
for (const { region, code } of COUNTRY_CALLING_CODES) {
|
||||
if (!digits.startsWith(code)) continue
|
||||
const formatted = formatNational(digits.slice(code.length), region, true)
|
||||
if (formatted) return formatted
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Región ISO → región con reglas propias. CA comparte NANP con 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.
|
||||
return 'AR'
|
||||
}
|
||||
|
||||
function formatNational(
|
||||
digits: string,
|
||||
region: PhoneRegion,
|
||||
hasCallingCode: boolean,
|
||||
): string | null {
|
||||
switch (region) {
|
||||
case 'AR':
|
||||
return formatArNational(digits, hasCallingCode)
|
||||
case 'US':
|
||||
return formatUsNational(digits)
|
||||
case 'ES':
|
||||
return formatEsNational(digits, hasCallingCode)
|
||||
case 'MX':
|
||||
return formatMxNational(digits, hasCallingCode)
|
||||
}
|
||||
}
|
||||
|
||||
function formatArNational(digits: string, withCountry: boolean): string | null {
|
||||
let national = digits
|
||||
let isMobile = false
|
||||
|
||||
// Móvil argentino: 9 + 10 dígitos nacionales.
|
||||
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.
|
||||
if (national.startsWith('0') && national.length >= 9) {
|
||||
national = national.slice(1)
|
||||
withCountry = true
|
||||
}
|
||||
if (national.length < 6 || national.length > 10) return null
|
||||
|
||||
const local = groupArNational(national)
|
||||
const body = isMobile ? `9 ${local}` : local
|
||||
return withCountry ? `+54 ${body}` : body
|
||||
}
|
||||
|
||||
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.
|
||||
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)}`
|
||||
}
|
||||
if (digits.length === 9) return `${digits.slice(0, 3)} ${digits.slice(3, 5)}-${digits.slice(5)}`
|
||||
if (digits.length <= 8) return `${digits.slice(0, 4)} ${digits.slice(4)}`
|
||||
return digits
|
||||
}
|
||||
|
||||
/** NANP (US/CA): 10 dígitos con área e intercambio que arrancan en 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.
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
export function formatBillingMeta(
|
||||
billingType: BillingType | null,
|
||||
dueDay: number | null,
|
||||
): string | null {
|
||||
if (billingType === 'PER_CLASS') return BILLING_LABELS.PER_CLASS
|
||||
if (billingType === 'MONTHLY') {
|
||||
return dueDay ? `Vence el día ${dueDay} de cada mes` : BILLING_LABELS.MONTHLY
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
33
apps/web/src/lib/immersive-routes.ts
Normal file
33
apps/web/src/lib/immersive-routes.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/* 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.
|
||||
|
||||
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. */
|
||||
|
||||
const IMMERSIVE_SEGMENTS: ReadonlyArray<readonly string[]> = [
|
||||
['groups', ':id'],
|
||||
['groups', ':id', 'analytics'],
|
||||
['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. */
|
||||
const STATIC_SEGMENTS: ReadonlySet<string> = new Set(['new'])
|
||||
|
||||
export function isImmersiveRoute(pathname: string) {
|
||||
const segments = pathname.split('/').filter(Boolean)
|
||||
|
||||
return IMMERSIVE_SEGMENTS.some(
|
||||
(pattern) =>
|
||||
pattern.length === segments.length &&
|
||||
pattern.every((part, index) => {
|
||||
const segment = segments[index]
|
||||
if (part.startsWith(':')) return !STATIC_SEGMENTS.has(segment)
|
||||
return part === segment
|
||||
}),
|
||||
)
|
||||
}
|
||||
271
apps/web/src/lib/region.ts
Normal file
271
apps/web/src/lib/region.ts
Normal file
@@ -0,0 +1,271 @@
|
||||
/* De dónde es la persona y cómo se le escriben los números.
|
||||
|
||||
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.
|
||||
|
||||
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. */
|
||||
|
||||
export const REGION_CURRENCY: Record<string, string> = {
|
||||
// Norteamérica
|
||||
CA: 'CAD',
|
||||
US: 'USD',
|
||||
|
||||
// Latinoamérica y Caribe
|
||||
AR: 'ARS',
|
||||
BO: 'BOB',
|
||||
BR: 'BRL',
|
||||
CL: 'CLP',
|
||||
CO: 'COP',
|
||||
CR: 'CRC',
|
||||
CU: 'CUP',
|
||||
DO: 'DOP',
|
||||
EC: 'USD',
|
||||
GT: 'GTQ',
|
||||
HN: 'HNL',
|
||||
MX: 'MXN',
|
||||
NI: 'NIO',
|
||||
PA: 'USD',
|
||||
PE: 'PEN',
|
||||
PR: 'USD',
|
||||
PY: 'PYG',
|
||||
SV: 'USD',
|
||||
UY: 'UYU',
|
||||
VE: 'VES',
|
||||
|
||||
// Zona euro
|
||||
AT: 'EUR',
|
||||
BE: 'EUR',
|
||||
HR: 'EUR',
|
||||
CY: 'EUR',
|
||||
EE: 'EUR',
|
||||
FI: 'EUR',
|
||||
FR: 'EUR',
|
||||
DE: 'EUR',
|
||||
GR: 'EUR',
|
||||
IE: 'EUR',
|
||||
IT: 'EUR',
|
||||
LV: 'EUR',
|
||||
LT: 'EUR',
|
||||
LU: 'EUR',
|
||||
MT: 'EUR',
|
||||
NL: 'EUR',
|
||||
PT: 'EUR',
|
||||
SK: 'EUR',
|
||||
SI: 'EUR',
|
||||
ES: 'EUR',
|
||||
|
||||
// Fuera de la zona euro
|
||||
CH: 'CHF',
|
||||
GB: 'GBP',
|
||||
CZ: 'CZK',
|
||||
DK: 'DKK',
|
||||
NO: 'NOK',
|
||||
PL: 'PLN',
|
||||
RU: 'RUB',
|
||||
SE: 'SEK',
|
||||
TR: 'TRY',
|
||||
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. */
|
||||
export const REGION_LOCALE: Record<string, string> = {
|
||||
// Norteamérica
|
||||
CA: 'en-CA',
|
||||
US: 'en-US',
|
||||
|
||||
// Latinoamérica y Caribe
|
||||
AR: 'es-AR',
|
||||
BO: 'es-BO',
|
||||
BR: 'pt-BR',
|
||||
CL: 'es-CL',
|
||||
CO: 'es-CO',
|
||||
CR: 'es-CR',
|
||||
CU: 'es-CU',
|
||||
DO: 'es-DO',
|
||||
EC: 'es-EC',
|
||||
GT: 'es-GT',
|
||||
HN: 'es-HN',
|
||||
MX: 'es-MX',
|
||||
NI: 'es-NI',
|
||||
PA: 'es-PA',
|
||||
PE: 'es-PE',
|
||||
PR: 'es-PR',
|
||||
PY: 'es-PY',
|
||||
SV: 'es-SV',
|
||||
UY: 'es-UY',
|
||||
VE: 'es-VE',
|
||||
|
||||
// Zona euro
|
||||
AT: 'de-AT',
|
||||
BE: 'nl-BE',
|
||||
HR: 'hr-HR',
|
||||
CY: 'el-CY',
|
||||
EE: 'et-EE',
|
||||
FI: 'fi-FI',
|
||||
FR: 'fr-FR',
|
||||
DE: 'de-DE',
|
||||
GR: 'el-GR',
|
||||
IE: 'en-IE',
|
||||
IT: 'it-IT',
|
||||
LV: 'lv-LV',
|
||||
LT: 'lt-LT',
|
||||
LU: 'fr-LU',
|
||||
MT: 'mt-MT',
|
||||
NL: 'nl-NL',
|
||||
PT: 'pt-PT',
|
||||
SK: 'sk-SK',
|
||||
SI: 'sl-SI',
|
||||
ES: 'es-ES',
|
||||
|
||||
// Fuera de la zona euro
|
||||
CH: 'de-CH',
|
||||
GB: 'en-GB',
|
||||
CZ: 'cs-CZ',
|
||||
DK: 'da-DK',
|
||||
NO: 'nb-NO',
|
||||
PL: 'pl-PL',
|
||||
RU: 'ru-RU',
|
||||
SE: 'sv-SE',
|
||||
TR: 'tr-TR',
|
||||
UA: 'uk-UA',
|
||||
}
|
||||
|
||||
/* Zona horaria IANA → región ISO 3166-1 alpha-2.
|
||||
|
||||
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. */
|
||||
export const TIMEZONE_REGION: Record<string, string> = {
|
||||
// ── Latinoamérica ─────────────────────────────────────────────────────────
|
||||
'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.
|
||||
'America/Buenos_Aires': 'AR',
|
||||
'America/Catamarca': 'AR',
|
||||
'America/Cordoba': 'AR',
|
||||
'America/Jujuy': 'AR',
|
||||
'America/Mendoza': 'AR',
|
||||
'America/La_Paz': 'BO',
|
||||
'America/Sao_Paulo': 'BR',
|
||||
'America/Fortaleza': 'BR',
|
||||
'America/Recife': 'BR',
|
||||
'America/Bahia': 'BR',
|
||||
'America/Manaus': 'BR',
|
||||
'America/Cuiaba': 'BR',
|
||||
'America/Porto_Velho': 'BR',
|
||||
'America/Noronha': 'BR',
|
||||
'America/Campo_Grande': 'BR',
|
||||
'America/Santiago': 'CL',
|
||||
'America/Bogota': 'CO',
|
||||
'America/Lima': 'PE',
|
||||
'America/Asuncion': 'PY',
|
||||
'America/Montevideo': 'UY',
|
||||
'America/Caracas': 'VE',
|
||||
'America/Guayaquil': 'EC',
|
||||
'America/Panama': 'PA',
|
||||
'America/Managua': 'NI',
|
||||
'America/Tegucigalpa': 'HN',
|
||||
'America/El_Salvador': 'SV',
|
||||
'America/Guatemala': 'GT',
|
||||
'America/Costa_Rica': 'CR',
|
||||
'America/Havana': 'CU',
|
||||
'America/Santo_Domingo': 'DO',
|
||||
'America/Puerto_Rico': 'PR',
|
||||
|
||||
// ── Norteamérica ─────────────────────────────────────────────────────────
|
||||
'America/New_York': 'US',
|
||||
'America/Detroit': 'US',
|
||||
'America/Chicago': 'US',
|
||||
'America/Denver': 'US',
|
||||
'America/Phoenix': 'US',
|
||||
'America/Los_Angeles': 'US',
|
||||
'America/Anchorage': 'US',
|
||||
'Pacific/Honolulu': 'US',
|
||||
'America/Toronto': 'CA',
|
||||
'America/Vancouver': 'CA',
|
||||
'America/Winnipeg': 'CA',
|
||||
'America/Edmonton': 'CA',
|
||||
'America/Halifax': 'CA',
|
||||
'America/Regina': 'CA',
|
||||
'America/St_Johns': 'CA',
|
||||
|
||||
// ── Europa ───────────────────────────────────────────────────────────────
|
||||
'Europe/Madrid': 'ES',
|
||||
'Atlantic/Canary': 'ES',
|
||||
'Atlantic/Faeroe': 'ES',
|
||||
'Europe/Lisbon': 'PT',
|
||||
'Europe/Rome': 'IT',
|
||||
'Europe/Paris': 'FR',
|
||||
'Europe/Berlin': 'DE',
|
||||
'Europe/Vienna': 'AT',
|
||||
'Europe/Brussels': 'BE',
|
||||
'Europe/Amsterdam': 'NL',
|
||||
'Europe/Dublin': 'IE',
|
||||
'Europe/Zurich': 'CH',
|
||||
'Europe/London': 'GB',
|
||||
'Europe/Copenhagen': 'DK',
|
||||
'Europe/Oslo': 'NO',
|
||||
'Europe/Stockholm': 'SE',
|
||||
'Europe/Warsaw': 'PL',
|
||||
'Europe/Prague': 'CZ',
|
||||
'Europe/Helsinki': 'FI',
|
||||
'Europe/Athens': 'GR',
|
||||
'Europe/Kyiv': 'UA',
|
||||
'Europe/Kiev': 'UA',
|
||||
'Europe/Moscow': 'RU',
|
||||
'Europe/Istanbul': 'TR',
|
||||
}
|
||||
|
||||
const ZONE_PREFIXES = Object.keys(TIMEZONE_REGION).filter((zone) => zone.endsWith('/'))
|
||||
|
||||
export function browserTimezone(): string | undefined {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function regionForTimezone(timezone: string | undefined): string | undefined {
|
||||
if (!timezone) return undefined
|
||||
const exact = TIMEZONE_REGION[timezone]
|
||||
if (exact) return exact
|
||||
const prefix = ZONE_PREFIXES.find((zone) => timezone.startsWith(zone))
|
||||
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. */
|
||||
export function regionOf(locale: string | undefined): string | undefined {
|
||||
if (!locale || typeof Intl.Locale === 'undefined') return undefined
|
||||
try {
|
||||
return new Intl.Locale(locale).maximize().region
|
||||
} catch {
|
||||
return 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. */
|
||||
export function countryOf(locale: string | undefined): string | undefined {
|
||||
return regionForTimezone(browserTimezone()) ?? regionOf(locale)
|
||||
}
|
||||
|
||||
export function currencyForRegion(region: string | undefined): string | undefined {
|
||||
return region ? REGION_CURRENCY[region] : undefined
|
||||
}
|
||||
|
||||
export function localeForRegion(region: string | undefined): string | undefined {
|
||||
return region ? REGION_LOCALE[region] : undefined
|
||||
}
|
||||
299
apps/web/test/format.test.ts
Normal file
299
apps/web/test/format.test.ts
Normal file
@@ -0,0 +1,299 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
|
||||
import { formatPhoneDisplay, formatPrice } from '../src/lib/format'
|
||||
import {
|
||||
browserTimezone,
|
||||
countryOf,
|
||||
currencyForRegion,
|
||||
localeForRegion,
|
||||
REGION_CURRENCY,
|
||||
REGION_LOCALE,
|
||||
regionForTimezone,
|
||||
regionOf,
|
||||
TIMEZONE_REGION,
|
||||
} from '../src/lib/region'
|
||||
|
||||
/* Un importe se pinta con el país de la persona: su moneda y su regional
|
||||
(separadores, posición del símbolo). El país sale de la zona horaria del
|
||||
sistema y, si no se conoce, del idioma del browser. El valor persistido no
|
||||
cambia: no hay conversión. */
|
||||
|
||||
const nav = globalThis as { navigator?: { language?: string; languages?: string[] } }
|
||||
|
||||
function stubLanguage(language: string) {
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
value: { language, languages: [language] },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
|
||||
function restoreNavigator() {
|
||||
delete (nav as { navigator?: unknown }).navigator
|
||||
}
|
||||
|
||||
/** Simula el navegador: idioma y zona horaria del sistema. */
|
||||
function stubLocation(language: string, timezone: string) {
|
||||
stubLanguage(language)
|
||||
const original = Intl.DateTimeFormat
|
||||
// Callable sin new, como Intl.DateTimeFormat().
|
||||
const fake = () => ({ resolvedOptions: () => ({ timeZone: timezone }) })
|
||||
;(Intl as { DateTimeFormat: unknown }).DateTimeFormat = fake as never
|
||||
return () => {
|
||||
;(Intl as { DateTimeFormat: unknown }).DateTimeFormat = original
|
||||
}
|
||||
}
|
||||
|
||||
/** Ejecuta fn con un navegador simulado y deja todo como estaba. */
|
||||
function withLocation(language: string, timezone: string, fn: () => void) {
|
||||
const restore = stubLocation(language, timezone)
|
||||
try {
|
||||
fn()
|
||||
} finally {
|
||||
restore()
|
||||
}
|
||||
}
|
||||
|
||||
/** Pinta el importe como lo vería un browser con esa locale. */
|
||||
function priceFor(amount: number, language: string): string {
|
||||
stubLanguage(language)
|
||||
return formatPrice(amount)
|
||||
}
|
||||
|
||||
describe('formatPrice — país del browser', () => {
|
||||
beforeEach(() => stubLanguage('es-AR'))
|
||||
afterEach(() => restoreNavigator())
|
||||
|
||||
test('el idioma del browser define moneda y regional', () => {
|
||||
expect(priceFor(50_000, 'es-AR')).toBe('$50.000')
|
||||
expect(priceFor(50_000, 'es-MX')).toBe('$50,000')
|
||||
expect(priceFor(50_000, 'es-PE')).toBe('S/50,000')
|
||||
expect(priceFor(50_000, 'pt-BR')).toBe('R$50.000')
|
||||
expect(priceFor(50_000, 'es-ES')).toBe('50.000\u00A0€')
|
||||
expect(priceFor(50_000, 'en-US')).toBe('$50,000')
|
||||
expect(priceFor(50_000, 'en-CA')).toBe('$50,000')
|
||||
})
|
||||
|
||||
test('la zona horaria define el país si el idioma no lo dice', () => {
|
||||
// Browser en inglés, usuario en Argentina: pesos y separador de miles argentino.
|
||||
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||
expect(formatPrice(50_000)).toBe('$50.000')
|
||||
})
|
||||
})
|
||||
|
||||
test('la zona horaria gana sobre el idioma del browser', () => {
|
||||
withLocation('es-MX', 'America/Argentina/Buenos_Aires', () => {
|
||||
expect(formatPrice(50_000)).toBe('$50.000')
|
||||
})
|
||||
})
|
||||
|
||||
test('la zona horaria cubre otros países', () => {
|
||||
withLocation('es-419', 'America/Lima', () => {
|
||||
expect(formatPrice(50_000)).toBe('S/50,000')
|
||||
})
|
||||
withLocation('es-419', 'America/Mexico_City', () => {
|
||||
expect(formatPrice(50_000)).toBe('$50,000')
|
||||
})
|
||||
withLocation('es-419', 'Europe/Madrid', () => {
|
||||
expect(formatPrice(50_000)).toBe('50.000\u00A0€')
|
||||
})
|
||||
})
|
||||
|
||||
test('los centavos se conservan', () => {
|
||||
expect(priceFor(50_000.5, 'es-AR')).toBe('$50.000,50')
|
||||
expect(priceFor(50_000.5, 'es-MX')).toBe('$50,000.50')
|
||||
})
|
||||
|
||||
test('sin país ni zona conocida se ve el símbolo $', () => {
|
||||
withLocation('es-419', 'Africa/Algiers', () => {
|
||||
expect(formatPrice(50_000)).toBe('$50,000')
|
||||
})
|
||||
})
|
||||
|
||||
test('sin browser se ve el símbolo $ con la regional del runtime', () => {
|
||||
restoreNavigator()
|
||||
const value = formatPrice(50_000)
|
||||
expect(value).toContain('$')
|
||||
expect(value).toContain('50')
|
||||
expect(value).not.toContain('ARS')
|
||||
})
|
||||
|
||||
test('por defecto usa la locale del browser', () => {
|
||||
stubLanguage('en-US')
|
||||
expect(formatPrice(50_000)).toBe('$50,000')
|
||||
})
|
||||
|
||||
test('importes nulos y cero', () => {
|
||||
expect(formatPrice(null)).toBe('—')
|
||||
expect(priceFor(0, 'es-AR')).toBe('$0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatPrice — moneda y locale explícitos', () => {
|
||||
beforeEach(() => stubLanguage('es-AR'))
|
||||
afterEach(() => restoreNavigator())
|
||||
|
||||
test('separa y posiciona según la locale pedida', () => {
|
||||
expect(formatPrice(50_000, 'ARS', 'es-AR')).toBe('$50.000')
|
||||
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||
expect(formatPrice(50_000, 'ARS', 'es-ES')).toBe('50.000\u00A0ARS')
|
||||
})
|
||||
|
||||
test('muestra centavos solo cuando el importe los tiene', () => {
|
||||
expect(formatPrice(50_000.5, 'ARS', 'en-US')).toBe('ARS\u00A050,000.50')
|
||||
expect(formatPrice(50_000.5, 'ARS', 'es-AR')).toBe('$50.000,50')
|
||||
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||
})
|
||||
|
||||
test('ganan sobre el país del browser', () => {
|
||||
withLocation('en-US', 'America/Lima', () => {
|
||||
expect(formatPrice(50_000, 'ARS', 'es-AR')).toBe('$50.000')
|
||||
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('region', () => {
|
||||
test('el mapa de monedas usa códigos ISO válidos', () => {
|
||||
const known = Intl.supportedValuesOf('currency')
|
||||
for (const [region, currency] of Object.entries(REGION_CURRENCY)) {
|
||||
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||
expect(currency).toMatch(/^[A-Z]{3}$/)
|
||||
expect(known).toContain(currency)
|
||||
}
|
||||
})
|
||||
|
||||
test('el mapa de zonas usa códigos ISO y zonas reales', () => {
|
||||
for (const [zone, region] of Object.entries(TIMEZONE_REGION)) {
|
||||
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||
if (zone.endsWith('/')) continue
|
||||
expect(() => new Intl.DateTimeFormat('en-US', { timeZone: zone })).not.toThrow()
|
||||
}
|
||||
})
|
||||
|
||||
test('las locales por país son tags válidos y cubren a los países', () => {
|
||||
for (const [region, locale] of Object.entries(REGION_LOCALE)) {
|
||||
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||
expect(locale).toMatch(/^[a-z]{2}-[A-Z]{2}$/)
|
||||
expect(() => new Intl.NumberFormat(locale)).not.toThrow()
|
||||
}
|
||||
for (const region of Object.keys(REGION_CURRENCY)) {
|
||||
expect(localeForRegion(region)).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
test('el mapa de zonas cubre países que tienen moneda', () => {
|
||||
for (const zone of Object.keys(TIMEZONE_REGION)) {
|
||||
const resolvable = zone.endsWith('/') ? `${zone}Test` : zone
|
||||
expect(currencyForRegion(regionForTimezone(resolvable))).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
test('resuelve la zona por ciudad y por prefijo', () => {
|
||||
expect(regionForTimezone('America/Argentina/Buenos_Aires')).toBe('AR')
|
||||
expect(regionForTimezone('America/Argentina/Catamarca')).toBe('AR')
|
||||
expect(regionForTimezone('America/Sao_Paulo')).toBe('BR')
|
||||
expect(regionForTimezone('America/Lima')).toBe('PE')
|
||||
expect(regionForTimezone('Europe/Madrid')).toBe('ES')
|
||||
expect(regionForTimezone('Asia/Tokyo')).toBeUndefined()
|
||||
expect(regionForTimezone('Africa/Algiers')).toBeUndefined()
|
||||
expect(regionForTimezone('UTC')).toBeUndefined()
|
||||
expect(regionForTimezone(undefined)).toBeUndefined()
|
||||
})
|
||||
|
||||
test('las zonas legacy que reporta el browser también resuelven', () => {
|
||||
// Chromium/ICU canonicaliza America/Argentina/X a America/X.
|
||||
expect(regionForTimezone('America/Buenos_Aires')).toBe('AR')
|
||||
expect(regionForTimezone('America/Catamarca')).toBe('AR')
|
||||
expect(regionForTimezone('America/Mendoza')).toBe('AR')
|
||||
})
|
||||
|
||||
test('resuelve el país: la zona horaria primero', () => {
|
||||
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||
expect(countryOf('en-US')).toBe('AR')
|
||||
})
|
||||
withLocation('es-419', 'America/Lima', () => {
|
||||
expect(countryOf('es-419')).toBe('PE')
|
||||
})
|
||||
// Sin zona conocida manda el idioma.
|
||||
withLocation('es-MX', 'Africa/Algiers', () => {
|
||||
expect(countryOf('es-MX')).toBe('MX')
|
||||
})
|
||||
})
|
||||
|
||||
test('regionOf usa el locale que le pasan', () => {
|
||||
expect(regionOf('es-MX')).toBe('MX')
|
||||
expect(regionOf('es-419')).toBe('419')
|
||||
expect(regionOf('pt-BR')).toBe('BR')
|
||||
expect(regionOf(undefined)).toBeUndefined()
|
||||
})
|
||||
|
||||
test('lookup de moneda y regional por región', () => {
|
||||
expect(currencyForRegion('PE')).toBe('PEN')
|
||||
expect(currencyForRegion('MX')).toBe('MXN')
|
||||
expect(currencyForRegion('ES')).toBe('EUR')
|
||||
expect(currencyForRegion('US')).toBe('USD')
|
||||
expect(currencyForRegion('419')).toBeUndefined()
|
||||
expect(currencyForRegion('SE')).toBe('SEK')
|
||||
expect(currencyForRegion(undefined)).toBeUndefined()
|
||||
expect(localeForRegion('AR')).toBe('es-AR')
|
||||
expect(localeForRegion('BR')).toBe('pt-BR')
|
||||
expect(localeForRegion('419')).toBeUndefined()
|
||||
expect(localeForRegion(undefined)).toBeUndefined()
|
||||
})
|
||||
|
||||
test('el runtime expone una zona horaria', () => {
|
||||
// bun test corre en UTC; en el browser es la zona del sistema.
|
||||
expect(browserTimezone()).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatPhoneDisplay — región del número y país del browser', () => {
|
||||
beforeEach(() => stubLanguage('es-AR'))
|
||||
afterEach(() => restoreNavigator())
|
||||
|
||||
test('números argentinos conservan el formato actual', () => {
|
||||
expect(formatPhoneDisplay('+5492954667788', 'es-AR')).toBe('+54 9 2954 66-7788')
|
||||
expect(formatPhoneDisplay('5490989009988', 'es-AR')).toBe('+54 9 989 00-9988')
|
||||
expect(formatPhoneDisplay('0989009988', 'es-AR')).toBe('+54 989 00-9988')
|
||||
expect(formatPhoneDisplay('2983649550', 'es-AR')).toBe('2983 64-9550')
|
||||
})
|
||||
|
||||
test('número irreconocible se devuelve tal cual', () => {
|
||||
expect(formatPhoneDisplay('3209872223344', 'es-AR')).toBe('3209872223344')
|
||||
expect(formatPhoneDisplay('12345', 'es-AR')).toBe('12345')
|
||||
expect(formatPhoneDisplay(null)).toBeNull()
|
||||
expect(formatPhoneDisplay('')).toBeNull()
|
||||
})
|
||||
|
||||
test('números de otra región usan las reglas de esa región', () => {
|
||||
expect(formatPhoneDisplay('+12125551234', 'es-AR')).toBe('(212) 555-1234')
|
||||
expect(formatPhoneDisplay('+34612345678', 'es-AR')).toBe('+34 612 34 56 78')
|
||||
expect(formatPhoneDisplay('+525512345678', 'es-AR')).toBe('+52 55 1234 5678')
|
||||
})
|
||||
|
||||
test('nacional sin prefijo se agrupa según el país del browser', () => {
|
||||
expect(formatPhoneDisplay('2125551234', 'en-US')).toBe('(212) 555-1234')
|
||||
expect(formatPhoneDisplay('612345678', 'es-ES')).toBe('612 34 56 78')
|
||||
expect(formatPhoneDisplay('5512345678', 'es-MX')).toBe('55 1234 5678')
|
||||
})
|
||||
|
||||
test('la zona horaria define el país de los números nacionales', () => {
|
||||
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||
expect(formatPhoneDisplay('3364609550')).toBe('3364 60-9550')
|
||||
})
|
||||
})
|
||||
|
||||
test('el prefijo del número manda sobre el país del browser', () => {
|
||||
expect(formatPhoneDisplay('+5492954667788', 'en-US')).toBe('+54 9 2954 66-7788')
|
||||
})
|
||||
|
||||
test('región sin reglas propias cae a E.164', () => {
|
||||
expect(formatPhoneDisplay('+331234567890', 'es-AR')).toBe('+331234567890')
|
||||
expect(formatPhoneDisplay('00331234567890', 'es-AR')).toBe('+331234567890')
|
||||
})
|
||||
|
||||
test('por defecto usa el país del browser', () => {
|
||||
stubLanguage('en-US')
|
||||
expect(formatPhoneDisplay('2125551234')).toBe('(212) 555-1234')
|
||||
})
|
||||
})
|
||||
35
apps/web/test/immersive-routes.test.ts
Normal file
35
apps/web/test/immersive-routes.test.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { isImmersiveRoute } from '../src/lib/immersive-routes'
|
||||
|
||||
/* Solo las pantallas con Large Title arman su propia barra. Todo lo demás
|
||||
—incluidas las rutas hijas de un grupo— sigue con el header global. */
|
||||
|
||||
describe('isImmersiveRoute', () => {
|
||||
test('la ficha de grupo, sus estadísticas y la asistencia son immersive', () => {
|
||||
expect(isImmersiveRoute('/groups/cm1234')).toBe(true)
|
||||
expect(isImmersiveRoute('/groups/cm1234/analytics')).toBe(true)
|
||||
expect(isImmersiveRoute('/class/ses_987/attendance')).toBe(true)
|
||||
})
|
||||
|
||||
test('las rutas hijas del grupo no lo son', () => {
|
||||
expect(isImmersiveRoute('/groups')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/new')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/cm1234/attendees/new')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/cm1234/attendees/at_55')).toBe(false)
|
||||
})
|
||||
|
||||
test('el resto de la app mantiene el header global', () => {
|
||||
expect(isImmersiveRoute('/')).toBe(false)
|
||||
expect(isImmersiveRoute('/payments')).toBe(false)
|
||||
expect(isImmersiveRoute('/settings')).toBe(false)
|
||||
expect(isImmersiveRoute('/class/ses_987')).toBe(false)
|
||||
})
|
||||
|
||||
test('el chequeo es por segmento exacto, no por prefijo', () => {
|
||||
expect(isImmersiveRoute('/grupos/cm1234')).toBe(false)
|
||||
expect(isImmersiveRoute('/clas/ses_987/attendance')).toBe(false)
|
||||
expect(isImmersiveRoute('/grup')).toBe(false)
|
||||
expect(isImmersiveRoute('/groups/cm1234/analytics/extra')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -13,7 +13,7 @@
|
||||
"lint": "turbo lint",
|
||||
"lint:fix": "turbo lint:fix",
|
||||
"typecheck": "turbo typecheck",
|
||||
"test": "bun --filter @gruperly/backend test",
|
||||
"test": "bun --filter @gruperly/backend test && bun --filter @gruperly/web test",
|
||||
"db:generate": "bun --filter @gruperly/backend db:generate",
|
||||
"db:migrate": "bun --filter @gruperly/backend db:migrate",
|
||||
"db:push": "bun --filter @gruperly/backend db:push",
|
||||
|
||||
@@ -10,5 +10,6 @@ export * from './schemas/home.js';
|
||||
export * from './schemas/onboarding.js';
|
||||
export * from './schemas/pagination.js';
|
||||
export * from './schemas/payments.js';
|
||||
export * from './schemas/preregistrations.js';
|
||||
export * from './schemas/problem-details.js';
|
||||
export * from './schemas/waitlist.js';
|
||||
@@ -77,7 +77,7 @@ export const JoinGroupViaInviteSchema = z.object({
|
||||
export type JoinGroupViaInvite = z.output<typeof JoinGroupViaInviteSchema>;
|
||||
|
||||
export const JoinGroupViaInviteResultSchema = z.object({
|
||||
status: z.enum(['registered', 'waitlisted']),
|
||||
status: z.literal('pre_registered'),
|
||||
message: z.string(),
|
||||
attendee: AttendeeDtoSchema.nullable(),
|
||||
});
|
||||
|
||||
54
packages/shared/src/schemas/preregistrations.ts
Normal file
54
packages/shared/src/schemas/preregistrations.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { z } from 'zod';
|
||||
import { AttendeeDtoSchema } from './attendees.js';
|
||||
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
|
||||
import { GroupWaitlistEntryDtoSchema } from './waitlist.js';
|
||||
|
||||
const isoDateTimeSchema = z.string().datetime();
|
||||
const pageSchema = createPageSchema();
|
||||
const pageSizeSchema = createPageSizeSchema(10);
|
||||
const paginationSchema = createPaginationSchema();
|
||||
|
||||
export const preRegistrationStatusSchema = z.enum(['PENDING', 'APPROVED', 'REJECTED']);
|
||||
export type PreRegistrationStatus = z.output<typeof preRegistrationStatusSchema>;
|
||||
|
||||
export const GroupPreRegistrationDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
groupId: z.string(),
|
||||
fullName: z.string(),
|
||||
phone: z.string(),
|
||||
email: z.string().nullable(),
|
||||
status: preRegistrationStatusSchema,
|
||||
reviewedAt: isoDateTimeSchema.nullable(),
|
||||
createdAt: isoDateTimeSchema,
|
||||
updatedAt: isoDateTimeSchema,
|
||||
});
|
||||
export type GroupPreRegistrationDto = z.output<typeof GroupPreRegistrationDtoSchema>;
|
||||
|
||||
export const GroupPreRegistrationQuerySchema = z.object({
|
||||
page: pageSchema,
|
||||
pageSize: pageSizeSchema,
|
||||
status: preRegistrationStatusSchema.optional(),
|
||||
});
|
||||
export type GroupPreRegistrationQuery = z.output<typeof GroupPreRegistrationQuerySchema>;
|
||||
|
||||
export const GroupPreRegistrationListSchema = z.object({
|
||||
data: z.array(GroupPreRegistrationDtoSchema),
|
||||
pagination: paginationSchema,
|
||||
});
|
||||
export type GroupPreRegistrationList = z.output<typeof GroupPreRegistrationListSchema>;
|
||||
|
||||
export const ApproveGroupPreRegistrationResultSchema = z.object({
|
||||
outcome: z.enum(['added', 'waitlisted']),
|
||||
attendee: AttendeeDtoSchema.nullable(),
|
||||
waitlistEntry: GroupWaitlistEntryDtoSchema.nullable(),
|
||||
});
|
||||
export type ApproveGroupPreRegistrationResult = z.output<
|
||||
typeof ApproveGroupPreRegistrationResultSchema
|
||||
>;
|
||||
|
||||
export const RejectGroupPreRegistrationResultSchema = z.object({
|
||||
entry: GroupPreRegistrationDtoSchema,
|
||||
});
|
||||
export type RejectGroupPreRegistrationResult = z.output<
|
||||
typeof RejectGroupPreRegistrationResultSchema
|
||||
>;
|
||||
Reference in New Issue
Block a user