Compare commits
20 Commits
feat/atten
...
e9b44caf54
| Author | SHA1 | Date | |
|---|---|---|---|
| e9b44caf54 | |||
|
|
581cf2f2b2 | ||
|
|
81ed5747f3 | ||
|
|
8ccff20473 | ||
|
|
9520763ec3 | ||
|
|
5ef393fa64 | ||
|
|
45a1f50231 | ||
|
|
0f02331dfc | ||
|
|
df510cfe45 | ||
|
|
9f2e770509 | ||
|
|
2be59f99dd | ||
|
|
56096b1e35 | ||
|
|
2fd1826014 | ||
|
|
05da085e36 | ||
|
|
2e027408e6 | ||
|
|
54f1c7ab34 | ||
|
|
88c8b2ec90 | ||
|
|
0cd74194e3 | ||
|
|
f05fbf9e30 | ||
| 2370895710 |
29
.dockerignore
Normal file
29
.dockerignore
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Dependencias y artefactos locales: el build los regenera adentro de la imagen.
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
|
||||||
|
# Se generan en el builder (prisma generate, vite build).
|
||||||
|
apps/backend/generated
|
||||||
|
apps/backend/dist
|
||||||
|
apps/web/dist
|
||||||
|
.turbo
|
||||||
|
**/.turbo
|
||||||
|
|
||||||
|
# Secretos: en Dokploy llegan por variables de entorno.
|
||||||
|
.env
|
||||||
|
**/.env
|
||||||
|
!.env.example
|
||||||
|
**/.env.example
|
||||||
|
|
||||||
|
# Ruido del repo.
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.github
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
|
README.md
|
||||||
|
stack.md
|
||||||
|
skills-lock.json
|
||||||
|
**/skills-lock.json
|
||||||
|
.agents
|
||||||
|
**/.agents
|
||||||
38
.env.example
Normal file
38
.env.example
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# Plantilla de variables para `docker compose`.
|
||||||
|
#
|
||||||
|
# Local: copiá este archivo a `.env` en la raíz y completá los valores.
|
||||||
|
# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña
|
||||||
|
# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del
|
||||||
|
# compose, que es de donde salen los `${...}`).
|
||||||
|
|
||||||
|
# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y
|
||||||
|
# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten
|
||||||
|
# dominio y por lo tanto la cookie de sesión es first-party.
|
||||||
|
WEB_URL="http://localhost:8080"
|
||||||
|
|
||||||
|
# PostgreSQL de producción.
|
||||||
|
# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala
|
||||||
|
# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza
|
||||||
|
# el fragmento y falla con P1013 "invalid port number in database URL".
|
||||||
|
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||||
|
|
||||||
|
# Generalo con: openssl rand -base64 32
|
||||||
|
BETTER_AUTH_SECRET=""
|
||||||
|
|
||||||
|
# ── Opcionales ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Login social con Google. Sin client id/secret no se registra el provider.
|
||||||
|
# GOOGLE_CLIENT_ID=""
|
||||||
|
# GOOGLE_CLIENT_SECRET=""
|
||||||
|
|
||||||
|
# Envío de emails (mismas variables que apps/backend/.env.example).
|
||||||
|
# EMAIL_PROVIDER="smtp"
|
||||||
|
# EMAIL_SERVER_HOST=""
|
||||||
|
# EMAIL_SERVER_PORT="587"
|
||||||
|
# EMAIL_SERVER_USER=""
|
||||||
|
# EMAIL_SERVER_PASSWORD=""
|
||||||
|
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||||
|
|
||||||
|
# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga
|
||||||
|
# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado).
|
||||||
|
# VITE_API_URL=""
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -90,6 +90,8 @@ out
|
|||||||
# Nuxt.js build / generate output
|
# Nuxt.js build / generate output
|
||||||
.nuxt
|
.nuxt
|
||||||
dist
|
dist
|
||||||
|
# Service worker que vite-plugin-pwa escribe al serving en dev
|
||||||
|
dev-dist
|
||||||
|
|
||||||
# Gatsby files
|
# Gatsby files
|
||||||
.cache/
|
.cache/
|
||||||
|
|||||||
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.
|
||||||
11
AGENTS.md
11
AGENTS.md
@@ -21,6 +21,7 @@ bun run lint:fix # biome check --write
|
|||||||
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
bun --filter @gruperly/backend typecheck # verificación de un solo paquete
|
||||||
bun --filter @gruperly/backend test # bun test (backend)
|
bun --filter @gruperly/backend test # bun test (backend)
|
||||||
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push / db:studio
|
||||||
|
bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web/public/ (sharp)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Estructura y fronteras
|
## Estructura y fronteras
|
||||||
@@ -30,8 +31,8 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
|||||||
- `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/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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `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`).
|
- `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/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).
|
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||||
|
|
||||||
@@ -40,7 +41,9 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
|||||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- `.env`, `dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||||
|
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||||
|
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||||
|
|
||||||
## Convenciones repo-específicas
|
## Convenciones repo-específicas
|
||||||
|
|
||||||
@@ -51,8 +54,10 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push
|
|||||||
- **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 />`).
|
- **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.
|
- **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.
|
- 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.
|
- **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+`.
|
- 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.
|
||||||
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
|
||||||
|
|
||||||
## Fuentes de contexto
|
## Fuentes de contexto
|
||||||
|
|||||||
66
Dockerfile.backend
Normal file
66
Dockerfile.backend
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||||
|
FROM oven/bun:1.4-alpine AS base
|
||||||
|
WORKDIR /app
|
||||||
|
ENV CI=1
|
||||||
|
|
||||||
|
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||||
|
# Solo los package.json:bun no necesita el código fuente para resolver el lockfile.
|
||||||
|
FROM base AS deps
|
||||||
|
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY apps/web/package.json ./apps/web/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||||
|
# El generator "prisma-client" emite TypeScript, así que el cliente generado se
|
||||||
|
# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no
|
||||||
|
# necesita conexión, solo leer el schema.
|
||||||
|
FROM deps AS generate
|
||||||
|
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
|
||||||
|
ENV DATABASE_URL=$DATABASE_URL
|
||||||
|
COPY apps/backend/prisma.config.ts ./apps/backend/
|
||||||
|
COPY apps/backend/prisma ./apps/backend/prisma
|
||||||
|
WORKDIR /app/apps/backend
|
||||||
|
RUN bun run db:generate
|
||||||
|
|
||||||
|
# ─── Imagen de la API ────────────────────────────────────────────────────────
|
||||||
|
FROM base AS api
|
||||||
|
ENV NODE_ENV=production \
|
||||||
|
PORT=4000
|
||||||
|
|
||||||
|
COPY package.json bun.lock bunfig.toml ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# `prisma` y `dotenv` son dependencies (no dev) porque el entrypoint corre
|
||||||
|
# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto
|
||||||
|
# del tooling: biome, typescript, turbo.
|
||||||
|
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# El CLI de Prisma carga prisma.config.ts, que apunta al schema.
|
||||||
|
COPY apps/backend/prisma ./apps/backend/prisma
|
||||||
|
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
|
||||||
|
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
|
||||||
|
COPY apps/backend/tsconfig.json ./apps/backend/
|
||||||
|
COPY apps/backend/src ./apps/backend/src
|
||||||
|
# @gruperly/shared se consume como fuente TS; @gruperly/config aporta el
|
||||||
|
# tsconfig base del que extiende el tsconfig del backend.
|
||||||
|
COPY packages ./packages
|
||||||
|
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||||
|
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||||
|
|
||||||
|
WORKDIR /app/apps/backend
|
||||||
|
EXPOSE 4000
|
||||||
|
# Sin `${...}`: el CMD corre bajo /bin/sh (ash), donde eso es un error de sintaxis.
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||||
|
CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||||
|
|
||||||
|
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||||
|
# Bun ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json,
|
||||||
|
# igual que `bun start` en local.
|
||||||
|
CMD ["bun", "src/server.ts"]
|
||||||
35
Dockerfile.web
Normal file
35
Dockerfile.web
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ─── Base ────────────────────────────────────────────────────────────────────
|
||||||
|
FROM oven/bun:1.4-alpine AS base
|
||||||
|
WORKDIR /app
|
||||||
|
ENV CI=1
|
||||||
|
|
||||||
|
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||||
|
FROM base AS deps
|
||||||
|
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||||
|
COPY apps/backend/package.json ./apps/backend/
|
||||||
|
COPY apps/web/package.json ./apps/web/
|
||||||
|
COPY packages/config/package.json ./packages/config/
|
||||||
|
COPY packages/shared/package.json ./packages/shared/
|
||||||
|
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||||
|
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||||
|
|
||||||
|
# ─── Build de Vite ───────────────────────────────────────────────────────────
|
||||||
|
FROM deps AS build
|
||||||
|
# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime.
|
||||||
|
# Vacío = mismo origen: el proxy /api de nginx hace de API.
|
||||||
|
ARG VITE_API_URL=""
|
||||||
|
ENV VITE_API_URL=$VITE_API_URL
|
||||||
|
COPY apps/web ./apps/web
|
||||||
|
COPY packages ./packages
|
||||||
|
RUN bun --filter @gruperly/web build
|
||||||
|
|
||||||
|
# ─── Imagen final ────────────────────────────────────────────────────────────
|
||||||
|
FROM nginx:1.27-alpine AS web
|
||||||
|
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||||
|
EXPOSE 80
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||||
|
CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
85
README.md
85
README.md
@@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi
|
|||||||
- Package manager: [Bun](https://bun.sh/) 1.4
|
- Package manager: [Bun](https://bun.sh/) 1.4
|
||||||
- Monorepo: bun workspaces + Turborepo
|
- Monorepo: bun workspaces + Turborepo
|
||||||
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
|
||||||
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4
|
- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox)
|
||||||
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
|
||||||
|
|
||||||
## Estructura
|
## Estructura
|
||||||
@@ -31,9 +31,92 @@ bun run lint # biome check (backend y shared)
|
|||||||
bun --filter @gruperly/backend test # bun test (backend)
|
bun --filter @gruperly/backend test # bun test (backend)
|
||||||
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
|
||||||
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
|
||||||
|
bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## PWA
|
||||||
|
|
||||||
|
La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan.
|
||||||
|
|
||||||
|
- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline.
|
||||||
|
- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".**
|
||||||
|
- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo.
|
||||||
|
- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `<link>` a `fonts.googleapis.com`: era una dependencia de red en runtime.
|
||||||
|
- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio).
|
||||||
|
- Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar.
|
||||||
|
- El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador.
|
||||||
|
- El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`.
|
||||||
|
- Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt.
|
||||||
|
- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre.
|
||||||
|
|
||||||
|
### Requisitos para que funcione
|
||||||
|
|
||||||
|
El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx.
|
||||||
|
|
||||||
|
### Verificar
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun --filter @gruperly/web build
|
||||||
|
bun --filter @gruperly/web preview # http://localhost:4173
|
||||||
|
```
|
||||||
|
|
||||||
|
En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado.
|
||||||
|
|
||||||
## Setup de base de datos
|
## Setup de base de datos
|
||||||
|
|
||||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||||
|
|
||||||
|
## Deploy en producción (Docker / Dokploy)
|
||||||
|
|
||||||
|
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||||
|
|
||||||
|
- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`.
|
||||||
|
- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando.
|
||||||
|
- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa.
|
||||||
|
- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`.
|
||||||
|
|
||||||
|
### Variables de entorno
|
||||||
|
|
||||||
|
El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz.
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` |
|
||||||
|
| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio |
|
||||||
|
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
|
||||||
|
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
|
||||||
|
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
|
||||||
|
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||||
|
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||||
|
|
||||||
|
Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje.
|
||||||
|
|
||||||
|
### Pasos en Dokploy
|
||||||
|
|
||||||
|
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||||
|
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||||
|
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
|
||||||
|
4. Deploy.
|
||||||
|
|
||||||
|
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
||||||
|
|
||||||
|
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
||||||
|
|
||||||
|
### Correr las migraciones a mano
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec api bun run db:deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
### Comprobar el compose en local
|
||||||
|
|
||||||
|
Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la declara como externa:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network create dokploy-network # una sola vez
|
||||||
|
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
||||||
|
docker compose up --build -d
|
||||||
|
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||||
|
curl http://localhost:8080/api/v1/health
|
||||||
|
```
|
||||||
|
|||||||
42
apps/backend/docker-entrypoint.sh
Executable file
42
apps/backend/docker-entrypoint.sh
Executable file
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Entrypoint de producción del backend: aplica las migraciones y levanta el
|
||||||
|
# servidor en el mismo contenedor.
|
||||||
|
#
|
||||||
|
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo
|
||||||
|
# serían ~10MB por un shebang).
|
||||||
|
#
|
||||||
|
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una
|
||||||
|
# base ya migrada a mano o una que se gestiona fuera de este despliegue).
|
||||||
|
set -e
|
||||||
|
|
||||||
|
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||||
|
|
||||||
|
if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then
|
||||||
|
echo "migrate: omitido (RUN_MIGRATIONS=false)"
|
||||||
|
else
|
||||||
|
attempts="${MIGRATE_ATTEMPTS:-30}"
|
||||||
|
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||||
|
i=1
|
||||||
|
|
||||||
|
# La base puede seguir arrancando cuando este contenedor ya empezó, y un
|
||||||
|
# deploy suele convivir con un reinicio de Postgres.
|
||||||
|
while [ "$i" -le "$attempts" ]; do
|
||||||
|
if bun run db:deploy; then
|
||||||
|
echo "migrate: listo"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$i" -eq "$attempts" ]; then
|
||||||
|
echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2
|
||||||
|
i=$((i + 1))
|
||||||
|
sleep "$delay"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop`
|
||||||
|
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma).
|
||||||
|
exec "$@"
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
"lint:fix": "biome check . --write",
|
"lint:fix": "biome check . --write",
|
||||||
"db:generate": "prisma generate",
|
"db:generate": "prisma generate",
|
||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
|
"db:deploy": "prisma migrate deploy",
|
||||||
"db:push": "prisma db push",
|
"db:push": "prisma db push",
|
||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio"
|
||||||
},
|
},
|
||||||
@@ -23,10 +24,13 @@
|
|||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
"hono": "^4.13.3",
|
"hono": "^4.13.3",
|
||||||
|
"nanoid": "^3.3.19",
|
||||||
"nodemailer": "^9.0.6",
|
"nodemailer": "^9.0.6",
|
||||||
"pino": "^9.5.0",
|
"pino": "^9.5.0",
|
||||||
"pino-pretty": "^13.0.0",
|
"pino-pretty": "^13.0.0",
|
||||||
|
"prisma": "^7.10.0",
|
||||||
"zod": "3.24.2"
|
"zod": "3.24.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -35,8 +39,6 @@
|
|||||||
"@types/bun": "^1.4.0",
|
"@types/bun": "^1.4.0",
|
||||||
"@types/node": "^20.17.0",
|
"@types/node": "^20.17.0",
|
||||||
"@types/nodemailer": "^8.0.1",
|
"@types/nodemailer": "^8.0.1",
|
||||||
"dotenv": "^16.4.5",
|
|
||||||
"prisma": "^7.10.0",
|
|
||||||
"typescript": "^5.7.0"
|
"typescript": "^5.7.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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[]
|
attendees Attendee[]
|
||||||
payments Payment[]
|
payments Payment[]
|
||||||
waitlist GroupWaitlistEntry[]
|
waitlist GroupWaitlistEntry[]
|
||||||
|
preRegistrations GroupPreRegistration[]
|
||||||
classSessions ClassSession[]
|
classSessions ClassSession[]
|
||||||
|
|
||||||
@@map("groups")
|
@@map("groups")
|
||||||
@@ -157,6 +158,30 @@ enum WaitlistStatus {
|
|||||||
DECLINED
|
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 {
|
enum PaymentProvider {
|
||||||
MERCADO_PAGO
|
MERCADO_PAGO
|
||||||
STRIPE
|
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 getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createGroupRoute from './features/create/route';
|
import createGroupRoute from './features/create/route';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
@@ -24,6 +25,7 @@ routes.route('/', bulkCreateAttendeesRoute);
|
|||||||
routes.route('/', getByIdRoute);
|
routes.route('/', getByIdRoute);
|
||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
|
routes.route('/', groupPreRegistrationRoutes);
|
||||||
routes.route('/', analyticsRoutes);
|
routes.route('/', analyticsRoutes);
|
||||||
routes.route('/', getAttendeeRoute);
|
routes.route('/', getAttendeeRoute);
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
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 { err, ok } from '@gruperly/shared';
|
||||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||||
|
|
||||||
type JoinViaInviteDeps = {
|
type JoinViaInviteDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type JoinViaInviteResult = {
|
export type JoinViaInviteResult = {
|
||||||
status: 'registered' | 'waitlisted';
|
status: 'pre_registered';
|
||||||
message: string;
|
message: string;
|
||||||
attendee: AttendeeDto | null;
|
attendee: null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class JoinViaInvite {
|
export class JoinViaInvite {
|
||||||
@@ -53,50 +53,63 @@ export class JoinViaInvite {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||||
|
const email = payload.email?.trim() || null;
|
||||||
|
|
||||||
if (group.capacity !== null) {
|
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||||
const currentCount = await db.attendee.count({
|
where: {
|
||||||
where: { groupId: group.id, status: 'ACTIVE' },
|
|
||||||
});
|
|
||||||
|
|
||||||
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,
|
groupId: group.id,
|
||||||
fullName,
|
OR: [
|
||||||
phone,
|
{ phone },
|
||||||
email: payload.email?.trim() || null,
|
{ phone: payload.phone.trim() },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
if (existingPreRegistration?.status === 'REJECTED') {
|
||||||
|
await db.groupPreRegistration.update({
|
||||||
|
where: { id: existingPreRegistration.id },
|
||||||
|
data: { status: 'PENDING', fullName, email, reviewedAt: null },
|
||||||
|
});
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
status: 'waitlisted',
|
status: 'pre_registered',
|
||||||
message:
|
|
||||||
'El grupo está completo. Fuiste agregado a la lista de espera. Te contactaremos cuando haya un lugar disponible.',
|
|
||||||
attendee: null,
|
attendee: null,
|
||||||
|
message:
|
||||||
|
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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',
|
||||||
|
}),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const created = await db.attendee.create({
|
await db.groupPreRegistration.create({
|
||||||
data: {
|
data: {
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
fullName,
|
fullName,
|
||||||
phone,
|
phone,
|
||||||
email: payload.email?.trim() || null,
|
email,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
status: 'registered',
|
status: 'pre_registered',
|
||||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
attendee: null,
|
||||||
message: 'Inscripción realizada con éxito',
|
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(),
|
create: mock(),
|
||||||
count: mock(),
|
count: mock(),
|
||||||
},
|
},
|
||||||
groupWaitlistEntry: {
|
groupPreRegistration: {
|
||||||
findFirst: mock(),
|
findFirst: mock(),
|
||||||
create: mock(),
|
create: mock(),
|
||||||
|
update: mock(),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,18 +84,18 @@ describe('public invitations routes', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('POST /invitations/:token/join', () => {
|
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.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
prisma.attendee.create.mockResolvedValue({
|
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||||
id: 'att-1',
|
prisma.groupPreRegistration.create.mockResolvedValue({
|
||||||
|
id: 'pre-1',
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
email: 'lucia@test.com',
|
email: 'lucia@test.com',
|
||||||
phone: '+5491122334455',
|
phone: '+5491122334455',
|
||||||
guardianName: null,
|
status: 'PENDING',
|
||||||
guardianPhone: null,
|
reviewedAt: null,
|
||||||
notes: null,
|
|
||||||
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
|
||||||
} as never);
|
} as never);
|
||||||
@@ -112,9 +113,11 @@ describe('public invitations routes', () => {
|
|||||||
|
|
||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.message).toBe('Inscripción realizada con éxito');
|
expect(body.status).toBe('pre_registered');
|
||||||
expect(body.attendee.fullName).toBe('Lucía Méndez');
|
expect(body.attendee).toBeNull();
|
||||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
expect(body.message).toContain('solicitud de inscripción');
|
||||||
|
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||||
|
expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({
|
||||||
data: {
|
data: {
|
||||||
groupId: 'group-1',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
@@ -141,7 +144,7 @@ describe('public invitations routes', () => {
|
|||||||
expect(res.status).toBe(409);
|
expect(res.status).toBe(409);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.code).toBe('attendee_already_registered');
|
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 () => {
|
it('rejects invalid inputs (missing required name/phone)', async () => {
|
||||||
@@ -157,21 +160,67 @@ describe('public invitations routes', () => {
|
|||||||
expect(res.status).toBe(400);
|
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.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
prisma.attendee.count.mockResolvedValue(15); // capacity full
|
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
id: 'pre-1',
|
||||||
prisma.groupWaitlistEntry.create.mockResolvedValue({
|
status: 'PENDING',
|
||||||
id: 'wl-1',
|
} 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',
|
groupId: 'group-1',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
phone: '+5491122334455',
|
phone: '+5491122334455',
|
||||||
email: 'lucia@test.com',
|
status: 'REJECTED',
|
||||||
notes: null,
|
reviewedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||||
status: 'PENDING',
|
|
||||||
createdAt: new Date('2026-09-18T10: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);
|
} as never);
|
||||||
|
|
||||||
const res = await app.request('/invitations/valid-token-123/join', {
|
const res = await app.request('/invitations/valid-token-123/join', {
|
||||||
@@ -187,15 +236,15 @@ describe('public invitations routes', () => {
|
|||||||
|
|
||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.status).toBe('waitlisted');
|
expect(body.status).toBe('pre_registered');
|
||||||
expect(body.attendee).toBeNull();
|
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
where: { id: 'pre-1' },
|
||||||
data: {
|
data: {
|
||||||
groupId: 'group-1',
|
status: 'PENDING',
|
||||||
fullName: 'Lucía Méndez',
|
fullName: 'Lucía Méndez',
|
||||||
phone: '+5491122334455',
|
|
||||||
email: 'lucia@test.com',
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,16 +2,19 @@
|
|||||||
<html lang="es">
|
<html lang="es">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<!-- viewport-fit=cover habilita env(safe-area-inset-*) en iOS standalone. -->
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
<title>Gruperly</title>
|
<title>Gruperly</title>
|
||||||
|
<meta name="description" content="Gestión de cobros grupales" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180.png" />
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
<!-- iOS standalone: sin esto la app abre en un pestaña de Safari. -->
|
||||||
<link
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
rel="stylesheet"
|
<meta name="apple-mobile-web-app-title" content="Gruperly" />
|
||||||
/>
|
|
||||||
|
<meta name="theme-color" id="theme-color" content="#ffffff" />
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
try {
|
try {
|
||||||
@@ -19,7 +22,11 @@
|
|||||||
var isDark =
|
var isDark =
|
||||||
stored === 'dark' ||
|
stored === 'dark' ||
|
||||||
(stored !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
(stored !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||||
if (isDark) document.documentElement.classList.add('dark');
|
if (isDark) {
|
||||||
|
document.documentElement.classList.add('dark');
|
||||||
|
var meta = document.getElementById('theme-color');
|
||||||
|
if (meta) meta.setAttribute('content', '#020617');
|
||||||
|
}
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
70
apps/web/nginx.conf
Normal file
70
apps/web/nginx.conf
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# Nginx para el build de @gruperly/web.
|
||||||
|
# Sirve los assets estáticos y hace de proxy de /api hacia el servicio `api`.
|
||||||
|
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
|
||||||
|
# es first-party y el CORS del backend queda como red de seguridad.
|
||||||
|
|
||||||
|
# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive
|
||||||
|
# a un recreate del contenedor (que cambia la IP).
|
||||||
|
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
client_max_body_size 10m;
|
||||||
|
|
||||||
|
# ── API ────────────────────────────────────────────────────────────────────
|
||||||
|
location /api/ {
|
||||||
|
set $api http://api:4000;
|
||||||
|
proxy_pass $api$request_uri;
|
||||||
|
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $host;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
|
||||||
|
proxy_connect_timeout 10s;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Assets con hash en el nombre ───────────────────────────────────────────
|
||||||
|
# Solo `add_header`: `expires` agregaría un segundo Cache-Control.
|
||||||
|
location /assets/ {
|
||||||
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Service worker y manifest ─────────────────────────────────────────────
|
||||||
|
# Nunca se cachean: el navegador tiene que ver la versión nueva en el próximo
|
||||||
|
# load. `=404` y no el fallback del SPA, porque un 404 del SW debe ser un 404.
|
||||||
|
location = /manifest.webmanifest {
|
||||||
|
# `mime.types` de alpine no conoce `webmanifest` y lo sirve como
|
||||||
|
# octet-stream. Un `types` acá reemplaza el mapa heredado, pero esta location
|
||||||
|
# solo sirve un archivo, así que no puede romper nada más.
|
||||||
|
types { application/manifest+json webmanifest; }
|
||||||
|
default_type application/manifest+json;
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ~ ^/(sw\.js|workbox-[^/]+\.js)$ {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── SPA ────────────────────────────────────────────────────────────────────
|
||||||
|
location = /index.html {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,10 +7,13 @@
|
|||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit"
|
"icons": "bun run scripts/generate-icons.ts",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@better-auth/passkey": "^1.7.2",
|
"@better-auth/passkey": "^1.7.2",
|
||||||
|
"@fontsource-variable/inter": "^5.3.0",
|
||||||
"@gruperly/shared": "workspace:*",
|
"@gruperly/shared": "workspace:*",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@tanstack/react-query": "^5.62.0",
|
"@tanstack/react-query": "^5.62.0",
|
||||||
@@ -31,8 +34,11 @@
|
|||||||
"@types/react": "^19.0.0",
|
"@types/react": "^19.0.0",
|
||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
"@vitejs/plugin-react": "^4.3.0",
|
"@vitejs/plugin-react": "^4.3.0",
|
||||||
|
"sharp": "^0.35.4",
|
||||||
"tailwindcss": "^4.0.0",
|
"tailwindcss": "^4.0.0",
|
||||||
"typescript": "^5.7.0",
|
"typescript": "^5.7.0",
|
||||||
"vite": "^6.0.0"
|
"vite": "^6.0.0",
|
||||||
|
"vite-plugin-pwa": "^1.3.0",
|
||||||
|
"workbox-window": "^7.4.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
apps/web/public/apple-touch-icon-180.png
Normal file
BIN
apps/web/public/apple-touch-icon-180.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB |
BIN
apps/web/public/pwa-192x192.png
Normal file
BIN
apps/web/public/pwa-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
BIN
apps/web/public/pwa-512x512.png
Normal file
BIN
apps/web/public/pwa-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/public/pwa-maskable-512x512.png
Normal file
BIN
apps/web/public/pwa-maskable-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
66
apps/web/scripts/generate-icons.ts
Normal file
66
apps/web/scripts/generate-icons.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
/**
|
||||||
|
* Genera el set de iconos PWA desde el isotipo SVG de marca.
|
||||||
|
*
|
||||||
|
* Uso: bun --filter @gruperly/web icons
|
||||||
|
*
|
||||||
|
* Las salidas se versionan en `public/`; el build de Vite no las regenera
|
||||||
|
* (sharp es una devDependency y no debe entrar en la imagen de Docker).
|
||||||
|
* Re-correr solo cuando cambia `src/assets/brand/isotipo-y-organica.svg`.
|
||||||
|
*/
|
||||||
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||||
|
import { dirname, join } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
|
const webDir = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||||
|
const source = join(webDir, 'src/assets/brand/isotipo-y-organica.svg')
|
||||||
|
const publicDir = join(webDir, 'public')
|
||||||
|
|
||||||
|
/** Fondo del tema claro; también sirve de lienzo para los iconos opacos. */
|
||||||
|
const BACKGROUND = '#ffffff'
|
||||||
|
const TRANSPARENT = { r: 0, g: 0, b: 0, alpha: 0 } as const
|
||||||
|
|
||||||
|
type IconTarget = {
|
||||||
|
file: string
|
||||||
|
size: number
|
||||||
|
/** Rellena el lienzo con `BACKGROUND` en vez de dejar transparencia. */
|
||||||
|
opaque: boolean
|
||||||
|
/** Fracción del lado que ocupa el logo. 1 = sin padding. */
|
||||||
|
contentRatio: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets: IconTarget[] = [
|
||||||
|
{ file: 'pwa-192x192.png', size: 192, opaque: false, contentRatio: 0.9 },
|
||||||
|
{ file: 'pwa-512x512.png', size: 512, opaque: false, contentRatio: 0.9 },
|
||||||
|
// Android recorta los iconos adaptativos en círculo: el contenido útil
|
||||||
|
// vive en el 80% central del canvas, así que el logo va over white y escalado.
|
||||||
|
{ file: 'pwa-maskable-512x512.png', size: 512, opaque: true, contentRatio: 0.8 },
|
||||||
|
{ file: 'apple-touch-icon-180.png', size: 180, opaque: true, contentRatio: 0.82 },
|
||||||
|
]
|
||||||
|
|
||||||
|
// El viewBox del isotipo no arranca en 0 y deja aire alrededor del glifo:
|
||||||
|
// `trim` recorta ese margen para que el encuadre use el área real del dibujo.
|
||||||
|
const logo = await sharp(await readFile(source), { density: 512 })
|
||||||
|
.trim({ threshold: 1 })
|
||||||
|
.png()
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
await mkdir(publicDir, { recursive: true })
|
||||||
|
|
||||||
|
for (const { file, size, opaque, contentRatio } of targets) {
|
||||||
|
const box = Math.round(size * contentRatio)
|
||||||
|
const layer = await sharp(logo)
|
||||||
|
.resize(box, box, { fit: 'inside' })
|
||||||
|
.png()
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
const output = await sharp({
|
||||||
|
create: { width: size, height: size, channels: 4, background: opaque ? BACKGROUND : TRANSPARENT },
|
||||||
|
})
|
||||||
|
.composite([{ input: layer, gravity: 'center' }])
|
||||||
|
.png({ compressionLevel: 9 })
|
||||||
|
.toBuffer()
|
||||||
|
|
||||||
|
await writeFile(join(publicDir, file), output)
|
||||||
|
console.log(`${file.padEnd(28)} ${size}x${size} ${(output.byteLength / 1024).toFixed(1)} KB`)
|
||||||
|
}
|
||||||
@@ -1,29 +1,36 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function BottomNav() {
|
export function BottomNav() {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 backdrop-blur lg:hidden">
|
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
||||||
<div className="mx-auto grid max-w-md grid-cols-4">
|
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||||
const isActive = location.pathname === to
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={to}
|
key={to}
|
||||||
to={to}
|
to={to}
|
||||||
|
aria-current={isActive ? 'page' : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex flex-col items-center gap-0.5 py-2.5 text-[11px] font-medium transition-colors',
|
'flex min-h-14 flex-col items-center justify-center gap-1 py-2 text-[11px] font-medium transition-colors',
|
||||||
isActive ? 'text-accent-fg' : 'text-foreground/50 hover:text-primary',
|
isActive ? 'text-accent-fg' : 'text-foreground/80 hover:text-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon
|
{/* Pastilla suave detrás del ícono: el estado activo se lee por
|
||||||
className={cn('size-6', isActive && 'fill-accent/15 stroke-accent')}
|
color + fondo, no solo por el tono del texto. */}
|
||||||
strokeWidth={isActive ? 2.2 : 2}
|
<span
|
||||||
/>
|
className={cn(
|
||||||
{label}
|
'flex size-8 items-center justify-center rounded-lg transition-colors duration-150',
|
||||||
|
isActive && 'bg-accent-soft',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
||||||
|
</span>
|
||||||
|
<span className="leading-none">{label}</span>
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { Breadcrumb } from './Breadcrumb'
|
import { Breadcrumb } from './Breadcrumb'
|
||||||
import { ThemeToggle } from './ThemeToggle'
|
import { ThemeToggle } from './ThemeToggle'
|
||||||
@@ -8,9 +9,12 @@ export function Header() {
|
|||||||
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
||||||
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
|
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
|
||||||
<div className="flex min-w-0 items-center">
|
<div className="flex min-w-0 items-center">
|
||||||
<a href="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
{/* `Link` y no `<a>`: en mobile el logo es la única forma de volver al
|
||||||
|
inicio y un anchor recargaría el documento entero, perdiendo el
|
||||||
|
estado en memoria (cache de React Query, evento de instalación). */}
|
||||||
|
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||||
<Logo className="h-8" />
|
<Logo className="h-8" />
|
||||||
</a>
|
</Link>
|
||||||
<Breadcrumb />
|
<Breadcrumb />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-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,17 +1,39 @@
|
|||||||
|
import { useLocation } from '@tanstack/react-router'
|
||||||
import type { ReactNode } from 'react'
|
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 { Header } from './Header'
|
||||||
import { Sidebar } from './Sidebar'
|
import { Sidebar } from './Sidebar'
|
||||||
import { BottomNav } from './BottomNav'
|
import { BottomNav } from './BottomNav'
|
||||||
|
|
||||||
export function RootLayout({ children }: { children: ReactNode }) {
|
export function RootLayout({ children }: { children: ReactNode }) {
|
||||||
|
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh w-full">
|
<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">
|
<div className="mx-auto flex w-full max-w-7xl gap-6 lg:px-6">
|
||||||
<Sidebar />
|
<Sidebar immersive={immersive} />
|
||||||
|
|
||||||
<main className="min-w-0 flex-1 px-4 pb-24 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>
|
</div>
|
||||||
|
|
||||||
<BottomNav />
|
<BottomNav />
|
||||||
|
|||||||
@@ -1,29 +1,40 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
|
||||||
return (
|
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
|
||||||
<a href="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
|
// 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">
|
||||||
<Logo className="h-10" />
|
<Logo className="h-10" />
|
||||||
</a>
|
</Link>
|
||||||
|
|
||||||
<nav className="flex flex-col gap-1">
|
<nav className="flex flex-col gap-1">
|
||||||
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
{NAV_ITEMS.map(({ label, to, icon: Icon }) => {
|
||||||
const isActive = location.pathname === to
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={to}
|
key={to}
|
||||||
to={to}
|
to={to}
|
||||||
|
aria-current={isActive ? 'page' : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
|
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors',
|
||||||
isActive
|
isActive
|
||||||
? 'bg-accent-soft text-accent-fg'
|
? 'bg-accent-soft text-accent-fg'
|
||||||
: 'text-foreground/60 hover:bg-primary-soft hover:text-primary',
|
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
export { RootLayout } from './RootLayout'
|
export { RootLayout } from './RootLayout'
|
||||||
export { Header } from './Header'
|
export { Header } from './Header'
|
||||||
|
export { LargeTitle } from './LargeTitle'
|
||||||
export { ThemeToggle } from './ThemeToggle'
|
export { ThemeToggle } from './ThemeToggle'
|
||||||
export { PublicHeader } from './PublicHeader'
|
export { PublicHeader } from './PublicHeader'
|
||||||
export { PublicFooter } from './PublicFooter'
|
export { PublicFooter } from './PublicFooter'
|
||||||
|
|||||||
@@ -12,3 +12,12 @@ export const NAV_ITEMS: NavItem[] = [
|
|||||||
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
{ label: 'Cobros', to: '/payments', icon: Wallet },
|
||||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/** Una sección sigue activa dentro de sus subrutas: en `/groups/abc` el ítem
|
||||||
|
* activo es "Grupos", no ninguno. El prefijo se corta en el separador para
|
||||||
|
* que `/groupsomething` no se considere "/groups". La raíz es exacta: no hay
|
||||||
|
* subrutas del home que deban marcarla. */
|
||||||
|
export function isNavItemActive(pathname: string, to: string): boolean {
|
||||||
|
if (to === '/') return pathname === '/'
|
||||||
|
return pathname === to || pathname.startsWith(`${to}/`)
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(
|
|||||||
<span
|
<span
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
|
'inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-medium',
|
||||||
variants[variant],
|
variants[variant],
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -28,7 +28,10 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
type={type}
|
type={type}
|
||||||
className={cn(
|
className={cn(
|
||||||
'inline-flex items-center justify-center gap-2 rounded-xl font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
|
// `transition-*` explícito en vez de `transition-all`: solo se animan
|
||||||
|
// color, fondo, borde y transform. El feedback de presión se anula
|
||||||
|
// con `motion-reduce` para respetar prefers-reduced-motion.
|
||||||
|
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl font-medium transition-[color,background-color,border-color,fill,stroke,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50',
|
||||||
variants[variant],
|
variants[variant],
|
||||||
sizes[size],
|
sizes[size],
|
||||||
className,
|
className,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
export { Avatar, type AvatarProps } from './avatar'
|
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 { Badge, type BadgeProps, type BadgeVariant } from './badge'
|
||||||
|
export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button'
|
||||||
export { Input, type InputProps } from './input'
|
export { Input, type InputProps } from './input'
|
||||||
export { Label, type LabelProps } from './label'
|
export { Label, type LabelProps } from './label'
|
||||||
export { Modal, type ModalProps } from './modal'
|
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'
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
|
|||||||
<input
|
<input
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
|
// text-base (16px) en mobile: iOS auto-zoomea al enfocar controles con
|
||||||
|
// font-size < 16px y, al cerrar el teclado, no restaura el scale.
|
||||||
|
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base sm:text-sm text-primary placeholder:text-foreground/40 transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
|
invalid && 'border-danger focus:border-danger focus:ring-danger/30',
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
@@ -18,6 +18,10 @@ type ThemeContextValue = {
|
|||||||
|
|
||||||
const STORAGE_KEY = 'theme'
|
const STORAGE_KEY = 'theme'
|
||||||
|
|
||||||
|
/** Colores de la barra de estado en modo standalone. Debe matchear index.css. */
|
||||||
|
const THEME_COLOR = { light: '#ffffff', dark: '#020617' } as const
|
||||||
|
const THEME_COLOR_META_ID = 'theme-color'
|
||||||
|
|
||||||
function readStoredTheme(): Theme {
|
function readStoredTheme(): Theme {
|
||||||
const value = localStorage.getItem(STORAGE_KEY)
|
const value = localStorage.getItem(STORAGE_KEY)
|
||||||
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
||||||
@@ -41,9 +45,16 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const update = () => {
|
const update = () => {
|
||||||
document.documentElement.classList.toggle('dark', resolveDark(theme))
|
const dark = resolveDark(theme)
|
||||||
setIsDark(document.documentElement.classList.contains('dark'))
|
document.documentElement.classList.toggle('dark', dark)
|
||||||
|
setIsDark(dark)
|
||||||
localStorage.setItem(STORAGE_KEY, theme)
|
localStorage.setItem(STORAGE_KEY, theme)
|
||||||
|
|
||||||
|
// En standalone la barra de estado se pinta con theme-color; sin esto
|
||||||
|
// queda congelada en el valor que puso el script inline de index.html.
|
||||||
|
document
|
||||||
|
.getElementById(THEME_COLOR_META_ID)
|
||||||
|
?.setAttribute('content', dark ? THEME_COLOR.dark : THEME_COLOR.light)
|
||||||
}
|
}
|
||||||
update()
|
update()
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../components/layout/LargeTitle'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge, Button } from '../../components/ui'
|
||||||
import { useAttendance } from './AttendanceProvider'
|
import { useAttendance } from './AttendanceProvider'
|
||||||
import { StudentRow } from './StudentRow'
|
import { StudentRow } from './StudentRow'
|
||||||
@@ -16,15 +17,43 @@ export function ClassAttendanceView() {
|
|||||||
isSaving,
|
isSaving,
|
||||||
} = useAttendance()
|
} = useAttendance()
|
||||||
|
|
||||||
|
const total = sessionInfo?.students.length ?? 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
|
{/* El título grande va siempre, incluso mientras carga la sesión: es lo
|
||||||
|
que orienta y da altura de anclaje a la barra. El contador de
|
||||||
|
presentes, en cambio, solo aparece cuando ya hay alumnos en pantalla. */}
|
||||||
|
<LargeTitle
|
||||||
|
title={sessionInfo?.groupName ?? 'Asistencia'}
|
||||||
|
leading={
|
||||||
<Link
|
<Link
|
||||||
to="/"
|
to="/"
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
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" />
|
<ArrowLeft className="size-4" />
|
||||||
<span>Volver al inicio</span>
|
<span>Volver al inicio</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
}
|
||||||
|
barTrailing={
|
||||||
|
total > 0 ? (
|
||||||
|
<Badge variant="success" className="text-[11px] tabular-nums">
|
||||||
|
{presentCount}/{total}
|
||||||
|
</Badge>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{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 ? (
|
{studentsPending ? (
|
||||||
<div className="flex items-center justify-center py-16">
|
<div className="flex items-center justify-center py-16">
|
||||||
@@ -43,19 +72,7 @@ export function ClassAttendanceView() {
|
|||||||
|
|
||||||
{sessionInfo ? (
|
{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">
|
{total === 0 ? (
|
||||||
<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 ? (
|
|
||||||
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
<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="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
@@ -70,7 +87,7 @@ export function ClassAttendanceView() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{sessionInfo.students.length > 0 ? (
|
{total > 0 ? (
|
||||||
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
<div className="sticky bottom-20 z-30 mt-6 lg:bottom-6">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
|
||||||
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared'
|
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { CalendarClock, Users } from 'lucide-react'
|
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 { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { RISK_LABELS } from './constants'
|
import { RISK_HINT, RISK_LABELS } from './constants'
|
||||||
|
|
||||||
export function GroupCard({
|
export function GroupCard({
|
||||||
group,
|
group,
|
||||||
@@ -28,6 +28,9 @@ export function GroupCard({
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-end gap-1.5">
|
<div className="flex flex-col items-end gap-1.5">
|
||||||
{hasRisk ? (
|
{hasRisk ? (
|
||||||
|
// Mismo tooltip que en el detalle: el badge es corto y la
|
||||||
|
// explicación (abandono, no cobranza) la da el tooltip.
|
||||||
|
<Tooltip content={RISK_HINT} tooltipClassName="left-auto right-0">
|
||||||
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -38,6 +41,7 @@ export function GroupCard({
|
|||||||
/>
|
/>
|
||||||
{RISK_LABELS[riskLevel]}
|
{RISK_LABELS[riskLevel]}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
</Tooltip>
|
||||||
) : null}
|
) : null}
|
||||||
<Badge variant="success">Activo</Badge>
|
<Badge variant="success">Activo</Badge>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ export function GroupForm({
|
|||||||
<div>
|
<div>
|
||||||
<Label htmlFor="price">Precio</Label>
|
<Label htmlFor="price">Precio</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-foreground/50">
|
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
||||||
$
|
$
|
||||||
</span>
|
</span>
|
||||||
<Input
|
<Input
|
||||||
|
|||||||
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
83
apps/web/src/features/groups/add/AddAttendeePage.tsx
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||||
|
import { BulkImportPanel } from './BulkImportPanel'
|
||||||
|
import { CapacityModal } from './CapacityModal'
|
||||||
|
import { QuickAddForm } from './QuickAddForm'
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
{ value: 'quick' as const, label: 'Carga Rápida (Individual)' },
|
||||||
|
{ value: 'bulk' as const, label: 'Carga Masiva (CSV / Excel)' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function AddAttendeePage() {
|
||||||
|
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
||||||
|
useAddAttendee()
|
||||||
|
|
||||||
|
if (groupPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="mx-auto w-full max-w-2xl animate-fade-in space-y-5">
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver al grupo</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<header className="space-y-1">
|
||||||
|
<h1 className="text-2xl font-bold text-primary">Agregar miembros</h1>
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
{groupName ? (
|
||||||
|
<>
|
||||||
|
Sumá miembros a <span className="font-medium text-primary">{groupName}</span> de forma
|
||||||
|
individual o masiva desde una lista.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Sumá miembros de forma individual o masiva desde una lista.'
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
{capacity != null ? (
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
{attendeesTotal} de {capacity} lugares ocupados.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
|
||||||
|
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
||||||
|
{TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setActiveTab(tab.value)}
|
||||||
|
className={cn(
|
||||||
|
'flex-1 rounded-lg px-1 py-2 text-xs font-semibold transition-all',
|
||||||
|
activeTab === tab.value
|
||||||
|
? 'bg-surface text-primary shadow-xs'
|
||||||
|
: 'text-foreground/60 hover:text-primary',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CapacityModal />
|
||||||
|
<BulkCapacityModal />
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
302
apps/web/src/features/groups/add/AddAttendeeProvider.tsx
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
import { createContext, useContext, useMemo, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type {
|
||||||
|
CreateAttendee,
|
||||||
|
CreateAttendeeResult,
|
||||||
|
CreateGroupWaitlistEntry,
|
||||||
|
GroupWaitlistEntryDto,
|
||||||
|
GroupWaitlistList,
|
||||||
|
} from '@gruperly/shared'
|
||||||
|
import { useToast } from '../../../components/ui'
|
||||||
|
import {
|
||||||
|
addToGroupWaitlist,
|
||||||
|
ApiError,
|
||||||
|
bulkCreateAttendees,
|
||||||
|
createAttendee,
|
||||||
|
getGroup,
|
||||||
|
getGroupAttendees,
|
||||||
|
} from '../../../lib/api'
|
||||||
|
import type { ParsedContactRow } from '../../../lib/file-parser'
|
||||||
|
|
||||||
|
export type BulkAttendeeRow = {
|
||||||
|
firstName: string
|
||||||
|
lastName: string
|
||||||
|
fullName: string
|
||||||
|
phone: string
|
||||||
|
email?: string
|
||||||
|
notes?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AddAttendeeTab = 'quick' | 'bulk'
|
||||||
|
|
||||||
|
type AddAttendeeContextValue = {
|
||||||
|
groupId: string
|
||||||
|
groupName: string | undefined
|
||||||
|
groupPending: boolean
|
||||||
|
attendeesTotal: number
|
||||||
|
capacity: number | null
|
||||||
|
activeTab: AddAttendeeTab
|
||||||
|
setActiveTab: (value: AddAttendeeTab) => void
|
||||||
|
cancelAddAttendee: () => void
|
||||||
|
isCapacityModalOpen: boolean
|
||||||
|
capacityPayload: CreateAttendee | null
|
||||||
|
closeCapacityModal: () => void
|
||||||
|
isBulkCapacityModalOpen: boolean
|
||||||
|
closeBulkCapacityModal: () => void
|
||||||
|
parsedContacts: ParsedContactRow[]
|
||||||
|
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
||||||
|
removeParsedContact: (id: string) => void
|
||||||
|
fileName: string | null
|
||||||
|
setFileName: (name: string | null) => void
|
||||||
|
isParsingFile: boolean
|
||||||
|
setIsParsingFile: (value: boolean) => void
|
||||||
|
isDragging: boolean
|
||||||
|
setIsDragging: (value: boolean) => void
|
||||||
|
validRowsCount: number
|
||||||
|
invalidRowsCount: number
|
||||||
|
isSubmittingAttendee: boolean
|
||||||
|
isSubmittingForcedAttendee: boolean
|
||||||
|
isSubmittingWaitlistEntry: boolean
|
||||||
|
isSubmittingBulkImport: boolean
|
||||||
|
submitQuickAttendee: (payload: CreateAttendee) => void
|
||||||
|
submitForcedAttendee: () => void
|
||||||
|
submitWaitlistEntry: () => void
|
||||||
|
requestBulkImport: () => void
|
||||||
|
confirmBulkImportOverCapacity: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddAttendeeContext = createContext<AddAttendeeContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
||||||
|
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
||||||
|
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
||||||
|
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
||||||
|
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
||||||
|
const [fileName, setFileName] = useState<string | null>(null)
|
||||||
|
const [isParsingFile, setIsParsingFile] = useState(false)
|
||||||
|
const [isDragging, setIsDragging] = useState(false)
|
||||||
|
|
||||||
|
// Mismas query keys que el detalle del grupo: la data ya está en caché al navegar,
|
||||||
|
// así que la página se monta sin spinner ni fetch duplicado.
|
||||||
|
const groupQuery = useQuery({
|
||||||
|
queryKey: ['group', groupId],
|
||||||
|
queryFn: () => getGroup(groupId),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const attendeesQuery = useQuery({
|
||||||
|
queryKey: ['group-attendees', groupId],
|
||||||
|
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const group = groupQuery.data
|
||||||
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? 0
|
||||||
|
const capacity = group?.capacity ?? null
|
||||||
|
|
||||||
|
const goBackToGroup = () => {
|
||||||
|
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeCapacityFlow = () => {
|
||||||
|
setPendingCapacityPayload(null)
|
||||||
|
setIsCapacityModalOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidateGroupQueries = () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
||||||
|
if (result.outcome === 'created') {
|
||||||
|
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
||||||
|
} else {
|
||||||
|
toast.info(result.message)
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
goBackToGroup()
|
||||||
|
}
|
||||||
|
|
||||||
|
const createAttendeeMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
||||||
|
onMutate: (payload) => setPendingCapacityPayload(payload),
|
||||||
|
onSuccess: handleCreateSuccess,
|
||||||
|
onError: (err: Error) => {
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
||||||
|
setIsCapacityModalOpen(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
toast.error(err.message || 'Error al agregar miembro.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const createAttendeeForceMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
||||||
|
onSuccess: handleCreateSuccess,
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message || 'Error al agregar miembro.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const addToWaitlistMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
||||||
|
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
||||||
|
|
||||||
|
if (previousWaitlist) {
|
||||||
|
const optimisticEntry: GroupWaitlistEntryDto = {
|
||||||
|
id: `temp-${Date.now()}`,
|
||||||
|
groupId,
|
||||||
|
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
||||||
|
phone: payload.phone,
|
||||||
|
email: payload.email || null,
|
||||||
|
notes: payload.notes ?? null,
|
||||||
|
status: 'PENDING',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
||||||
|
data: [optimisticEntry, ...previousWaitlist.data],
|
||||||
|
pagination: {
|
||||||
|
...previousWaitlist.pagination,
|
||||||
|
total: previousWaitlist.pagination.total + 1,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return { previousWaitlist }
|
||||||
|
},
|
||||||
|
onSuccess: (entry) => {
|
||||||
|
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
||||||
|
invalidateGroupQueries()
|
||||||
|
goBackToGroup()
|
||||||
|
},
|
||||||
|
onError: (err: Error, _payload, context) => {
|
||||||
|
if (context?.previousWaitlist) {
|
||||||
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
||||||
|
}
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
||||||
|
toast.info('Este número ya está en la lista de espera del grupo.')
|
||||||
|
} else {
|
||||||
|
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
||||||
|
}
|
||||||
|
closeCapacityFlow()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const bulkImportMutation = useMutation({
|
||||||
|
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
||||||
|
onSuccess: (res) => {
|
||||||
|
toast.success(res.message)
|
||||||
|
setParsedContacts([])
|
||||||
|
setFileName(null)
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
goBackToGroup()
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message || 'Error al importar miembros.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const validRows: BulkAttendeeRow[] = useMemo(
|
||||||
|
() =>
|
||||||
|
parsedContacts
|
||||||
|
.filter((contact) => contact.isValid)
|
||||||
|
.map((contact) => ({
|
||||||
|
firstName: contact.firstName,
|
||||||
|
lastName: contact.lastName,
|
||||||
|
fullName: contact.fullName,
|
||||||
|
phone: contact.phone,
|
||||||
|
email: contact.email || undefined,
|
||||||
|
notes: contact.notes || undefined,
|
||||||
|
})),
|
||||||
|
[parsedContacts],
|
||||||
|
)
|
||||||
|
|
||||||
|
const runBulkImport = () => {
|
||||||
|
if (validRows.length === 0) {
|
||||||
|
toast.error('No hay miembros válidos para importar.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bulkImportMutation.mutate(validRows)
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestBulkImport = () => {
|
||||||
|
if (validRows.length === 0) {
|
||||||
|
toast.error('No hay miembros válidos para importar.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
||||||
|
setIsBulkCapacityModalOpen(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
runBulkImport()
|
||||||
|
}
|
||||||
|
|
||||||
|
const value: AddAttendeeContextValue = {
|
||||||
|
groupId,
|
||||||
|
groupName: group?.name,
|
||||||
|
groupPending: groupQuery.isPending,
|
||||||
|
attendeesTotal,
|
||||||
|
capacity,
|
||||||
|
activeTab,
|
||||||
|
setActiveTab,
|
||||||
|
cancelAddAttendee: goBackToGroup,
|
||||||
|
isCapacityModalOpen,
|
||||||
|
capacityPayload: pendingCapacityPayload,
|
||||||
|
closeCapacityModal: closeCapacityFlow,
|
||||||
|
isBulkCapacityModalOpen,
|
||||||
|
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
||||||
|
parsedContacts,
|
||||||
|
setParsedContacts,
|
||||||
|
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
||||||
|
fileName,
|
||||||
|
setFileName,
|
||||||
|
isParsingFile,
|
||||||
|
setIsParsingFile,
|
||||||
|
isDragging,
|
||||||
|
setIsDragging,
|
||||||
|
validRowsCount: validRows.length,
|
||||||
|
invalidRowsCount: parsedContacts.length - validRows.length,
|
||||||
|
isSubmittingAttendee: createAttendeeMutation.isPending,
|
||||||
|
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
||||||
|
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
||||||
|
isSubmittingBulkImport: bulkImportMutation.isPending,
|
||||||
|
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
||||||
|
submitForcedAttendee: () => {
|
||||||
|
if (pendingCapacityPayload) {
|
||||||
|
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
submitWaitlistEntry: () => {
|
||||||
|
if (pendingCapacityPayload) {
|
||||||
|
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
requestBulkImport,
|
||||||
|
confirmBulkImportOverCapacity: () => {
|
||||||
|
setIsBulkCapacityModalOpen(false)
|
||||||
|
runBulkImport()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AddAttendeeContext.Provider value={value}>{children}</AddAttendeeContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAddAttendee() {
|
||||||
|
const context = useContext(AddAttendeeContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAddAttendee debe usarse dentro de <AddAttendeeProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function BulkCapacityModal() {
|
export function BulkCapacityModal() {
|
||||||
const {
|
const {
|
||||||
@@ -9,8 +9,9 @@ export function BulkCapacityModal() {
|
|||||||
confirmBulkImportOverCapacity,
|
confirmBulkImportOverCapacity,
|
||||||
validRowsCount,
|
validRowsCount,
|
||||||
attendeesTotal,
|
attendeesTotal,
|
||||||
group,
|
groupName,
|
||||||
} = useGroupDetail()
|
capacity,
|
||||||
|
} = useAddAttendee()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
@@ -24,13 +25,17 @@ export function BulkCapacityModal() {
|
|||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
||||||
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
||||||
de <strong className="text-primary">{group?.capacity}</strong>. ¿Deseas importarlos de todos modos?
|
de <strong className="text-primary">{capacity}</strong>. ¿Deseas importarlos de todos modos?
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center justify-end gap-2.5 pt-2">
|
<div className="flex flex-col-reverse gap-2.5 pt-2 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeBulkCapacityModal}>
|
<Button variant="ghost" onClick={closeBulkCapacityModal} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" onClick={confirmBulkImportOverCapacity} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={confirmBulkImportOverCapacity}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
|
>
|
||||||
<Check className="size-4" />
|
<Check className="size-4" />
|
||||||
Importar de todos modos
|
Importar de todos modos
|
||||||
</Button>
|
</Button>
|
||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
parseXlsxContent,
|
parseXlsxContent,
|
||||||
} from '../../../lib/file-parser'
|
} from '../../../lib/file-parser'
|
||||||
import { cn } from '../../../lib/utils'
|
import { cn } from '../../../lib/utils'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function BulkImportPanel() {
|
export function BulkImportPanel() {
|
||||||
const {
|
const {
|
||||||
@@ -24,9 +24,9 @@ export function BulkImportPanel() {
|
|||||||
validRowsCount,
|
validRowsCount,
|
||||||
invalidRowsCount,
|
invalidRowsCount,
|
||||||
isSubmittingBulkImport,
|
isSubmittingBulkImport,
|
||||||
closeAddAttendeeModal,
|
cancelAddAttendee,
|
||||||
requestBulkImport,
|
requestBulkImport,
|
||||||
} = useGroupDetail()
|
} = useAddAttendee()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
@@ -115,12 +115,12 @@ export function BulkImportPanel() {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between px-1 text-xs">
|
<div className="flex flex-col items-start gap-1 px-1 text-xs sm:flex-row sm:items-center sm:justify-between">
|
||||||
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={downloadAttendeeTemplateCsv}
|
onClick={downloadAttendeeTemplateCsv}
|
||||||
className="inline-flex items-center gap-1 font-medium text-accent transition-colors hover:text-accent-strong"
|
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-accent transition-colors hover:text-accent-strong"
|
||||||
>
|
>
|
||||||
<Download className="size-3.5" />
|
<Download className="size-3.5" />
|
||||||
<span>Descargar plantilla CSV</span>
|
<span>Descargar plantilla CSV</span>
|
||||||
@@ -207,15 +207,15 @@ export function BulkImportPanel() {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-3">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeAddAttendeeModal}>
|
<Button variant="ghost" onClick={cancelAddAttendee} className="w-full sm:w-auto">
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={requestBulkImport}
|
onClick={requestBulkImport}
|
||||||
disabled={isSubmittingBulkImport || validRowsCount === 0}
|
disabled={isSubmittingBulkImport || validRowsCount === 0}
|
||||||
className="gap-2"
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
<span>Confirmar e Importar ({validRowsCount})</span>
|
<span>Confirmar e Importar ({validRowsCount})</span>
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function CapacityModal() {
|
export function CapacityModal() {
|
||||||
const {
|
const {
|
||||||
isCapacityModalOpen,
|
isCapacityModalOpen,
|
||||||
closeCapacityModal,
|
closeCapacityModal,
|
||||||
capacityPayload,
|
capacityPayload,
|
||||||
group,
|
groupName,
|
||||||
|
capacity,
|
||||||
submitForcedAttendee,
|
submitForcedAttendee,
|
||||||
submitWaitlistEntry,
|
submitWaitlistEntry,
|
||||||
isSubmittingForcedAttendee,
|
isSubmittingForcedAttendee,
|
||||||
isSubmittingWaitlistEntry,
|
isSubmittingWaitlistEntry,
|
||||||
} = useGroupDetail()
|
} = useAddAttendee()
|
||||||
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -26,15 +27,20 @@ export function CapacityModal() {
|
|||||||
{capacityPayload ? (
|
{capacityPayload ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
El grupo <strong className="text-primary">{group?.name}</strong> ya alcanzó su cupo de{' '}
|
El grupo <strong className="text-primary">{groupName}</strong> ya alcanzó su cupo de{' '}
|
||||||
<strong className="text-primary">{group?.capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
<strong className="text-primary">{capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
||||||
<strong className="text-primary">
|
<strong className="text-primary">
|
||||||
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
||||||
</strong>
|
</strong>
|
||||||
?
|
?
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col gap-2.5">
|
<div className="flex flex-col gap-2.5">
|
||||||
<Button variant="primary" onClick={submitForcedAttendee} disabled={isBusy} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={submitForcedAttendee}
|
||||||
|
disabled={isBusy}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
{isSubmittingForcedAttendee ? (
|
{isSubmittingForcedAttendee ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
@@ -42,7 +48,12 @@ export function CapacityModal() {
|
|||||||
)}
|
)}
|
||||||
<span>Agregar de todos modos</span>
|
<span>Agregar de todos modos</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={submitWaitlistEntry} disabled={isBusy} className="gap-2">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={submitWaitlistEntry}
|
||||||
|
disabled={isBusy}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
{isSubmittingWaitlistEntry ? (
|
{isSubmittingWaitlistEntry ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Check, Loader2 } from 'lucide-react'
|
import { Check, Loader2 } from 'lucide-react'
|
||||||
import { Button, Input, Label, useToast } from '../../../components/ui'
|
import { Button, Input, Label, useToast } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
export function QuickAddForm() {
|
export function QuickAddForm() {
|
||||||
const { submitQuickAttendee, isSubmittingAttendee, closeAddAttendeeModal } = useGroupDetail()
|
const { submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const [firstName, setFirstName] = useState('')
|
const [firstName, setFirstName] = useState('')
|
||||||
const [lastName, setLastName] = useState('')
|
const [lastName, setLastName] = useState('')
|
||||||
@@ -34,7 +34,6 @@ export function QuickAddForm() {
|
|||||||
setEmail('')
|
setEmail('')
|
||||||
setNotes('')
|
setNotes('')
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
@@ -104,17 +103,23 @@ export function QuickAddForm() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-3">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
resetForm()
|
resetForm()
|
||||||
closeAddAttendeeModal()
|
cancelAddAttendee()
|
||||||
}}
|
}}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" type="submit" disabled={isSubmittingAttendee} className="gap-2">
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
type="submit"
|
||||||
|
disabled={isSubmittingAttendee}
|
||||||
|
className="w-full sm:w-auto"
|
||||||
|
>
|
||||||
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
<span>Guardar Miembro</span>
|
<span>Guardar Miembro</span>
|
||||||
</Button>
|
</Button>
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { Link, useParams } from '@tanstack/react-router'
|
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 { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
||||||
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
import { Badge, Button, useToast } from '../../../components/ui'
|
import { Badge, Button, useToast } from '../../../components/ui'
|
||||||
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
||||||
import { KpiCard } from './KpiCard'
|
import { KpiCard } from './KpiCard'
|
||||||
@@ -77,19 +78,62 @@ export function AnalyticsView() {
|
|||||||
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupName = riskQuery.data?.groupName
|
// 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)
|
||||||
|
|
||||||
if (analyticsQuery.isPending || riskQuery.isPending) {
|
|
||||||
return (
|
return (
|
||||||
|
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
||||||
|
{/* El título grande va siempre, incluso cargando: es lo que da altura a
|
||||||
|
la barra y evita que el layout salte cuando llegan los datos. */}
|
||||||
|
<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>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{/* "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>
|
||||||
|
<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">
|
<div className="flex items-center justify-center py-20">
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
</div>
|
</div>
|
||||||
)
|
) : null}
|
||||||
}
|
|
||||||
|
|
||||||
if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) {
|
{hasFailed ? (
|
||||||
return (
|
<div className="mt-6 rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||||
<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>
|
<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>
|
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
||||||
<Button
|
<Button
|
||||||
@@ -103,35 +147,10 @@ export function AnalyticsView() {
|
|||||||
Reintentar
|
Reintentar
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
) : null}
|
||||||
}
|
|
||||||
|
|
||||||
const analytics = analyticsQuery.data
|
|
||||||
const atRisk = riskQuery.data?.data ?? []
|
|
||||||
|
|
||||||
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"
|
|
||||||
>
|
|
||||||
<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>
|
|
||||||
|
|
||||||
|
{showContent && analytics ? (
|
||||||
|
<>
|
||||||
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
<KpiCard
|
<KpiCard
|
||||||
icon={<Percent className="size-5" />}
|
icon={<Percent className="size-5" />}
|
||||||
@@ -195,6 +214,8 @@ export function AnalyticsView() {
|
|||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<AttendeeHistoryModal
|
<AttendeeHistoryModal
|
||||||
student={historyStudent}
|
student={historyStudent}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
import type { StudentAtRiskDto } from '@gruperly/shared'
|
||||||
import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react'
|
import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react'
|
||||||
import { Avatar, Badge, Button } from '../../../components/ui'
|
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
|
export type StatusAction = { student: StudentAtRiskDto; status: 'PAUSED' | 'DROPPED' } | null
|
||||||
|
|
||||||
@@ -32,8 +32,10 @@ export function AtRiskStudentCard({
|
|||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
{student.phone ?? 'Sin teléfono'} · {student.monthlyAttendanceRate}% de asistencia
|
{student.phone
|
||||||
mensual
|
? `${formatPhoneDisplay(student.phone)} · `
|
||||||
|
: 'Sin teléfono · '}
|
||||||
|
{student.monthlyAttendanceRate}% de asistencia mensual
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -4,3 +4,8 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
|
|||||||
HIGH: 'Riesgo alto',
|
HIGH: 'Riesgo alto',
|
||||||
MEDIUM: 'Riesgo moderado',
|
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.'
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { Modal } from '../../../components/ui'
|
|
||||||
import { cn } from '../../../lib/utils'
|
|
||||||
import { BulkImportPanel } from './BulkImportPanel'
|
|
||||||
import { QuickAddForm } from './QuickAddForm'
|
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
|
||||||
|
|
||||||
export function AddAttendeeModal() {
|
|
||||||
const { isAddAttendeeModalOpen, closeAddAttendeeModal, activeTab, setActiveTab } = useGroupDetail()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={isAddAttendeeModalOpen}
|
|
||||||
onClose={closeAddAttendeeModal}
|
|
||||||
title="Agregar Miembros al Grupo"
|
|
||||||
description="Agrega miembros rápidamente completando sus datos o importa una lista de contactos."
|
|
||||||
maxWidth="lg"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setActiveTab('quick')}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
activeTab === 'quick' ? 'bg-surface text-primary shadow-xs' : 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Carga Rápida (Individual)
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setActiveTab('bulk')}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
activeTab === 'bulk' ? 'bg-surface text-primary shadow-xs' : 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Carga Masiva (CSV / Excel)
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
UserMinus,
|
UserMinus,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
|
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { DetailRow } from './DetailRow'
|
import { DetailRow } from './DetailRow'
|
||||||
@@ -97,7 +98,7 @@ export function AttendeeDetailPage() {
|
|||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||||
{attendee.phone ? (
|
{attendee.phone ? (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-primary">{attendee.phone}</span>
|
<span className="text-primary">{formatPhoneDisplay(attendee.phone)}</span>
|
||||||
<a
|
<a
|
||||||
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
|
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
@@ -136,7 +137,7 @@ export function AttendeeDetailPage() {
|
|||||||
{attendee.guardianPhone ? (
|
{attendee.guardianPhone ? (
|
||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-primary">{attendee.guardianPhone}</span>
|
<span className="text-primary">{formatPhoneDisplay(attendee.guardianPhone)}</span>
|
||||||
<a
|
<a
|
||||||
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
|
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
|
|||||||
@@ -3,42 +3,28 @@ import type { ReactNode } from 'react'
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type {
|
import type {
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
CreateAttendee,
|
|
||||||
CreateAttendeeResult,
|
|
||||||
CreateGroupWaitlistEntry,
|
|
||||||
GroupDto,
|
GroupDto,
|
||||||
|
GroupPreRegistrationDto,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
GroupWaitlistList,
|
|
||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { useToast } from '../../../components/ui'
|
import { useToast } from '../../../components/ui'
|
||||||
import type { ParsedContactRow } from '../../../lib/file-parser'
|
|
||||||
import {
|
import {
|
||||||
addToGroupWaitlist,
|
|
||||||
ApiError,
|
ApiError,
|
||||||
bulkCreateAttendees,
|
approveGroupPreRegistration,
|
||||||
createAttendee,
|
|
||||||
getGroup,
|
getGroup,
|
||||||
getGroupAttendees,
|
getGroupAttendees,
|
||||||
|
getGroupPreRegistrations,
|
||||||
getGroupsRiskOverview,
|
getGroupsRiskOverview,
|
||||||
getGroupWaitlist,
|
getGroupWaitlist,
|
||||||
getInviteToken,
|
getInviteToken,
|
||||||
promoteGroupWaitlistEntry,
|
promoteGroupWaitlistEntry,
|
||||||
|
rejectGroupPreRegistration,
|
||||||
removeGroupWaitlistEntry,
|
removeGroupWaitlistEntry,
|
||||||
} from '../../../lib/api'
|
} from '../../../lib/api'
|
||||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||||
|
|
||||||
export type BulkAttendeeRow = {
|
export type ListSection = 'members' | 'pending'
|
||||||
firstName: string
|
|
||||||
lastName: string
|
|
||||||
fullName: string
|
|
||||||
phone: string
|
|
||||||
email?: string
|
|
||||||
notes?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ListSection = 'members' | 'waitlist'
|
|
||||||
export type AddAttendeeTab = 'quick' | 'bulk'
|
|
||||||
|
|
||||||
type GroupDetailContextValue = {
|
type GroupDetailContextValue = {
|
||||||
groupId: string
|
groupId: string
|
||||||
@@ -52,6 +38,9 @@ type GroupDetailContextValue = {
|
|||||||
waitlistTotal: number
|
waitlistTotal: number
|
||||||
waitlistPending: boolean
|
waitlistPending: boolean
|
||||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
|
preRegistrations: GroupPreRegistrationDto[]
|
||||||
|
preRegistrationsTotal: number
|
||||||
|
preRegistrationsPending: boolean
|
||||||
hasFreeCapacity: boolean
|
hasFreeCapacity: boolean
|
||||||
inviteUrl: string | undefined
|
inviteUrl: string | undefined
|
||||||
invitePending: boolean
|
invitePending: boolean
|
||||||
@@ -60,51 +49,27 @@ type GroupDetailContextValue = {
|
|||||||
setSearchFilter: (value: string) => void
|
setSearchFilter: (value: string) => void
|
||||||
listSection: ListSection
|
listSection: ListSection
|
||||||
setListSection: (value: ListSection) => void
|
setListSection: (value: ListSection) => void
|
||||||
activeTab: AddAttendeeTab
|
|
||||||
setActiveTab: (value: AddAttendeeTab) => void
|
|
||||||
isInviteModalOpen: boolean
|
isInviteModalOpen: boolean
|
||||||
openInviteModal: () => void
|
openInviteModal: () => void
|
||||||
closeInviteModal: () => void
|
closeInviteModal: () => void
|
||||||
isAddAttendeeModalOpen: boolean
|
|
||||||
openAddAttendeeModal: () => void
|
|
||||||
closeAddAttendeeModal: () => void
|
|
||||||
attendeeToRemove: AttendeeDto | null
|
attendeeToRemove: AttendeeDto | null
|
||||||
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
||||||
cancelRemoveAttendee: () => void
|
cancelRemoveAttendee: () => void
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
||||||
isCapacityModalOpen: boolean
|
selectedPreRegistration: GroupPreRegistrationDto | null
|
||||||
capacityPayload: CreateAttendee | null
|
setSelectedPreRegistration: (entry: GroupPreRegistrationDto | null) => void
|
||||||
closeCapacityModal: () => void
|
|
||||||
isBulkCapacityModalOpen: boolean
|
|
||||||
closeBulkCapacityModal: () => void
|
|
||||||
parsedContacts: ParsedContactRow[]
|
|
||||||
setParsedContacts: (contacts: ParsedContactRow[]) => void
|
|
||||||
removeParsedContact: (id: string) => void
|
|
||||||
fileName: string | null
|
|
||||||
setFileName: (name: string | null) => void
|
|
||||||
isParsingFile: boolean
|
|
||||||
setIsParsingFile: (value: boolean) => void
|
|
||||||
isDragging: boolean
|
|
||||||
setIsDragging: (value: boolean) => void
|
|
||||||
validRowsCount: number
|
|
||||||
invalidRowsCount: number
|
|
||||||
isSubmittingAttendee: boolean
|
|
||||||
isSubmittingForcedAttendee: boolean
|
|
||||||
isSubmittingWaitlistEntry: boolean
|
|
||||||
isSubmittingBulkImport: boolean
|
|
||||||
isSubmittingRemoval: boolean
|
isSubmittingRemoval: boolean
|
||||||
isSubmittingPromotion: boolean
|
isSubmittingPromotion: boolean
|
||||||
isSubmittingWaitlistRemoval: boolean
|
isSubmittingWaitlistRemoval: boolean
|
||||||
|
isSubmittingApproval: boolean
|
||||||
|
isSubmittingRejection: boolean
|
||||||
isRegeneratingInvite: boolean
|
isRegeneratingInvite: boolean
|
||||||
submitQuickAttendee: (payload: CreateAttendee) => void
|
|
||||||
submitForcedAttendee: () => void
|
|
||||||
submitWaitlistEntry: () => void
|
|
||||||
requestBulkImport: () => void
|
|
||||||
confirmBulkImportOverCapacity: () => void
|
|
||||||
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
||||||
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
||||||
|
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||||
|
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||||
regenerateInvite: () => void
|
regenerateInvite: () => void
|
||||||
copyInviteLink: () => Promise<void>
|
copyInviteLink: () => Promise<void>
|
||||||
copyWhatsappMessage: () => Promise<void>
|
copyWhatsappMessage: () => Promise<void>
|
||||||
@@ -118,19 +83,18 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
|
||||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||||
const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false)
|
const [listSection, setListSectionState] = useState<ListSection>('members')
|
||||||
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
|
||||||
const [listSection, setListSection] = useState<ListSection>('members')
|
|
||||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||||
const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false)
|
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||||
const [pendingCapacityPayload, setPendingCapacityPayload] = useState<CreateAttendee | null>(null)
|
|
||||||
const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false)
|
|
||||||
const [searchFilter, setSearchFilter] = useState('')
|
const [searchFilter, setSearchFilter] = useState('')
|
||||||
const [parsedContacts, setParsedContacts] = useState<ParsedContactRow[]>([])
|
|
||||||
const [fileName, setFileName] = useState<string | null>(null)
|
// La búsqueda pertenece a la vista que la abrió: al cambiar de pestaña se
|
||||||
const [isParsingFile, setIsParsingFile] = useState(false)
|
// limpia para no heredar un filtro sin coincidencias.
|
||||||
const [isDragging, setIsDragging] = useState(false)
|
const setListSection = (value: ListSection) => {
|
||||||
|
setListSectionState(value)
|
||||||
|
setSearchFilter('')
|
||||||
|
}
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
queryKey: ['group', groupId],
|
queryKey: ['group', groupId],
|
||||||
@@ -162,36 +126,33 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
enabled: Boolean(groupId),
|
enabled: Boolean(groupId),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const preRegistrationsQuery = useQuery({
|
||||||
|
queryKey: ['group-preregistrations', groupId],
|
||||||
|
queryFn: () => getGroupPreRegistrations(groupId, 1, 100),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
const group = groupQuery.data
|
const group = groupQuery.data
|
||||||
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
||||||
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
||||||
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
||||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
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 firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||||
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
||||||
|
|
||||||
const closeAddAttendeeFlow = () => {
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
setIsAddAttendeeModalOpen(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const invalidateGroupQueries = () => {
|
const invalidateGroupQueries = () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-preregistrations', groupId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
|
||||||
if (result.outcome === 'created') {
|
|
||||||
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
|
||||||
} else {
|
|
||||||
toast.info(result.message)
|
|
||||||
}
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
||||||
closeAddAttendeeFlow()
|
|
||||||
}
|
|
||||||
|
|
||||||
const regenerateTokenMutation = useMutation({
|
const regenerateTokenMutation = useMutation({
|
||||||
mutationFn: () => getInviteToken(groupId, true),
|
mutationFn: () => getInviteToken(groupId, true),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
@@ -203,89 +164,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const createAttendeeMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload),
|
|
||||||
onMutate: (payload) => setPendingCapacityPayload(payload),
|
|
||||||
onSuccess: handleCreateSuccess,
|
|
||||||
onError: (err: Error) => {
|
|
||||||
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
|
||||||
setIsCapacityModalOpen(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const createAttendeeForceMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
|
||||||
onSuccess: handleCreateSuccess,
|
|
||||||
onError: (err: Error) => {
|
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const addToWaitlistMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload),
|
|
||||||
onMutate: async (payload: CreateGroupWaitlistEntry) => {
|
|
||||||
await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] })
|
|
||||||
const previousWaitlist = queryClient.getQueryData<GroupWaitlistList>(['group-waitlist', groupId])
|
|
||||||
|
|
||||||
if (previousWaitlist) {
|
|
||||||
const optimisticEntry: GroupWaitlistEntryDto = {
|
|
||||||
id: `temp-${Date.now()}`,
|
|
||||||
groupId,
|
|
||||||
fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(),
|
|
||||||
phone: payload.phone,
|
|
||||||
email: payload.email || null,
|
|
||||||
notes: payload.notes ?? null,
|
|
||||||
status: 'PENDING',
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
updatedAt: new Date().toISOString(),
|
|
||||||
}
|
|
||||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], {
|
|
||||||
data: [optimisticEntry, ...previousWaitlist.data],
|
|
||||||
pagination: {
|
|
||||||
...previousWaitlist.pagination,
|
|
||||||
total: previousWaitlist.pagination.total + 1,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return { previousWaitlist }
|
|
||||||
},
|
|
||||||
onSuccess: (entry) => {
|
|
||||||
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
|
||||||
invalidateGroupQueries()
|
|
||||||
closeAddAttendeeFlow()
|
|
||||||
},
|
|
||||||
onError: (err: Error, _payload, context) => {
|
|
||||||
if (context?.previousWaitlist) {
|
|
||||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
|
||||||
}
|
|
||||||
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
|
||||||
toast.info('Este número ya está en la lista de espera del grupo.')
|
|
||||||
} else {
|
|
||||||
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
|
||||||
}
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const bulkImportMutation = useMutation({
|
|
||||||
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
|
||||||
onSuccess: (res) => {
|
|
||||||
toast.success(res.message)
|
|
||||||
setParsedContacts([])
|
|
||||||
setFileName(null)
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
||||||
setIsAddAttendeeModalOpen(false)
|
|
||||||
},
|
|
||||||
onError: (err: Error) => {
|
|
||||||
toast.error(err.message || 'Error al importar miembros.')
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const removeAttendeeMutation = useRemoveAttendee({
|
const removeAttendeeMutation = useRemoveAttendee({
|
||||||
groupId,
|
groupId,
|
||||||
onRemoved: () => setAttendeeToRemove(null),
|
onRemoved: () => setAttendeeToRemove(null),
|
||||||
@@ -317,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 inviteUrl = inviteTokenQuery.data?.inviteUrl
|
||||||
const whatsappMessage =
|
const whatsappMessage =
|
||||||
group && inviteUrl
|
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
|
const whatsappShareUrl = whatsappMessage
|
||||||
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
||||||
@@ -359,41 +283,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const validRows: BulkAttendeeRow[] = useMemo(
|
|
||||||
() =>
|
|
||||||
parsedContacts
|
|
||||||
.filter((contact) => contact.isValid)
|
|
||||||
.map((contact) => ({
|
|
||||||
firstName: contact.firstName,
|
|
||||||
lastName: contact.lastName,
|
|
||||||
fullName: contact.fullName,
|
|
||||||
phone: contact.phone,
|
|
||||||
email: contact.email || undefined,
|
|
||||||
notes: contact.notes || undefined,
|
|
||||||
})),
|
|
||||||
[parsedContacts],
|
|
||||||
)
|
|
||||||
|
|
||||||
const runBulkImport = () => {
|
|
||||||
if (validRows.length === 0) {
|
|
||||||
toast.error('No hay miembros válidos para importar.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
bulkImportMutation.mutate(validRows)
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestBulkImport = () => {
|
|
||||||
if (validRows.length === 0) {
|
|
||||||
toast.error('No hay miembros válidos para importar.')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (group?.capacity != null && attendeesTotal + validRows.length > group.capacity) {
|
|
||||||
setIsBulkCapacityModalOpen(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
runBulkImport()
|
|
||||||
}
|
|
||||||
|
|
||||||
const value: GroupDetailContextValue = {
|
const value: GroupDetailContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
group,
|
group,
|
||||||
@@ -406,6 +295,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
waitlistTotal,
|
waitlistTotal,
|
||||||
waitlistPending: waitlistQuery.isPending,
|
waitlistPending: waitlistQuery.isPending,
|
||||||
firstWaitlistEntry,
|
firstWaitlistEntry,
|
||||||
|
preRegistrations,
|
||||||
|
preRegistrationsTotal,
|
||||||
|
preRegistrationsPending: preRegistrationsQuery.isPending,
|
||||||
hasFreeCapacity,
|
hasFreeCapacity,
|
||||||
inviteUrl,
|
inviteUrl,
|
||||||
invitePending: inviteTokenQuery.isPending,
|
invitePending: inviteTokenQuery.isPending,
|
||||||
@@ -414,14 +306,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
setSearchFilter,
|
setSearchFilter,
|
||||||
listSection,
|
listSection,
|
||||||
setListSection,
|
setListSection,
|
||||||
activeTab,
|
|
||||||
setActiveTab,
|
|
||||||
isInviteModalOpen,
|
isInviteModalOpen,
|
||||||
openInviteModal: () => setIsInviteModalOpen(true),
|
openInviteModal: () => setIsInviteModalOpen(true),
|
||||||
closeInviteModal: () => setIsInviteModalOpen(false),
|
closeInviteModal: () => setIsInviteModalOpen(false),
|
||||||
isAddAttendeeModalOpen,
|
|
||||||
openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true),
|
|
||||||
closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false),
|
|
||||||
attendeeToRemove,
|
attendeeToRemove,
|
||||||
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
||||||
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
||||||
@@ -431,49 +318,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
selectedWaitlistEntry,
|
selectedWaitlistEntry,
|
||||||
setSelectedWaitlistEntry,
|
setSelectedWaitlistEntry,
|
||||||
isCapacityModalOpen,
|
selectedPreRegistration,
|
||||||
capacityPayload: pendingCapacityPayload,
|
setSelectedPreRegistration,
|
||||||
closeCapacityModal: () => {
|
|
||||||
setPendingCapacityPayload(null)
|
|
||||||
setIsCapacityModalOpen(false)
|
|
||||||
},
|
|
||||||
isBulkCapacityModalOpen,
|
|
||||||
closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false),
|
|
||||||
parsedContacts,
|
|
||||||
setParsedContacts,
|
|
||||||
removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)),
|
|
||||||
fileName,
|
|
||||||
setFileName,
|
|
||||||
isParsingFile,
|
|
||||||
setIsParsingFile,
|
|
||||||
isDragging,
|
|
||||||
setIsDragging,
|
|
||||||
validRowsCount: validRows.length,
|
|
||||||
invalidRowsCount: parsedContacts.length - validRows.length,
|
|
||||||
isSubmittingAttendee: createAttendeeMutation.isPending,
|
|
||||||
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
|
||||||
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
|
||||||
isSubmittingBulkImport: bulkImportMutation.isPending,
|
|
||||||
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
||||||
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
||||||
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
||||||
|
isSubmittingApproval: approvePreRegistrationMutation.isPending,
|
||||||
|
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
|
||||||
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
||||||
submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload),
|
|
||||||
submitForcedAttendee: () => {
|
|
||||||
if (pendingCapacityPayload) {
|
|
||||||
createAttendeeForceMutation.mutate({ ...pendingCapacityPayload })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
submitWaitlistEntry: () => {
|
|
||||||
if (pendingCapacityPayload) {
|
|
||||||
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
requestBulkImport,
|
|
||||||
confirmBulkImportOverCapacity: () => {
|
|
||||||
setIsBulkCapacityModalOpen(false)
|
|
||||||
runBulkImport()
|
|
||||||
},
|
|
||||||
promoteEntry: (entry) => {
|
promoteEntry: (entry) => {
|
||||||
setSelectedWaitlistEntry(null)
|
setSelectedWaitlistEntry(null)
|
||||||
promoteWaitlistMutation.mutate(entry.id)
|
promoteWaitlistMutation.mutate(entry.id)
|
||||||
@@ -482,6 +334,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
setSelectedWaitlistEntry(null)
|
setSelectedWaitlistEntry(null)
|
||||||
removeWaitlistEntryMutation.mutate(entry)
|
removeWaitlistEntryMutation.mutate(entry)
|
||||||
},
|
},
|
||||||
|
approvePreRegistration: (entry) => {
|
||||||
|
approvePreRegistrationMutation.mutate(entry)
|
||||||
|
},
|
||||||
|
rejectPreRegistration: (entry) => {
|
||||||
|
rejectPreRegistrationMutation.mutate(entry)
|
||||||
|
},
|
||||||
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
||||||
copyInviteLink,
|
copyInviteLink,
|
||||||
copyWhatsappMessage,
|
copyWhatsappMessage,
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
import { AddAttendeeModal } from './AddAttendeeModal'
|
|
||||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
|
||||||
import { CapacityModal } from './CapacityModal'
|
|
||||||
import { GroupHeader } from './GroupHeader'
|
import { GroupHeader } from './GroupHeader'
|
||||||
import { GroupInfoCard } from './GroupInfoCard'
|
import { GroupInfoCard } from './GroupInfoCard'
|
||||||
import { InviteLinkModal } from './InviteLinkModal'
|
import { InviteLinkModal } from './InviteLinkModal'
|
||||||
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
||||||
|
import { PreRegistrationDetailModal } from './PreRegistrationDetailModal'
|
||||||
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
||||||
@@ -46,15 +44,12 @@ export function GroupDetailView() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="animate-fade-in space-y-6">
|
<section className="animate-fade-in space-y-5 sm:space-y-6">
|
||||||
<GroupHeader />
|
<GroupHeader />
|
||||||
<GroupInfoCard />
|
<GroupInfoCard />
|
||||||
<MembersWaitlistSection />
|
<MembersWaitlistSection />
|
||||||
|
|
||||||
<InviteLinkModal />
|
<InviteLinkModal />
|
||||||
<AddAttendeeModal />
|
|
||||||
<CapacityModal />
|
|
||||||
<BulkCapacityModal />
|
|
||||||
<RemoveAttendeeModal
|
<RemoveAttendeeModal
|
||||||
attendee={attendeeToRemove}
|
attendee={attendeeToRemove}
|
||||||
groupName={group?.name}
|
groupName={group?.name}
|
||||||
@@ -66,6 +61,7 @@ export function GroupDetailView() {
|
|||||||
onConfirm={confirmRemoveAttendee}
|
onConfirm={confirmRemoveAttendee}
|
||||||
/>
|
/>
|
||||||
<WaitlistEntryDetailModal />
|
<WaitlistEntryDetailModal />
|
||||||
|
<PreRegistrationDetailModal />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,76 +1,123 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
||||||
import { Badge, Button } from '../../../components/ui'
|
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||||
import { RISK_LABELS } from '../constants'
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
|
import { RISK_HINT, RISK_LABELS } from '../constants'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
export function GroupHeader() {
|
export function GroupHeader() {
|
||||||
const { group, groupId, riskLevel, openInviteModal, openAddAttendeeModal } = useGroupDetail()
|
const {
|
||||||
|
group,
|
||||||
|
groupId,
|
||||||
|
riskLevel,
|
||||||
|
openInviteModal,
|
||||||
|
attendeesTotal,
|
||||||
|
attendeesPending,
|
||||||
|
preRegistrationsTotal,
|
||||||
|
preRegistrationsPending,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending,
|
||||||
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM'
|
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 (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
<LargeTitle
|
||||||
|
title={group?.name ?? ''}
|
||||||
|
leading={
|
||||||
<Link
|
<Link
|
||||||
to="/groups"
|
to="/groups"
|
||||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
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" />
|
<ArrowLeft className="size-4" />
|
||||||
<span>Volver a grupos</span>
|
<span>Volver a grupos</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
}
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
>
|
||||||
<div>
|
{/* Los estados cuelgan del título y no de la barra: en la barra
|
||||||
<div className="flex items-center gap-2.5">
|
colapsada solo va el nombre, que es lo que se usa para orientarse. */}
|
||||||
<h1 className="text-2xl font-bold text-primary">{group?.name}</h1>
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||||
<Badge variant="success">Activo</Badge>
|
<Badge variant="success" className="gap-1.5 text-[11px]">
|
||||||
|
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
|
||||||
|
Activo
|
||||||
|
</Badge>
|
||||||
{hasRisk ? (
|
{hasRisk ? (
|
||||||
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
|
// 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
|
<span
|
||||||
className={`size-2 rounded-full ${riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning'}`}
|
className={cn(
|
||||||
|
'size-1.5 rounded-full',
|
||||||
|
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
|
||||||
|
)}
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
{RISK_LABELS[riskLevel]}
|
{RISK_LABELS[riskLevel]}
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
</Tooltip>
|
||||||
</div>
|
|
||||||
{group?.description ? (
|
|
||||||
<p className="mt-1 text-sm text-foreground/70">{group.description}</p>
|
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid w-full grid-cols-3 gap-2 sm:flex sm:w-auto sm:flex-wrap sm:items-center sm:gap-2.5">
|
{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
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() =>
|
onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })}
|
||||||
void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })
|
className={cn(
|
||||||
}
|
'h-11 w-full justify-center border-border sm:w-auto',
|
||||||
className="w-full justify-center gap-1.5 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" />
|
<BarChart3 className="size-4 text-accent" />
|
||||||
<span>Estadísticas</span>
|
<span>Estadísticas</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
{!isEmptyGroup ? (
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={openInviteModal}
|
onClick={openInviteModal}
|
||||||
className="w-full justify-center gap-1.5 border-border sm:w-auto"
|
className="h-11 w-full justify-center border-border sm:w-auto"
|
||||||
>
|
>
|
||||||
<Share2 className="size-4 text-accent" />
|
<Share2 className="size-4 text-accent" />
|
||||||
<span>
|
<span>
|
||||||
Compartir <span className="hidden sm:inline">Link</span>
|
Compartir <span className="hidden sm:inline">Link</span>
|
||||||
</span>
|
</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
) : null}
|
||||||
variant="primary"
|
|
||||||
onClick={openAddAttendeeModal}
|
|
||||||
className="w-full justify-center gap-1.5 sm:w-auto"
|
|
||||||
>
|
|
||||||
<UserPlus className="size-4" />
|
|
||||||
<span>
|
|
||||||
Agregar <span className="hidden sm:inline">Miembros</span>
|
|
||||||
</span>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,45 +1,104 @@
|
|||||||
import { CalendarClock, Users } from 'lucide-react'
|
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'
|
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() {
|
export function GroupInfoCard() {
|
||||||
const { group, attendees, waitlistTotal } = useGroupDetail()
|
const { group, attendeesTotal, attendeesPending, waitlistTotal } = useGroupDetail()
|
||||||
if (!group) return null
|
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 (
|
return (
|
||||||
<div className="grid grid-cols-1 gap-4 rounded-xl border border-border bg-surface p-4 text-sm md:grid-cols-3">
|
<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="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:pr-6')}>
|
||||||
<CalendarClock className="size-5 shrink-0 text-accent" />
|
<CalendarClock className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Horario</p>
|
<p className={LABEL_CLASS}>Horario</p>
|
||||||
<p className="font-medium text-primary">
|
<p className="mt-0.5 text-base font-semibold leading-snug text-primary">
|
||||||
{(group.days?.length ?? 0) > 0
|
{daysLabel || 'Sin horario definido'}
|
||||||
? formatSchedule(group.days ?? [], group.time)
|
|
||||||
: 'Sin horario definido'}
|
|
||||||
</p>
|
</p>
|
||||||
|
{daysLabel && group.time ? (
|
||||||
|
<p className="mt-0.5 text-sm tabular-nums text-foreground">{group.time}</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:px-6')}>
|
||||||
<Users className="size-5 shrink-0 text-accent" />
|
<Users className="mt-0.5 size-5 shrink-0 text-accent" />
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Miembros & Cupo</p>
|
<p className={LABEL_CLASS}>Miembros & Cupo</p>
|
||||||
<p className="font-medium text-primary">
|
<p className="mt-0.5 flex items-baseline text-2xl font-semibold leading-none tracking-tight tabular-nums text-primary">
|
||||||
{attendees.length} inscritos {waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''}
|
<span>{attendeesPending ? '—' : attendeesTotal}</span>
|
||||||
{group.capacity ? ` · Cupo de ${group.capacity}` : ''}
|
{capacity ? (
|
||||||
|
<span className="text-base font-medium text-foreground/70">/{capacity}</span>
|
||||||
|
) : null}
|
||||||
</p>
|
</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>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className={cn(CELL_CLASS, 'md:pl-6')}>
|
||||||
<div className="flex size-5 shrink-0 items-center justify-center font-bold text-accent">$</div>
|
<div className="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent">
|
||||||
<div>
|
$
|
||||||
<p className="text-xs font-medium uppercase text-foreground/50">Cobro</p>
|
</div>
|
||||||
<p className="font-medium 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.price != null ? formatPrice(group.price) : 'Sin precio'}
|
||||||
{group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}
|
|
||||||
{group.dueDay ? ` · Vence día ${group.dueDay}` : ''}
|
|
||||||
</p>
|
</p>
|
||||||
|
{billingMeta && group.price != null ? (
|
||||||
|
<p className="mt-0.5 text-sm text-foreground">{billingMeta}</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ export function InviteLinkModal() {
|
|||||||
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
||||||
<strong>{group?.name}</strong>.
|
<strong>{group?.name}</strong>.
|
||||||
{'\n\n'}
|
{'\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'}
|
{'\n'}
|
||||||
<span className="break-all text-accent underline">{inviteUrl}</span>
|
<span className="break-all text-accent underline">{inviteUrl}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { AttendeeDto } from '@gruperly/shared'
|
import type { AttendeeDto } from '@gruperly/shared'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { ChevronRight } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
||||||
@@ -12,40 +13,62 @@ export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="overflow-x-auto">
|
<table className="w-full table-fixed text-left text-sm">
|
||||||
<table className="w-full text-left text-sm">
|
<thead>
|
||||||
<thead className="border-b border-border text-xs font-semibold uppercase text-foreground/60">
|
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||||
<tr>
|
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
|
||||||
<th className="px-3 pb-3">Nombre</th>
|
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
|
||||||
<th className="px-3 pb-3">Teléfono</th>
|
<th scope="col" className="w-8 px-1 pb-1.5">
|
||||||
<th className="w-8 px-3 pb-3" />
|
<span className="sr-only">Detalle</span>
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-border">
|
<tbody>
|
||||||
{attendees.map((attendee) => (
|
{attendees.map((attendee) => (
|
||||||
<tr
|
<tr
|
||||||
key={attendee.id}
|
key={attendee.id}
|
||||||
className="cursor-pointer transition-colors hover:bg-primary-soft/50"
|
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)}
|
onClick={() => openAttendee(attendee.id)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault()
|
||||||
|
openAttendee(attendee.id)
|
||||||
|
}
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<td className="px-3 py-3">
|
<td className="px-2 py-2">
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<div className="flex size-8 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
|
<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()}
|
{attendee.fullName.charAt(0).toUpperCase()}
|
||||||
</div>
|
</div>
|
||||||
<span className="font-medium text-primary">{attendee.fullName}</span>
|
{/* `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-semibold text-primary"
|
||||||
|
title={attendee.fullName}
|
||||||
|
>
|
||||||
|
{attendee.fullName}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-3 text-foreground/70">
|
{/* El nombre manda; el teléfono es un dato secundario: un nivel
|
||||||
{attendee.phone || <span className="text-foreground/40">—</span>}
|
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}>
|
||||||
|
{formatPhoneDisplay(attendee.phone)}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-foreground/60">—</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-1 py-3 text-foreground/30">
|
<td className="w-8 px-1 py-2 text-foreground/50">
|
||||||
<ChevronRight className="size-4" />
|
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
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,146 +1,46 @@
|
|||||||
import { Clock, Loader2, Plus, Search, Share2, Users } from 'lucide-react'
|
import { Search } from 'lucide-react'
|
||||||
import { Button, Input } from '../../../components/ui'
|
import { Input } from '../../../components/ui'
|
||||||
import { cn } from '../../../lib/utils'
|
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
import { MembersTable } from './MembersTable'
|
import { MembersView } from './MembersView'
|
||||||
import { WaitlistTable } from './WaitlistTable'
|
import { PendingView } from './PendingView'
|
||||||
|
import { SectionChips } from './SectionChips'
|
||||||
|
|
||||||
export function MembersWaitlistSection() {
|
export function MembersWaitlistSection() {
|
||||||
const {
|
const { listSection, searchFilter, setSearchFilter } = useGroupDetail()
|
||||||
attendees,
|
|
||||||
attendeesTotal,
|
|
||||||
attendeesPending,
|
|
||||||
waitlistEntries,
|
|
||||||
waitlistTotal,
|
|
||||||
waitlistPending,
|
|
||||||
listSection,
|
|
||||||
setListSection,
|
|
||||||
searchFilter,
|
|
||||||
setSearchFilter,
|
|
||||||
openInviteModal,
|
|
||||||
openAddAttendeeModal,
|
|
||||||
} = useGroupDetail()
|
|
||||||
|
|
||||||
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)),
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4 rounded-xl border border-border bg-surface p-5">
|
// Radios concéntricos: `rounded-2xl` (16px) con `p-2` (8px) deja a las
|
||||||
<div className="flex flex-col gap-3">
|
// superficies interiores un radio de 16 - 8 = 8px, o sea `rounded-lg`.
|
||||||
<div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
|
// Sin bordes: el lavado `bg-primary-soft` separa la sección del fondo.
|
||||||
<div className="flex w-full items-center rounded-xl bg-primary-soft p-1 sm:w-[26rem]">
|
<div className="rounded-2xl bg-primary-soft p-2">
|
||||||
<button
|
<div className="space-y-2 p-2 sm:p-3">
|
||||||
type="button"
|
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
|
||||||
onClick={() => setListSection('members')}
|
<SectionChips />
|
||||||
className={cn(
|
|
||||||
'flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
listSection === 'members'
|
|
||||||
? 'bg-surface text-primary shadow-xs'
|
|
||||||
: 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Users className="size-4 shrink-0" />
|
|
||||||
<span className="whitespace-nowrap">Miembros ({attendeesTotal})</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setListSection('waitlist')}
|
|
||||||
className={cn(
|
|
||||||
'flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 text-xs font-semibold transition-all',
|
|
||||||
listSection === 'waitlist'
|
|
||||||
? 'bg-surface text-primary shadow-xs'
|
|
||||||
: 'text-foreground/60 hover:text-primary',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Clock className="size-4 shrink-0" />
|
|
||||||
<span className="whitespace-nowrap">Lista de espera ({waitlistTotal})</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{listSection === 'members' ? (
|
<div className="relative w-full sm:w-72 lg:shrink-0">
|
||||||
<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" />
|
||||||
<Search className="absolute left-3 top-2.5 size-4 text-foreground/40" />
|
|
||||||
<Input
|
<Input
|
||||||
placeholder="Buscar por nombre o teléfono..."
|
placeholder="Buscar por nombre o teléfono..."
|
||||||
value={searchFilter}
|
value={searchFilter}
|
||||||
onChange={(e) => setSearchFilter(e.target.value)}
|
onChange={(e) => setSearchFilter(e.target.value)}
|
||||||
className="h-9 pl-9 text-xs"
|
aria-label="Buscar en el listado"
|
||||||
|
className="h-11 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="text-xs text-foreground/60">
|
{/* 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'
|
{listSection === 'members'
|
||||||
? 'Listado de todos los miembros incorporados al grupo.'
|
? '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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{listSection === 'members' ? (
|
<div className="rounded-lg bg-surface p-1 shadow-xs sm:p-2">
|
||||||
<>
|
{listSection === 'members' ? <MembersView /> : <PendingView />}
|
||||||
{attendeesPending ? (
|
|
||||||
<div className="flex items-center justify-center py-12">
|
|
||||||
<Loader2 className="size-6 animate-spin text-accent" />
|
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
|
||||||
|
|
||||||
{!attendeesPending && attendees.length === 0 ? (
|
|
||||||
<div className="rounded-xl border border-dashed border-border px-4 py-12 text-center">
|
|
||||||
<Users className="mx-auto mb-2 size-10 text-foreground/30" />
|
|
||||||
<p className="font-medium text-primary">Todavía no hay miembros en este grupo</p>
|
|
||||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/60">
|
|
||||||
Puedes compartir el enlace de invitación único o agregar miembros de forma manual o
|
|
||||||
masiva.
|
|
||||||
</p>
|
|
||||||
<div className="mt-4 flex items-center justify-center gap-3">
|
|
||||||
<Button variant="outline" size="sm" onClick={openInviteModal} className="gap-2">
|
|
||||||
<Share2 className="size-4" />
|
|
||||||
Compartir Enlace
|
|
||||||
</Button>
|
|
||||||
<Button variant="primary" size="sm" onClick={openAddAttendeeModal} className="gap-2">
|
|
||||||
<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/60">
|
|
||||||
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-xl border border-dashed border-border px-4 py-12 text-center">
|
|
||||||
<Clock className="mx-auto mb-2 size-10 text-foreground/30" />
|
|
||||||
<p className="font-medium text-primary">No hay nadie en la lista de espera</p>
|
|
||||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/60">
|
|
||||||
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>
|
|
||||||
)}
|
|
||||||
</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 type { AttendeeDto, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react'
|
import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
|
|
||||||
type RemoveAttendeeModalProps = {
|
type RemoveAttendeeModalProps = {
|
||||||
attendee: AttendeeDto | null
|
attendee: AttendeeDto | null
|
||||||
@@ -37,7 +38,9 @@ export function RemoveAttendeeModal({
|
|||||||
<strong className="text-primary">{groupName}</strong>
|
<strong className="text-primary">{groupName}</strong>
|
||||||
{firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'}
|
{firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'}
|
||||||
{attendee.phone ? (
|
{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}
|
) : null}
|
||||||
</p>
|
</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 { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
import { DetailRow } from './DetailRow'
|
import { DetailRow } from './DetailRow'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
@@ -44,7 +45,7 @@ export function WaitlistEntryDetailModal() {
|
|||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||||
{selectedWaitlistEntry.phone ? (
|
{selectedWaitlistEntry.phone ? (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-primary">{selectedWaitlistEntry.phone}</span>
|
<span className="text-primary">{formatPhoneDisplay(selectedWaitlistEntry.phone)}</span>
|
||||||
<a
|
<a
|
||||||
href={`https://wa.me/${selectedWaitlistEntry.phone.replace(/\D/g, '')}`}
|
href={`https://wa.me/${selectedWaitlistEntry.phone.replace(/\D/g, '')}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
|
|||||||
@@ -1,48 +1,68 @@
|
|||||||
import type { GroupWaitlistEntryDto } from '@gruperly/shared'
|
import type { GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
import { ChevronRight } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
|
import { formatPhoneDisplay } from '../../../lib/format'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) {
|
export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) {
|
||||||
const { setSelectedWaitlistEntry } = useGroupDetail()
|
const { setSelectedWaitlistEntry } = useGroupDetail()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="overflow-x-auto">
|
<table className="w-full table-fixed text-left text-sm">
|
||||||
<table className="w-full text-left text-sm">
|
<thead>
|
||||||
<thead className="border-b border-border text-xs font-semibold uppercase text-foreground/60">
|
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||||
<tr>
|
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
|
||||||
<th className="px-3 pb-3">Nombre</th>
|
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
|
||||||
<th className="px-3 pb-3">Teléfono</th>
|
<th scope="col" className="w-8 px-1 pb-1.5">
|
||||||
<th className="w-8 px-3 pb-3" />
|
<span className="sr-only">Detalle</span>
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-border">
|
<tbody>
|
||||||
{entries.map((entry) => (
|
{entries.map((entry) => (
|
||||||
<tr
|
<tr
|
||||||
key={entry.id}
|
key={entry.id}
|
||||||
className="cursor-pointer transition-colors hover:bg-primary-soft/50"
|
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)}
|
onClick={() => setSelectedWaitlistEntry(entry)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault()
|
||||||
|
setSelectedWaitlistEntry(entry)
|
||||||
|
}
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<td className="px-3 py-3">
|
<td className="px-2 py-2">
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<div className="flex size-8 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
|
<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()}
|
{entry.fullName.charAt(0).toUpperCase()}
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate font-medium text-primary">{entry.fullName}</p>
|
<p className="truncate font-semibold text-primary" title={entry.fullName}>
|
||||||
|
{entry.fullName}
|
||||||
|
</p>
|
||||||
{entry.notes ? (
|
{entry.notes ? (
|
||||||
<p className="truncate text-xs text-foreground/50">{entry.notes}</p>
|
<p className="truncate text-xs text-foreground/70" title={entry.notes}>
|
||||||
|
{entry.notes}
|
||||||
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-3 text-foreground/70">{entry.phone}</td>
|
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70">
|
||||||
<td className="px-1 py-3 text-foreground/30">
|
{entry.phone ? (
|
||||||
<ChevronRight className="size-4" />
|
<span className="block truncate tabular-nums" title={entry.phone}>
|
||||||
|
{formatPhoneDisplay(entry.phone)}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-foreground/60">—</span>
|
||||||
|
)}
|
||||||
|
</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>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -43,6 +43,11 @@ export function GroupInviteSummary() {
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,7 @@ export function JoinForm() {
|
|||||||
className="w-full gap-2 py-2.5 text-sm font-semibold"
|
className="w-full gap-2 py-2.5 text-sm font-semibold"
|
||||||
>
|
>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
<span>Completar Inscripción</span>
|
<span>Enviar Solicitud</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -4,11 +4,6 @@ import { useMutation, useQuery } from '@tanstack/react-query'
|
|||||||
import type { GroupInviteInfoDto } from '@gruperly/shared'
|
import type { GroupInviteInfoDto } from '@gruperly/shared'
|
||||||
import { ApiError, getInviteInfo, joinViaInvite } from '../../lib/api'
|
import { ApiError, getInviteInfo, joinViaInvite } from '../../lib/api'
|
||||||
|
|
||||||
type RegisteredAttendee = {
|
|
||||||
fullName: string
|
|
||||||
phone: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
type JoinGroupContextValue = {
|
type JoinGroupContextValue = {
|
||||||
token: string
|
token: string
|
||||||
group: GroupInviteInfoDto | undefined
|
group: GroupInviteInfoDto | undefined
|
||||||
@@ -23,8 +18,7 @@ type JoinGroupContextValue = {
|
|||||||
email: string
|
email: string
|
||||||
setEmail: (value: string) => void
|
setEmail: (value: string) => void
|
||||||
errorMessage: string | null
|
errorMessage: string | null
|
||||||
registeredAttendee: RegisteredAttendee | null
|
preRegistrationMessage: string | null
|
||||||
waitlistMessage: string | null
|
|
||||||
submit: () => void
|
submit: () => void
|
||||||
isSubmitting: boolean
|
isSubmitting: boolean
|
||||||
}
|
}
|
||||||
@@ -37,8 +31,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
|||||||
const [phone, setPhone] = useState('')
|
const [phone, setPhone] = useState('')
|
||||||
const [email, setEmail] = useState('')
|
const [email, setEmail] = useState('')
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||||
const [registeredAttendee, setRegisteredAttendee] = useState<RegisteredAttendee | null>(null)
|
const [preRegistrationMessage, setPreRegistrationMessage] = useState<string | null>(null)
|
||||||
const [waitlistMessage, setWaitlistMessage] = useState<string | null>(null)
|
|
||||||
|
|
||||||
const inviteQuery = useQuery({
|
const inviteQuery = useQuery({
|
||||||
queryKey: ['public-invite', token],
|
queryKey: ['public-invite', token],
|
||||||
@@ -57,16 +50,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
|||||||
}),
|
}),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
setErrorMessage(null)
|
setErrorMessage(null)
|
||||||
if (data.status === 'waitlisted') {
|
setPreRegistrationMessage(data.message)
|
||||||
setRegisteredAttendee(null)
|
|
||||||
setWaitlistMessage(data.message)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setWaitlistMessage(null)
|
|
||||||
setRegisteredAttendee({
|
|
||||||
fullName: data.attendee?.fullName ?? `${firstName.trim()} ${lastName.trim()}`.trim(),
|
|
||||||
phone: data.attendee?.phone ?? null,
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
onError: (error: unknown) => {
|
onError: (error: unknown) => {
|
||||||
if (error instanceof ApiError) {
|
if (error instanceof ApiError) {
|
||||||
@@ -76,6 +60,16 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
|||||||
)
|
)
|
||||||
return
|
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.')
|
setErrorMessage(error.message || 'Error al procesar la inscripción.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -110,8 +104,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
|||||||
email,
|
email,
|
||||||
setEmail,
|
setEmail,
|
||||||
errorMessage,
|
errorMessage,
|
||||||
registeredAttendee,
|
preRegistrationMessage,
|
||||||
waitlistMessage,
|
|
||||||
submit,
|
submit,
|
||||||
isSubmitting: joinMutation.isPending,
|
isSubmitting: joinMutation.isPending,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,11 @@ import { PublicFooter, PublicHeader } from '../../components/layout'
|
|||||||
import { GroupInviteSummary } from './GroupInviteSummary'
|
import { GroupInviteSummary } from './GroupInviteSummary'
|
||||||
import { InvalidInviteCard } from './InvalidInviteCard'
|
import { InvalidInviteCard } from './InvalidInviteCard'
|
||||||
import { JoinForm } from './JoinForm'
|
import { JoinForm } from './JoinForm'
|
||||||
import { JoinSuccessCard } from './JoinSuccessCard'
|
|
||||||
import { useJoinGroup } from './JoinGroupProvider'
|
import { useJoinGroup } from './JoinGroupProvider'
|
||||||
import { WaitlistNoticeCard } from './WaitlistNoticeCard'
|
import { PreRegistrationNoticeCard } from './PreRegistrationNoticeCard'
|
||||||
|
|
||||||
export function JoinGroupView() {
|
export function JoinGroupView() {
|
||||||
const { group, invitePending, inviteFailed, registeredAttendee, waitlistMessage } = useJoinGroup()
|
const { group, invitePending, inviteFailed, preRegistrationMessage } = useJoinGroup()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
|
<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}
|
{inviteFailed || (!group && !invitePending) ? <InvalidInviteCard /> : null}
|
||||||
|
|
||||||
{registeredAttendee ? <JoinSuccessCard /> : null}
|
{preRegistrationMessage ? <PreRegistrationNoticeCard /> : null}
|
||||||
{waitlistMessage ? <WaitlistNoticeCard /> : 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">
|
<div className="space-y-6 rounded-2xl border border-border bg-surface p-6 shadow-xl sm:p-8">
|
||||||
<GroupInviteSummary />
|
<GroupInviteSummary />
|
||||||
<JoinForm />
|
<JoinForm />
|
||||||
|
|||||||
@@ -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 { Badge } from '../../components/ui'
|
||||||
import { useJoinGroup } from './JoinGroupProvider'
|
import { useJoinGroup } from './JoinGroupProvider'
|
||||||
|
|
||||||
export function WaitlistNoticeCard() {
|
export function PreRegistrationNoticeCard() {
|
||||||
const { group, waitlistMessage } = useJoinGroup()
|
const { group, preRegistrationMessage } = useJoinGroup()
|
||||||
if (!group || !waitlistMessage) return null
|
if (!group || !preRegistrationMessage) return null
|
||||||
|
|
||||||
return (
|
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">
|
<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,15 +14,16 @@ export function WaitlistNoticeCard() {
|
|||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Badge variant="neutral" className="mb-2">
|
<Badge variant="neutral" className="mb-2">
|
||||||
Lista de Espera
|
Pre-inscripción
|
||||||
</Badge>
|
</Badge>
|
||||||
<h1 className="text-2xl font-bold text-primary">Cupo completo</h1>
|
<h1 className="text-2xl font-bold text-primary">Solicitud enviada</h1>
|
||||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{waitlistMessage}</p>
|
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{preRegistrationMessage}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="text-xs text-foreground/60">
|
<p className="text-xs text-foreground/60">
|
||||||
El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '}
|
El profesor revisará tu solicitud para el grupo{' '}
|
||||||
<strong className="font-semibold text-primary">{group.name}</strong>.
|
<strong className="font-semibold text-primary">{group.name}</strong> y se pondrá en contacto
|
||||||
|
contigo por WhatsApp para confirmarte el lugar.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
44
apps/web/src/features/pwa/InstallBanner.tsx
Normal file
44
apps/web/src/features/pwa/InstallBanner.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { Download, X } from 'lucide-react'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
|
||||||
|
type InstallBannerProps = {
|
||||||
|
onInstall: () => void
|
||||||
|
onDismiss: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InstallBanner({ onInstall, onDismiss }: InstallBannerProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-x-0 z-30 px-4 lg:left-auto lg:right-6 lg:w-96 lg:px-0
|
||||||
|
// Encima de BottomNav en móvil; abajo a la derecha en desktop.
|
||||||
|
bottom-[calc(4.5rem+env(safe-area-inset-bottom))] lg:bottom-6"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface p-4 shadow-lg">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-semibold text-primary">Instalá Gruperly</p>
|
||||||
|
<p className="mt-0.5 text-xs leading-relaxed text-foreground/70">
|
||||||
|
Abrila directo desde tu pantalla de inicio, sin barra de navegador.
|
||||||
|
</p>
|
||||||
|
<div className="mt-3 flex items-center gap-2">
|
||||||
|
<Button variant="primary" size="sm" onClick={onInstall}>
|
||||||
|
<Download className="size-4" strokeWidth={2} />
|
||||||
|
Instalar app
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" onClick={onDismiss}>
|
||||||
|
Ahora no
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onDismiss}
|
||||||
|
aria-label="Cerrar aviso de instalación"
|
||||||
|
className="shrink-0 rounded-lg p-1 text-foreground/40 transition-colors hover:bg-primary-soft hover:text-foreground"
|
||||||
|
>
|
||||||
|
<X className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
16
apps/web/src/features/pwa/InstallPrompt.tsx
Normal file
16
apps/web/src/features/pwa/InstallPrompt.tsx
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { usePwa } from './PwaProvider'
|
||||||
|
import { InstallBanner } from './InstallBanner'
|
||||||
|
import { IosInstallHint } from './IosInstallHint'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Presenta el aviso de instalación. Cuándo mostrarse lo decide `PwaProvider`
|
||||||
|
* (sesión iniciada + dwell cumplido); acá solo se dibuja lo que corresponda.
|
||||||
|
*/
|
||||||
|
export function InstallPrompt() {
|
||||||
|
const { canPrompt, canShowIosHint, promptInstall, dismiss } = usePwa()
|
||||||
|
|
||||||
|
if (canPrompt) return <InstallBanner onInstall={promptInstall} onDismiss={dismiss} />
|
||||||
|
if (canShowIosHint) return <IosInstallHint onDismiss={dismiss} />
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
41
apps/web/src/features/pwa/IosInstallHint.tsx
Normal file
41
apps/web/src/features/pwa/IosInstallHint.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { Share, X } from 'lucide-react'
|
||||||
|
|
||||||
|
type IosInstallHintProps = {
|
||||||
|
onDismiss: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safari en iOS no expone `beforeinstallprompt`: no hay forma de disparar la
|
||||||
|
* instalación desde la web, hay que instruir al usuario. Solo informa, sin
|
||||||
|
* botón de acción.
|
||||||
|
*/
|
||||||
|
export function IosInstallHint({ onDismiss }: IosInstallHintProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-x-0 z-30 px-4 lg:left-auto lg:right-6 lg:w-96 lg:px-0
|
||||||
|
bottom-[calc(4.5rem+env(safe-area-inset-bottom))] lg:bottom-6"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface p-4 shadow-lg">
|
||||||
|
<Share className="mt-0.5 size-5 shrink-0 text-accent" strokeWidth={2} />
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-semibold text-primary">Instalá Gruperly en el iPhone</p>
|
||||||
|
<p className="mt-0.5 text-xs leading-relaxed text-foreground/70">
|
||||||
|
Tocá <span className="font-medium text-foreground">Compartir</span> y elegí{' '}
|
||||||
|
<span className="font-medium text-foreground">Agregar a pantalla de inicio</span> para
|
||||||
|
abrirla como app.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onDismiss}
|
||||||
|
aria-label="Cerrar aviso de instalación"
|
||||||
|
className="shrink-0 rounded-lg p-1 text-foreground/40 transition-colors hover:bg-primary-soft hover:text-foreground"
|
||||||
|
>
|
||||||
|
<X className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
199
apps/web/src/features/pwa/PwaProvider.tsx
Normal file
199
apps/web/src/features/pwa/PwaProvider.tsx
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
type ReactNode,
|
||||||
|
} from 'react'
|
||||||
|
import { registerSW } from 'virtual:pwa-register'
|
||||||
|
import { router } from '../../router'
|
||||||
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
|
import { useToast } from '../../components/ui'
|
||||||
|
import { InstallPrompt } from './InstallPrompt'
|
||||||
|
|
||||||
|
/** `beforeinstallprompt` todavía no está en lib.dom (Chromium >= 108). */
|
||||||
|
type BeforeInstallPromptEvent = Event & {
|
||||||
|
prompt: () => Promise<void>
|
||||||
|
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
|
||||||
|
}
|
||||||
|
|
||||||
|
type PwaContextValue = {
|
||||||
|
/** El navegador ofreció instalar y el usuario todavía no lo decidió. */
|
||||||
|
canPrompt: boolean
|
||||||
|
/** Safari en iOS: no hay `prompt()`, hay que instruir al usuario. */
|
||||||
|
canShowIosHint: boolean
|
||||||
|
promptInstall: () => Promise<void>
|
||||||
|
dismiss: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const PwaContext = createContext<PwaContextValue | null>(null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El descarte es definitivo: una vez que el usuario dice "ahora no" no se vuelve
|
||||||
|
* a preguntar. Comparte clave con la pista de iOS porque el motivo es el mismo.
|
||||||
|
*/
|
||||||
|
const DISMISSED_KEY = 'pwa-install-dismissed'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cuánto hay que quedarse en la misma ruta antes de ofrecer instalar. El evento
|
||||||
|
* `beforeinstallprompt` llega a los segundos, así que sin este margen el banner
|
||||||
|
* cae en medio de la primera tarea de la visita.
|
||||||
|
*/
|
||||||
|
const DWELL_MS = 20_000
|
||||||
|
|
||||||
|
/** iOS Safari no dispara `beforeinstallprompt`: se chequea el modo standalone. */
|
||||||
|
function isStandalone() {
|
||||||
|
return (
|
||||||
|
window.matchMedia('(display-mode: standalone)').matches ||
|
||||||
|
(navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* iOS real, Safari real. Excluye Chrome/Firefox/Edge/Opera en iOS: usan WebKit
|
||||||
|
* pero también los instala desde Safari, así que la instrucción de compartir
|
||||||
|
* no aplica. El iPad de iPadOS 13+ se reporta como MacIntel con touch points.
|
||||||
|
*/
|
||||||
|
function detectIos() {
|
||||||
|
if (isStandalone()) return false
|
||||||
|
|
||||||
|
const ua = navigator.userAgent
|
||||||
|
const isIosDevice =
|
||||||
|
/iPad|iPhone|iPod/.test(ua) ||
|
||||||
|
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
|
||||||
|
if (!isIosDevice) return false
|
||||||
|
|
||||||
|
return !/CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo|YaBrowser/.test(ua)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El registro se hace desde el provider y no con `injectRegister: 'auto'` para
|
||||||
|
* poder avisar cuando el shell quedó cacheado. El flag es de módulo porque
|
||||||
|
* StrictMode monta dos veces en dev y `onOfflineReady` dispararía dos toasts.
|
||||||
|
* No se limpia en el unmount: StrictMode lo resetea en el mismo ciclo de montaje
|
||||||
|
* y volvería a registrar. Con HMR el módulo se re-evalua y arranca en false.
|
||||||
|
*/
|
||||||
|
let registered = false
|
||||||
|
|
||||||
|
export function PwaProvider({ children }: { children: ReactNode }) {
|
||||||
|
const { user } = useAuth()
|
||||||
|
const { success, info } = useToast()
|
||||||
|
const [installEvent, setInstallEvent] = useState<BeforeInstallPromptEvent | null>(null)
|
||||||
|
const [dismissed, setDismissed] = useState(() => localStorage.getItem(DISMISSED_KEY) === '1')
|
||||||
|
const [isInstalled, setIsInstalled] = useState(isStandalone)
|
||||||
|
const [isIos] = useState(detectIos)
|
||||||
|
const [pathname, setPathname] = useState(() => router.state.location.pathname)
|
||||||
|
const [settled, setSettled] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (registered) return
|
||||||
|
registered = true
|
||||||
|
registerSW({
|
||||||
|
immediate: true,
|
||||||
|
onOfflineReady() {
|
||||||
|
success('La app quedó lista para abrirse sin conexión', 'Ya podés usar Gruperly offline.')
|
||||||
|
},
|
||||||
|
onRegisterError(error) {
|
||||||
|
console.error('No se pudo registrar el service worker', error)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}, [success])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onBeforeInstallPrompt = (event: Event) => {
|
||||||
|
// Sin preventDefault el navegador muestra su propio mini-infobar.
|
||||||
|
event.preventDefault()
|
||||||
|
setInstallEvent(event as BeforeInstallPromptEvent)
|
||||||
|
}
|
||||||
|
const onInstalled = () => {
|
||||||
|
setIsInstalled(true)
|
||||||
|
setInstallEvent(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||||
|
window.addEventListener('appinstalled', onInstalled)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||||
|
window.removeEventListener('appinstalled', onInstalled)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// `PwaProvider` monta fuera del `RouterProvider`, así que no puede usar
|
||||||
|
// `useRouterState`: se suscribe al singleton. Conviene tener la ruta acá y no
|
||||||
|
// en el componente que muestra el banner, porque `AppLayoutGuard` desmonta
|
||||||
|
// `RootLayout` cada vez que su query de onboarding vuelve a `pending` y un
|
||||||
|
// timer de dwell en el hijo se perdería en cada navegación.
|
||||||
|
useEffect(
|
||||||
|
() => router.subscribe('onResolved', ({ toLocation }) => setPathname(toLocation.pathname)),
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Durante el alta inicial no se ofrece instalar: la persona todavía no
|
||||||
|
// conoce la app. El timer ni siquiera corre, así que al salir arranca de cero
|
||||||
|
// en la primera pantalla real.
|
||||||
|
const inOnboarding = pathname.startsWith('/onboarding')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Navegar antes de que se cumpla el tiempo reinicia la cuenta: tampoco
|
||||||
|
// estamos pidiendo instalar a alguien que está peleando con la app. Una
|
||||||
|
// vez cumplido queda armed y no se oculta más al navegar.
|
||||||
|
if (settled || inOnboarding) return
|
||||||
|
const timer = setTimeout(() => setSettled(true), DWELL_MS)
|
||||||
|
return () => clearTimeout(timer)
|
||||||
|
}, [pathname, settled, inOnboarding])
|
||||||
|
|
||||||
|
const promptInstall = useCallback(async () => {
|
||||||
|
if (!installEvent) return
|
||||||
|
await installEvent.prompt()
|
||||||
|
const { outcome } = await installEvent.userChoice
|
||||||
|
setInstallEvent(null)
|
||||||
|
if (outcome === 'accepted') {
|
||||||
|
localStorage.setItem(DISMISSED_KEY, '1')
|
||||||
|
setDismissed(true)
|
||||||
|
success('App instalada', 'Ahora tenés Gruperly en tu pantalla de inicio.')
|
||||||
|
}
|
||||||
|
}, [installEvent, success])
|
||||||
|
|
||||||
|
const dismiss = useCallback(() => {
|
||||||
|
setDismissed(true)
|
||||||
|
localStorage.setItem(DISMISSED_KEY, '1')
|
||||||
|
info('Podés instalarla más adelante desde el menú del navegador.')
|
||||||
|
}, [info])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sin sesión no hay nada que instalar todavía: la primera vez que alguien
|
||||||
|
* conoce la app es instalándola, no pidiéndole que la instale.
|
||||||
|
*
|
||||||
|
* OJO: `_authenticated` NO es un guard de sesión. `AppLayoutGuard` renderiza
|
||||||
|
* `RootLayout` aunque no haya usuario, así que el gate se chequea acá y no
|
||||||
|
* se puede inferir de dónde se monte el prompt.
|
||||||
|
*/
|
||||||
|
const eligible = !!user && settled && !dismissed && !isInstalled && !inOnboarding
|
||||||
|
|
||||||
|
const value = useMemo<PwaContextValue>(
|
||||||
|
() => ({
|
||||||
|
canPrompt: eligible && installEvent !== null,
|
||||||
|
canShowIosHint: eligible && isIos,
|
||||||
|
promptInstall,
|
||||||
|
dismiss,
|
||||||
|
}),
|
||||||
|
[eligible, installEvent, isIos, promptInstall, dismiss],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PwaContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
<InstallPrompt />
|
||||||
|
</PwaContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePwa() {
|
||||||
|
const context = useContext(PwaContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('usePwa debe usarse dentro de <PwaProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
4
apps/web/src/features/pwa/index.ts
Normal file
4
apps/web/src/features/pwa/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export { PwaProvider, usePwa } from './PwaProvider'
|
||||||
|
export { InstallPrompt } from './InstallPrompt'
|
||||||
|
export { InstallBanner } from './InstallBanner'
|
||||||
|
export { IosInstallHint } from './IosInstallHint'
|
||||||
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,27 @@
|
|||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Inter variable auto-hospedada. Declaramos solo latin y latin-ext a mano en
|
||||||
|
lugar de importar el wght.css de @fontsource: ese trae los 7 subsets y el
|
||||||
|
service worker precachea todo lo emitido, casi 1 MB que nunca se descarga.
|
||||||
|
El archivo .woff2 sí viene del paquete, con hash y cache immutable. */
|
||||||
|
@font-face {
|
||||||
|
font-family: "Inter Variable";
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
font-weight: 100 900;
|
||||||
|
src: url("@fontsource-variable/inter/files/inter-latin-wght-normal.woff2") format("woff2-variations");
|
||||||
|
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: "Inter Variable";
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
font-weight: 100 900;
|
||||||
|
src: url("@fontsource-variable/inter/files/inter-latin-ext-wght-normal.woff2") format("woff2-variations");
|
||||||
|
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||||
|
}
|
||||||
|
|
||||||
@custom-variant dark (&:where(.dark, .dark *));
|
@custom-variant dark (&:where(.dark, .dark *));
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
@@ -45,7 +67,8 @@
|
|||||||
--radius-xl: 0.75rem;
|
--radius-xl: 0.75rem;
|
||||||
|
|
||||||
/* Tipografía (igual que la landing) */
|
/* Tipografía (igual que la landing) */
|
||||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
/* @fontsource-variable/inter registra la familia como "Inter Variable" */
|
||||||
|
--font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
|
||||||
|
|
||||||
/* Animaciones */
|
/* Animaciones */
|
||||||
--animate-fade-in: fade-in 0.2s ease-out;
|
--animate-fade-in: fade-in 0.2s ease-out;
|
||||||
@@ -141,4 +164,20 @@
|
|||||||
@apply bg-background text-primary antialiased transition-colors;
|
@apply bg-background text-primary antialiased transition-colors;
|
||||||
min-height: 100dvh;
|
min-height: 100dvh;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* iOS (Safari y standalone) hace auto-zoom al enfocar un control de
|
||||||
|
formulario con font-size < 16px, y al cerrar el teclado no restaura el
|
||||||
|
scale: la app queda con zoom. El `Input` ya sube a 16px en mobile
|
||||||
|
(`text-base sm:text-sm`); esto es la red de seguridad para textareas,
|
||||||
|
selects o inputs crudos que se agreguen más adelante.
|
||||||
|
El 639px calza con el breakpoint `sm` de Tailwind. El `!important` es
|
||||||
|
a propósito: sin él, una clase `text-sm` en un input futuro ganaría por
|
||||||
|
especificidad y reintroduciría el bug sin avisar. */
|
||||||
|
@media (max-width: 639px) {
|
||||||
|
input,
|
||||||
|
textarea,
|
||||||
|
select {
|
||||||
|
font-size: 16px !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import type {
|
import type {
|
||||||
AbsenceDetails,
|
AbsenceDetails,
|
||||||
|
ApproveGroupPreRegistrationResult,
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
AttendeeHistory,
|
AttendeeHistory,
|
||||||
AttendeeList,
|
AttendeeList,
|
||||||
@@ -20,6 +21,7 @@ import type {
|
|||||||
GroupDto,
|
GroupDto,
|
||||||
GroupInviteInfoDto,
|
GroupInviteInfoDto,
|
||||||
GroupList,
|
GroupList,
|
||||||
|
GroupPreRegistrationList,
|
||||||
GroupRiskSummary,
|
GroupRiskSummary,
|
||||||
GroupsRiskOverview,
|
GroupsRiskOverview,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
@@ -36,6 +38,7 @@ import type {
|
|||||||
ProblemDetails,
|
ProblemDetails,
|
||||||
PromoteGroupWaitlistEntryResult,
|
PromoteGroupWaitlistEntryResult,
|
||||||
PublicNotifyAbsence,
|
PublicNotifyAbsence,
|
||||||
|
RejectGroupPreRegistrationResult,
|
||||||
RemoveAttendeeResult,
|
RemoveAttendeeResult,
|
||||||
RemoveGroupWaitlistEntryResult,
|
RemoveGroupWaitlistEntryResult,
|
||||||
SessionStudents,
|
SessionStudents,
|
||||||
@@ -180,6 +183,23 @@ export const removeGroupWaitlistEntry = (groupId: string, entryId: string) =>
|
|||||||
method: 'DELETE',
|
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 = (
|
export const removeGroupAttendee = (
|
||||||
groupId: string,
|
groupId: string,
|
||||||
attendeeId: string,
|
attendeeId: string,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
|
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
|
||||||
|
|
||||||
|
import { countryOf, currencyForRegion, localeForRegion } from './region'
|
||||||
|
|
||||||
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
|
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
|
||||||
MONDAY: 'Lunes',
|
MONDAY: 'Lunes',
|
||||||
TUESDAY: 'Martes',
|
TUESDAY: 'Martes',
|
||||||
@@ -49,7 +51,210 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
|
|||||||
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
|
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
|
||||||
if (price == null) return '—'
|
(separadores, posición del símbolo), sin conversión — el importe lo fija
|
||||||
return price.toLocaleString('es-MX', { style: 'currency', currency: 'MXN' })
|
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 '—'
|
||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { router } from './router'
|
|||||||
import { AuthProvider } from './context/AuthProvider'
|
import { AuthProvider } from './context/AuthProvider'
|
||||||
import { ThemeProvider } from './context/ThemeProvider'
|
import { ThemeProvider } from './context/ThemeProvider'
|
||||||
import { ToastProvider } from './components/ui'
|
import { ToastProvider } from './components/ui'
|
||||||
|
import { PwaProvider } from './features/pwa'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
@@ -20,7 +21,9 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
|
|||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
|
<PwaProvider>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
|
</PwaProvider>
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './rou
|
|||||||
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport } from './routes/_authenticated/groups/$groupId/attendees/$attendeeId'
|
import { Route as AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport } from './routes/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
|
import { Route as AuthenticatedGroupsGroupIdAttendeesNewRouteImport } from './routes/_authenticated/groups/$groupId/attendees/new'
|
||||||
|
|
||||||
const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
||||||
id: '/_authenticated',
|
id: '/_authenticated',
|
||||||
@@ -122,6 +123,12 @@ const AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute =
|
|||||||
path: '/groups/$groupId/attendees/$attendeeId',
|
path: '/groups/$groupId/attendees/$attendeeId',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AuthenticatedGroupsGroupIdAttendeesNewRoute =
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesNewRouteImport.update({
|
||||||
|
id: '/groups/$groupId/attendees/new',
|
||||||
|
path: '/groups/$groupId/attendees/new',
|
||||||
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
|
} as any)
|
||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
@@ -141,6 +148,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
|
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
@@ -160,6 +168,7 @@ export interface FileRoutesByTo {
|
|||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
|
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
@@ -181,6 +190,7 @@ export interface FileRoutesById {
|
|||||||
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
|
'/_authenticated/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
@@ -202,6 +212,7 @@ export interface FileRouteTypes {
|
|||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId/'
|
| '/groups/$groupId/'
|
||||||
| '/groups/$groupId/attendees/$attendeeId'
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
|
| '/groups/$groupId/attendees/new'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
| '/login'
|
| '/login'
|
||||||
@@ -221,6 +232,7 @@ export interface FileRouteTypes {
|
|||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId'
|
| '/groups/$groupId'
|
||||||
| '/groups/$groupId/attendees/$attendeeId'
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
|
| '/groups/$groupId/attendees/new'
|
||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/_authenticated'
|
| '/_authenticated'
|
||||||
@@ -241,6 +253,7 @@ export interface FileRouteTypes {
|
|||||||
| '/_authenticated/groups/$groupId/analytics'
|
| '/_authenticated/groups/$groupId/analytics'
|
||||||
| '/_authenticated/groups/$groupId/'
|
| '/_authenticated/groups/$groupId/'
|
||||||
| '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
| '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
|
| '/_authenticated/groups/$groupId/attendees/new'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
@@ -381,6 +394,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport
|
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
parentRoute: typeof AuthenticatedRoute
|
||||||
}
|
}
|
||||||
|
'/_authenticated/groups/$groupId/attendees/new': {
|
||||||
|
id: '/_authenticated/groups/$groupId/attendees/new'
|
||||||
|
path: '/groups/$groupId/attendees/new'
|
||||||
|
fullPath: '/groups/$groupId/attendees/new'
|
||||||
|
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAttendeesNewRouteImport
|
||||||
|
parentRoute: typeof AuthenticatedRoute
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,6 +416,7 @@ interface AuthenticatedRouteChildren {
|
|||||||
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesNewRoute: typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||||
@@ -413,6 +434,8 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
|||||||
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute:
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute:
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute,
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute,
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesNewRoute:
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesNewRoute,
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { useParams } from '@tanstack/react-router'
|
||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { AddAttendeePage } from '../../../../../features/groups/add/AddAttendeePage'
|
||||||
|
import { AddAttendeeProvider } from '../../../../../features/groups/add/AddAttendeeProvider'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/new')({
|
||||||
|
component: () => {
|
||||||
|
const { groupId } = useParams({ from: '/_authenticated/groups/$groupId/attendees/new' })
|
||||||
|
return (
|
||||||
|
<AddAttendeeProvider groupId={groupId}>
|
||||||
|
<AddAttendeePage />
|
||||||
|
</AddAttendeeProvider>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { OnboardingProvider } from '../features/onboarding/OnboardingProvider'
|
||||||
import { OnboardingView } from '../features/onboarding/OnboardingView'
|
import { OnboardingView } from '../features/onboarding/OnboardingView'
|
||||||
|
|
||||||
export const Route = createFileRoute('/onboarding')({
|
export const Route = createFileRoute('/onboarding')({
|
||||||
component: OnboardingView,
|
component: () => (
|
||||||
|
<OnboardingProvider>
|
||||||
|
<OnboardingView />
|
||||||
|
</OnboardingProvider>
|
||||||
|
),
|
||||||
})
|
})
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user