feat: initial commit — frontend + backend + docker + schema

This commit is contained in:
Jorem Juárez committed 2026-04-20 18:32:29 -06:00
commit 37bb88c440
25 files changed
+4616

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# ══════════ API ══════════
NODE_ENV=production
API_PORT=3001
API_HOST=0.0.0.0
LOG_LEVEL=info
# ══════════ DATABASE ══════════
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=wonderloo
POSTGRES_USER=wonderloo_app
POSTGRES_PASSWORD= # generar con: openssl rand -base64 32
# ══════════ GOOGLE SHEETS MIRROR ══════════
SHEETS_WEBHOOK_URL=https://script.google.com/macros/s/XXXX/exec
SHEETS_SYNC_ENABLED=true
# ══════════ CORS ══════════
# Dominios permitidos (separados por coma)
ALLOWED_ORIGINS=https://registro.wonderlooindoorpark.com,https://wonderloo.collinasystems.com.mx
+37
View File
@@ -0,0 +1,37 @@
# Dependencias
node_modules/
backend/node_modules/
# Entorno (contiene secretos)
.env
.env.local
.env.*.local
# Logs
*.log
npm-debug.log*
pino-*.log
# Builds / temporales
dist/
build/
.DS_Store
Thumbs.db
# Editor
.vscode/
.idea/
*.swp
*~
# Backups de DB
*.sql.gz
backup-*.sql
backups/
# Volúmenes de Docker (si alguien los bindmountea localmente)
postgres_data/
# Certificados (no deberían vivir aquí, pero por si acaso)
*.pem
*.key
+266
View File
@@ -0,0 +1,266 @@
# WONDERLOO — BRIEF MAESTRO PARA CLAUDE CODE
> **Lee este archivo primero.** Contiene el contexto completo, arquitectura y orden de construcción.
> Los detalles técnicos de cada módulo están en los archivos numerados (`01-*.md`, `02-*.md`, etc.).
---
## 1. Contexto del proyecto
**Cliente final:** Wonderloo Indoor Park (ludoteca infantil en Lomas de Angelópolis, Puebla, MX)
**Proveedor/ejecutor:** Collina Systems
**Modelo comercial:** Collina gestiona el servicio como SaaS. El cliente usa el sistema, Collina opera la infraestructura.
**Estado actual (abril 2026):**
- Hay un demo estático ya hosteado en `wonderloo.collinasystems.com.mx` (archivo `wonderloo.html` incluido)
- El demo guarda datos en un Google Sheet vía Apps Script
- La dueña de Wonderloo ya lo vio en reunión y quedamos de entregar prototipo el jueves
**Lo que construimos ahora:**
Migrar del demo estático + Sheets a una arquitectura real self-hosted, manteniendo Sheets como **espejo de lectura** (la dueña ya lo tiene como su mini-dashboard).
---
## 2. Arquitectura objetivo
```
┌─────────────────────────────────────────────────────────────┐
│ registro.wonderlooindoorpark.com │
│ (dominio del cliente, DNS apunta al VPS de Collina) │
└──────────────────────────┬──────────────────────────────────┘
│ HTTPS (Let's Encrypt)
▼
┌─────────────────────────────────────────────────────────────┐
│ VPS DE COLLINA │
│ ┌──────────┐ │
│ │ Nginx │ ← SSL termination, reverse proxy │
│ └────┬─────┘ │
│ │ │
│ ├─► / (archivos estáticos) → wonderloo.html │
│ │ │
│ └─► /api/* (reverse proxy) → Node API (puerto │
│ interno 3001) │
│ │ │
│ ▼ │
│ ┌────────────────────────┐ │
│ │ Fastify API (Docker) │ │
│ └───────────┬────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────┐ │
│ │ PostgreSQL 16 (Docker)│ │
│ └────────────────────────┘ │
│ │ │
└──────────────────────────────────────────┼───────────────────┘
│
│ fire-and-forget
▼
┌──────────────────────────┐
│ Google Apps Script │
│ (webhook existente) │
└──────────┬───────────────┘
▼
┌──────────────────────────┐
│ Google Sheet (espejo) │
│ dueña ya tiene acceso │
└──────────────────────────┘
```
**Decisiones clave:**
1. **PostgreSQL es la fuente de verdad.** Google Sheets es espejo. Si Sheets falla, la DB ya tiene todo.
2. **El frontend es HTML estático** servido por Nginx. No hay build step, no hay SSR. El archivo actual (`wonderloo.html`) se modifica para que hable con la API en vez de con el mock DB local.
3. **El API es un solo servicio Node** (Fastify) en Docker. Junto con Postgres en otro container, orquestados con `docker-compose`.
4. **Nginx corre en el host del VPS**, no en Docker. Esto simplifica el manejo de SSL con certbot y permite servir múltiples subdominios en el mismo servidor si Collina suma más clientes.
5. **El Apps Script webhook se llama desde el backend**, no desde el navegador. Así la URL del webhook no queda expuesta en el HTML público.
---
## 3. Stack técnico
| Capa | Tecnología | Por qué |
|------|-----------|---------|
| Frontend | HTML + React (vía CDN) + Babel standalone | Ya existe, funciona, no merece sobre-ingeniería |
| API | Node.js 20 LTS + Fastify | Rápido, logger built-in, schema validation con JSON Schema |
| DB | PostgreSQL 16 | SQL real, triggers, UUIDs nativos |
| Driver DB | `pg` (node-postgres) con prepared statements | Sin ORM — el schema es simple, las queries son ~10. ORM sería overkill. |
| Container | Docker + Docker Compose | Reproducible, un `docker compose up -d` y listo |
| Reverse proxy | Nginx (host, no Docker) | SSL + static files + proxy a API |
| SSL | Let's Encrypt via certbot | Gratis, auto-renewal |
| Logging | Pino (default de Fastify) | JSON logs, rápido, estándar |
| Env | `.env` files con `dotenv` | Simple, explícito |
**Sin:** Redis, message queues, Kubernetes, microservicios. Es un solo local con ~200 visitas/mes proyectadas. Sobre-ingeniería mata el proyecto.
---
## 4. Estructura del repositorio
```
wonderloo-checkin/
├── README.md ← este archivo (00-BRIEF.md renombrado al repo)
├── docker-compose.yml ← orquesta api + postgres
├── .env.example ← variables de entorno template
├── .gitignore
│
├── frontend/
│ └── wonderloo.html ← HTML modificado para hablar con /api
│
├── backend/
│ ├── Dockerfile
│ ├── package.json
│ ├── package-lock.json
│ └── src/
│ ├── index.js ← entry point de Fastify
│ ├── config.js ← lee envs
│ ├── db/
│ │ ├── client.js ← pool de pg
│ │ └── migrations/
│ │ └── 001_initial.sql ← schema completo
│ ├── routes/
│ │ ├── tutores.js ← lookup, create, update
│ │ ├── ninos.js ← add child to existing tutor
│ │ ├── visitas.js ← create visit (main check-in)
│ │ └── precios.js ← GET prices
│ └── services/
│ └── sheets-sync.js ← fire-and-forget al Apps Script
│
├── deploy/
│ ├── nginx.conf ← config completa para nginx
│ ├── deploy.sh ← script de deploy (git pull + restart)
│ └── init-letsencrypt.sh ← bootstrap del SSL
│
└── docs/
├── 01-SCHEMA.md ← decisiones del schema con explicación
├── 02-API.md ← spec de endpoints
├── 03-DEPLOY.md ← paso a paso del deploy al VPS
└── 04-DNS.md ← instrucciones para Wonderloo (cliente)
```
---
## 5. Build order (orden sugerido de tareas)
### Fase A — Backend local (Claude Code puede empezar aquí)
1. **Inicializar el repo** con la estructura de arriba
2. **Backend Fastify base:**
- `npm init`, instalar `fastify`, `pg`, `dotenv`, `pino-pretty`
- `src/index.js` con health check en `GET /api/health`
- `src/config.js` que lee env vars
3. **Schema SQL:** Crear `src/db/migrations/001_initial.sql` (ver `docs/01-SCHEMA.md`)
4. **Cliente de DB:** `src/db/client.js` con pool de `pg`
5. **Rutas:** implementar en orden
- `routes/tutores.js` — lookup por teléfono, crear, actualizar
- `routes/ninos.js` — agregar niño a tutor existente
- `routes/visitas.js` — crear visita + append en `visita_ninos`
- `routes/precios.js` — GET de precios
6. **Sheets sync service** — `services/sheets-sync.js` que llama al Apps Script después de crear visita exitosamente
7. **Docker Compose local:** levantar Postgres + API y correr migraciones
### Fase B — Frontend integrado
8. **Modificar `wonderloo.html`:**
- Borrar el `INITIAL_DB` hardcoded
- Borrar la función `syncToSheets` (ahora lo hace el backend)
- Reemplazar las escrituras/lecturas del mock DB por `fetch` al API
- Agregar constante `API_BASE` al inicio del script
9. **Probar end-to-end local:** docker compose arriba, abrir `wonderloo.html`, hacer registros, verificar que aparezcan en la DB y en el Sheet
### Fase C — Deploy al VPS
10. **Subir repo al VPS** (git clone desde GitHub/GitLab)
11. **Instalar Docker, Docker Compose, Nginx, Certbot** en el host
12. **Configurar Nginx** con `deploy/nginx.conf` para:
- Servir `frontend/wonderloo.html` en `/`
- Proxy pass de `/api/*` a `http://localhost:3001`
13. **Obtener SSL** para `registro.wonderlooindoorpark.com` (necesita DNS ya apuntando al VPS)
14. **Levantar Docker Compose:** `docker compose up -d`
15. **Smoke test:** `curl https://registro.wonderlooindoorpark.com/api/health` debe devolver `{"status":"ok"}`
### Fase D — Handoff al cliente
16. **Documentar para Wonderloo** el procedimiento DNS (en `docs/04-DNS.md`)
17. **Compartir Google Sheet** con el correo de la dueña
18. **Generar QR** apuntando a `https://registro.wonderlooindoorpark.com`
---
## 6. Variables de entorno
`.env.example`:
```bash
# ══════════ API ══════════
NODE_ENV=production
API_PORT=3001
API_HOST=0.0.0.0
LOG_LEVEL=info
# ══════════ DATABASE ══════════
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=wonderloo
POSTGRES_USER=wonderloo_app
POSTGRES_PASSWORD= # generar con: openssl rand -base64 32
# ══════════ GOOGLE SHEETS MIRROR ══════════
SHEETS_WEBHOOK_URL=https://script.google.com/macros/s/XXXX/exec
SHEETS_SYNC_ENABLED=true
# ══════════ CORS ══════════
# Dominios permitidos (separados por coma)
ALLOWED_ORIGINS=https://registro.wonderlooindoorpark.com,https://wonderloo.collinasystems.com.mx
```
---
## 7. Reglas de negocio (invariantes)
Estas reglas son independientes de la implementación y deben respetarse siempre:
1. **WhatsApp es el identificador único del tutor.** No hay auth tradicional.
2. **Un tutor puede tener 1–4 niños.** Cada uno con su propia relación con el tutor.
3. **Los niños agregados desde el flujo "Ya tengo cuenta" se persisten permanentemente.**
4. **Cambio de teléfono = UPDATE atómico.** El registro se re-indexa con el nuevo número.
5. **La responsiva se firma en cada visita** (requisito legal).
6. **Cada visita registra qué niños específicos asistieron** (no todos los registrados).
7. **Precios vienen de la tabla `precios`,** no hardcodeados.
8. **Si el sync a Sheets falla, NO se bloquea el registro.** La DB es la fuente de verdad.
9. **El frontend no conoce la URL del webhook de Sheets.** Solo el backend.
---
## 8. Lo que NO se construye ahora
Explícitamente fuera de scope para no desbordar:
- Panel de admin para staff (viene después)
- Envío automático de WhatsApp (Fase 02)
- Dashboard con gráficas (Fase 03)
- Módulo de reservas de fiestas
- Autenticación multi-tenant (si Collina suma más clientes, se replantea)
- CI/CD automatizado — por ahora el deploy es SSH + script manual
---
## 9. Contacto y handoff
**El jueves 24 de abril 2026** se le entrega a la dueña de Wonderloo:
- URL funcional: `https://registro.wonderlooindoorpark.com`
- Acceso de lectura al Google Sheet (espejo)
- QR físico impreso para poner en la entrada del parque
Para los siguientes pasos (Fase 02 en adelante), se abre conversación comercial con el cliente después del jueves.
---
## 10. Archivos de referencia
Todos los archivos `docs/*.md` complementan este brief. Léelos en este orden:
1. `docs/01-SCHEMA.md` — decisiones del schema, SQL comentado
2. `docs/02-API.md` — endpoints con request/response examples
3. `docs/03-DEPLOY.md` — comandos exactos para el VPS
4. `docs/04-DNS.md` — lo que el cliente debe configurar (si necesitas pasárselo)
El archivo `frontend/wonderloo.html` original (el que ya está en producción como demo estático) se incluye en el repo como punto de partida. Se modifica, no se re-escribe.
+6
View File
@@ -0,0 +1,6 @@
node_modules
npm-debug.log
.env
.env.*
Dockerfile
.dockerignore
+16
View File
@@ -0,0 +1,16 @@
FROM node:20-alpine AS base
WORKDIR /app
# Dependencias
COPY package*.json ./
RUN npm ci --omit=dev
# Código
COPY src ./src
ENV NODE_ENV=production
EXPOSE 3001
USER node
CMD ["node", "src/index.js"]
+1144
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
{
"name": "wonderloo-api",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "API de check-in digital para Wonderloo Indoor Park",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js"
},
"dependencies": {
"@fastify/cors": "^10.0.1",
"dotenv": "^16.4.5",
"fastify": "^5.1.0",
"pg": "^8.13.1"
},
"devDependencies": {
"pino-pretty": "^11.3.0"
},
"engines": {
"node": ">=20"
}
}
+48
View File
@@ -0,0 +1,48 @@
import dotenv from 'dotenv';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const envPath = path.resolve(__dirname, '../../.env');
dotenv.config({ path: envPath });
const requiredVars = ['POSTGRES_PASSWORD', 'POSTGRES_DB', 'POSTGRES_USER', 'API_PORT'];
const missing = requiredVars.filter((key) => !process.env[key]);
if (missing.length > 0) {
for (const key of missing) {
console.error(`✗ Falta ${key} en .env`);
}
console.error(`\n Archivo esperado: ${envPath}`);
console.error(` Copia .env.example → .env y rellena los valores.\n`);
process.exit(1);
}
const sheetsSyncEnabled = process.env.SHEETS_SYNC_ENABLED === 'true';
if (sheetsSyncEnabled && !process.env.SHEETS_WEBHOOK_URL) {
console.warn(
'⚠ SHEETS_SYNC_ENABLED=true pero SHEETS_WEBHOOK_URL no está definido — el sync a Sheets quedará deshabilitado en runtime'
);
}
export const config = {
nodeEnv: process.env.NODE_ENV || 'development',
apiPort: Number(process.env.API_PORT),
apiHost: process.env.API_HOST || '0.0.0.0',
logLevel: process.env.LOG_LEVEL || 'info',
db: {
host: process.env.POSTGRES_HOST || 'localhost',
port: Number(process.env.POSTGRES_PORT || 5432),
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
},
sheetsWebhookUrl: process.env.SHEETS_WEBHOOK_URL || '',
sheetsSyncEnabled,
allowedOrigins: (process.env.ALLOWED_ORIGINS || '')
.split(',')
.map((origin) => origin.trim())
.filter(Boolean),
};
+40
View File
@@ -0,0 +1,40 @@
import pg from 'pg';
import { config } from '../config.js';
const { Pool } = pg;
const pool = new Pool({
host: config.db.host,
port: config.db.port,
database: config.db.database,
user: config.db.user,
password: config.db.password,
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
});
pool.on('error', (err) => {
console.error('[db] Error inesperado del pool:', err);
});
export const db = {
query(text, params) {
return pool.query(text, params);
},
getClient() {
return pool.connect();
},
end() {
return pool.end();
},
async testConnection() {
try {
const res = await pool.query('SELECT 1 AS ok');
return res.rows[0]?.ok === 1;
} catch (err) {
console.error('[db] testConnection falló:', err.message);
return false;
}
},
};
+166
View File
@@ -0,0 +1,166 @@
-- ═══════════════════════════════════════════════════════════
-- Wonderloo Indoor Park — Schema inicial
-- ═══════════════════════════════════════════════════════════
-- Para UUIDs nativos sin extensión extra
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
-- ══════════════ TUTORES ══════════════
CREATE TABLE tutores (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
nombre TEXT NOT NULL,
telefono TEXT NOT NULL UNIQUE,
correo TEXT,
canal_adquisicion TEXT,
codigo_postal TEXT,
notas_internas TEXT,
total_visitas INTEGER DEFAULT 0,
ultima_visita TIMESTAMPTZ,
primera_visita TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_tutores_telefono ON tutores(telefono);
CREATE INDEX idx_tutores_ultima_visita ON tutores(ultima_visita);
-- ══════════════ NIÑOS ══════════════
CREATE TABLE ninos (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
tutor_id UUID NOT NULL REFERENCES tutores(id) ON DELETE CASCADE,
nombre TEXT NOT NULL,
fecha_nacimiento DATE,
edad_registro INTEGER NOT NULL CHECK (edad_registro BETWEEN 1 AND 17),
genero TEXT,
relacion TEXT NOT NULL,
alergias TEXT,
activo BOOLEAN DEFAULT TRUE,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_ninos_tutor ON ninos(tutor_id);
CREATE INDEX idx_ninos_cumple ON ninos(fecha_nacimiento);
CREATE INDEX idx_ninos_activo ON ninos(activo) WHERE activo = TRUE;
-- ══════════════ VISITAS ══════════════
CREATE TABLE visitas (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
tutor_id UUID NOT NULL REFERENCES tutores(id),
tipo_servicio TEXT NOT NULL CHECK (tipo_servicio IN ('hora', 'daypass')),
metodo_pago TEXT NOT NULL CHECK (metodo_pago IN ('mostrador', 'applepay')),
firma_base64 TEXT NOT NULL,
responsiva_aceptada BOOLEAN NOT NULL DEFAULT TRUE,
hora_entrada TIMESTAMPTZ DEFAULT NOW(),
hora_salida TIMESTAMPTZ,
duracion_minutos INTEGER,
num_adultos INTEGER DEFAULT 1,
notas_staff TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_visitas_tutor ON visitas(tutor_id);
CREATE INDEX idx_visitas_fecha ON visitas(hora_entrada);
CREATE INDEX idx_visitas_servicio ON visitas(tipo_servicio);
-- ══════════════ VISITA_NIÑOS (M:N) ══════════════
CREATE TABLE visita_ninos (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
visita_id UUID NOT NULL REFERENCES visitas(id) ON DELETE CASCADE,
nino_id UUID NOT NULL REFERENCES ninos(id),
UNIQUE(visita_id, nino_id)
);
CREATE INDEX idx_visita_ninos_visita ON visita_ninos(visita_id);
CREATE INDEX idx_visita_ninos_nino ON visita_ninos(nino_id);
-- ══════════════ PRECIOS ══════════════
CREATE TABLE precios (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
concepto TEXT NOT NULL UNIQUE,
monto DECIMAL(10,2) NOT NULL,
activo BOOLEAN DEFAULT TRUE,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO precios (concepto, monto) VALUES
('nino_hora', 235.00),
('nino_daypass', 285.00),
('adulto_hora', 99.00),
('adulto_daypass', 199.00),
('hora_extra', 55.00),
('calcetas', 49.00);
-- ══════════════ FEEDBACK (estructura lista, se usa en Fase 02) ══════════════
CREATE TABLE feedback (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
visita_id UUID NOT NULL REFERENCES visitas(id),
rating INTEGER CHECK (rating BETWEEN 1 AND 5),
comentario TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ══════════════ TRIGGERS ══════════════
-- 1) Al crear una visita, incrementa stats del tutor
CREATE OR REPLACE FUNCTION actualizar_stats_tutor()
RETURNS TRIGGER AS $$
BEGIN
UPDATE tutores
SET total_visitas = total_visitas + 1,
ultima_visita = NEW.hora_entrada,
primera_visita = COALESCE(primera_visita, NEW.hora_entrada),
updated_at = NOW()
WHERE id = NEW.tutor_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_nueva_visita
AFTER INSERT ON visitas
FOR EACH ROW
EXECUTE FUNCTION actualizar_stats_tutor();
-- 2) Al registrar salida, calcula duración
CREATE OR REPLACE FUNCTION calcular_duracion()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.hora_salida IS NOT NULL AND OLD.hora_salida IS NULL THEN
NEW.duracion_minutos = EXTRACT(EPOCH FROM (NEW.hora_salida - NEW.hora_entrada)) / 60;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_checkout
BEFORE UPDATE ON visitas
FOR EACH ROW
EXECUTE FUNCTION calcular_duracion();
-- 3) Update automático de updated_at en tutores
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_tutores_updated
BEFORE UPDATE ON tutores
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
-- ══════════════ VISTA PARA DASHBOARD FUTURO ══════════════
CREATE VIEW v_metricas_diarias AS
SELECT
DATE(v.hora_entrada) AS fecha,
COUNT(DISTINCT v.id) AS total_visitas,
COUNT(DISTINCT vn.nino_id) AS total_ninos,
COUNT(DISTINCT v.tutor_id) AS tutores_unicos,
SUM(CASE WHEN v.tipo_servicio = 'daypass' THEN 1 ELSE 0 END) AS daypass_count,
SUM(CASE WHEN v.tipo_servicio = 'hora' THEN 1 ELSE 0 END) AS hora_count,
AVG(v.duracion_minutos) FILTER (WHERE v.duracion_minutos IS NOT NULL) AS duracion_promedio_min
FROM visitas v
LEFT JOIN visita_ninos vn ON v.id = vn.visita_id
GROUP BY DATE(v.hora_entrada)
ORDER BY fecha DESC;
@@ -0,0 +1,53 @@
-- SOLO PARA DESARROLLO. No ejecutar en producción.
-- Este archivo NO se monta en /docker-entrypoint-initdb.d automáticamente.
-- Para aplicarlo manualmente:
-- docker compose exec -T postgres psql -U wonderloo_app -d wonderloo < backend/src/db/migrations/002_seed_dev.sql
-- ══════════ Tutores ══════════
INSERT INTO tutores (nombre, telefono, correo) VALUES
('Luis Wonderloo', '2222392995', ''),
('Valeria Wonderloo', '2211173907', '');
-- ══════════ Niños ══════════
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 1 Wonderloo', 6, 'Papá' FROM tutores WHERE telefono = '2222392995';
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 2 Wonderloo', 4, 'Papá' FROM tutores WHERE telefono = '2222392995';
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 1 Wonderloo', 5, 'Mamá' FROM tutores WHERE telefono = '2211173907';
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 2 Wonderloo', 3, 'Mamá' FROM tutores WHERE telefono = '2211173907';
-- ══════════ Visitas previas ══════════
-- Los triggers (trg_nueva_visita) actualizan total_visitas/ultima_visita/primera_visita
-- automáticamente al insertar en visitas.
-- Luis: 2 visitas (hace 15 días y hace 5 días)
WITH v AS (
INSERT INTO visitas (tutor_id, tipo_servicio, metodo_pago, firma_base64, hora_entrada)
SELECT id, 'daypass', 'mostrador', 'data:image/png;base64,SEED', NOW() - INTERVAL '15 days'
FROM tutores WHERE telefono = '2222392995'
RETURNING id, tutor_id
)
INSERT INTO visita_ninos (visita_id, nino_id)
SELECT v.id, n.id FROM v JOIN ninos n ON n.tutor_id = v.tutor_id AND n.activo = TRUE;
WITH v AS (
INSERT INTO visitas (tutor_id, tipo_servicio, metodo_pago, firma_base64, hora_entrada)
SELECT id, 'hora', 'applepay', 'data:image/png;base64,SEED', NOW() - INTERVAL '5 days'
FROM tutores WHERE telefono = '2222392995'
RETURNING id, tutor_id
)
INSERT INTO visita_ninos (visita_id, nino_id)
SELECT v.id, n.id FROM v JOIN ninos n ON n.tutor_id = v.tutor_id AND n.activo = TRUE;
-- Valeria: 1 visita (hace 10 días)
WITH v AS (
INSERT INTO visitas (tutor_id, tipo_servicio, metodo_pago, firma_base64, hora_entrada)
SELECT id, 'daypass', 'mostrador', 'data:image/png;base64,SEED', NOW() - INTERVAL '10 days'
FROM tutores WHERE telefono = '2211173907'
RETURNING id, tutor_id
)
INSERT INTO visita_ninos (visita_id, nino_id)
SELECT v.id, n.id FROM v JOIN ninos n ON n.tutor_id = v.tutor_id AND n.activo = TRUE;
+77
View File
@@ -0,0 +1,77 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import { config } from './config.js';
import { db } from './db/client.js';
import preciosRoutes from './routes/precios.js';
import tutoresRoutes from './routes/tutores.js';
import ninosRoutes from './routes/ninos.js';
import visitasRoutes from './routes/visitas.js';
const fastify = Fastify({
logger: {
level: config.logLevel,
...(config.nodeEnv === 'development' && {
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss.l',
ignore: 'pid,hostname',
singleLine: false,
},
},
}),
},
});
await fastify.register(cors, {
origin: (origin, cb) => {
if (!origin) return cb(null, true);
if (config.allowedOrigins.includes(origin)) return cb(null, true);
cb(new Error(`Origen no permitido por CORS: ${origin}`), false);
},
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
credentials: false,
});
fastify.get('/api/health', async () => ({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
}));
const shutdown = async (signal) => {
fastify.log.info({ signal }, 'Graceful shutdown iniciado');
try {
await fastify.close();
await db.end();
process.exit(0);
} catch (err) {
fastify.log.error(err, 'Error durante shutdown');
process.exit(1);
}
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
const dbOk = await db.testConnection();
if (!dbOk) {
fastify.log.fatal('DB connection failed — abortando arranque');
process.exit(1);
}
fastify.log.info('DB connection OK');
fastify.decorate('db', db);
await fastify.register(preciosRoutes, { prefix: '/api' });
await fastify.register(tutoresRoutes, { prefix: '/api' });
await fastify.register(ninosRoutes, { prefix: '/api' });
await fastify.register(visitasRoutes, { prefix: '/api' });
try {
const address = await fastify.listen({ port: config.apiPort, host: config.apiHost });
fastify.log.info(`Wonderloo API lista en ${address}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
+72
View File
@@ -0,0 +1,72 @@
export default async function ninosRoutes(fastify) {
fastify.post(
'/tutores/:tutorId/ninos',
{
schema: {
params: {
type: 'object',
required: ['tutorId'],
properties: { tutorId: { type: 'string', format: 'uuid' } },
},
body: {
type: 'object',
required: ['nombre', 'edad', 'relacion'],
properties: {
nombre: { type: 'string', minLength: 1 },
edad: { type: 'integer', minimum: 1, maximum: 17 },
fecha_nacimiento: { type: 'string' },
relacion: { type: 'string', minLength: 1 },
alergias: { type: 'string' },
},
},
},
},
async (req, reply) => {
const { tutorId } = req.params;
const {
nombre,
edad,
fecha_nacimiento = null,
relacion,
alergias = null,
} = req.body;
const { rows: checkRows } = await fastify.db.query(
`SELECT t.id,
(SELECT COUNT(*)::int FROM ninos n
WHERE n.tutor_id = t.id AND n.activo = TRUE) AS active_count
FROM tutores t WHERE t.id = $1`,
[tutorId]
);
if (checkRows.length === 0) {
return reply.code(404).send({
error: 'Tutor no encontrado',
code: 'TUTOR_NOT_FOUND',
});
}
if (checkRows[0].active_count >= 4) {
return reply.code(400).send({
error: 'El tutor ya tiene el máximo de 4 niños activos',
code: 'MAX_CHILDREN_REACHED',
});
}
const {
rows: [nino],
} = await fastify.db.query(
`INSERT INTO ninos (tutor_id, nombre, edad_registro, fecha_nacimiento, relacion, alergias)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, tutor_id, nombre, edad_registro AS edad, fecha_nacimiento, relacion, alergias`,
[tutorId, nombre, edad, fecha_nacimiento, relacion, alergias]
);
req.log.info(
{ tutorId, ninoId: nino.id },
'Niño agregado a tutor existente'
);
return reply.code(201).send(nino);
}
);
}
+12
View File
@@ -0,0 +1,12 @@
export default async function preciosRoutes(fastify) {
fastify.get('/precios', async () => {
const { rows } = await fastify.db.query(
'SELECT concepto, monto FROM precios WHERE activo = TRUE'
);
const out = {};
for (const r of rows) {
out[r.concepto] = Number(r.monto);
}
return out;
});
}
+196
View File
@@ -0,0 +1,196 @@
const LOOKUP_SQL = `
SELECT t.*,
COALESCE(
json_agg(
json_build_object(
'id', n.id,
'nombre', n.nombre,
'edad', n.edad_registro,
'fecha_nacimiento', n.fecha_nacimiento,
'relacion', n.relacion,
'alergias', n.alergias
)
) FILTER (WHERE n.id IS NOT NULL AND n.activo = TRUE),
'[]'::json
) AS ninos
FROM tutores t
LEFT JOIN ninos n ON n.tutor_id = t.id
WHERE t.telefono = $1
GROUP BY t.id
`;
const TUTOR_RETURN_COLS =
'id, nombre, telefono, correo, total_visitas, ultima_visita, primera_visita';
export default async function tutoresRoutes(fastify) {
// ──────────────── POST /tutores/lookup ────────────────
fastify.post(
'/tutores/lookup',
{
schema: {
body: {
type: 'object',
required: ['telefono'],
properties: {
telefono: { type: 'string', pattern: '^[0-9]{10}$' },
},
},
},
},
async (req, reply) => {
const telefono = req.body.telefono.replace(/\D/g, '');
const { rows } = await fastify.db.query(LOOKUP_SQL, [telefono]);
if (rows.length === 0) {
return reply.code(404).send({
error: 'Tutor no encontrado',
code: 'TUTOR_NOT_FOUND',
});
}
return rows[0];
}
);
// ──────────────── POST /tutores (crear) ────────────────
fastify.post(
'/tutores',
{
schema: {
body: {
type: 'object',
required: ['nombre', 'telefono', 'ninos'],
properties: {
nombre: { type: 'string', minLength: 1 },
telefono: { type: 'string', pattern: '^[0-9]{10}$' },
correo: { type: 'string' },
ninos: {
type: 'array',
minItems: 1,
maxItems: 4,
items: {
type: 'object',
required: ['nombre', 'edad', 'relacion'],
properties: {
nombre: { type: 'string', minLength: 1 },
edad: { type: 'integer', minimum: 1, maximum: 17 },
fecha_nacimiento: { type: 'string' },
relacion: { type: 'string', minLength: 1 },
alergias: { type: 'string' },
},
},
},
},
},
},
},
async (req, reply) => {
const { nombre, correo = '', ninos } = req.body;
const telefono = req.body.telefono.replace(/\D/g, '');
const client = await fastify.db.getClient();
try {
await client.query('BEGIN');
const {
rows: [tutor],
} = await client.query(
`INSERT INTO tutores (nombre, telefono, correo)
VALUES ($1, $2, $3)
RETURNING ${TUTOR_RETURN_COLS}`,
[nombre, telefono, correo]
);
const insertedNinos = [];
for (const n of ninos) {
const {
rows: [row],
} = await client.query(
`INSERT INTO ninos (tutor_id, nombre, edad_registro, fecha_nacimiento, relacion, alergias)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, nombre, edad_registro AS edad, fecha_nacimiento, relacion, alergias`,
[tutor.id, n.nombre, n.edad, n.fecha_nacimiento || null, n.relacion, n.alergias || null]
);
insertedNinos.push(row);
}
await client.query('COMMIT');
req.log.info(
{ tutorId: tutor.id, ninos: insertedNinos.length },
'Tutor creado'
);
return reply.code(201).send({ ...tutor, ninos: insertedNinos });
} catch (err) {
await client.query('ROLLBACK');
if (err.code === '23505') {
return reply.code(409).send({
error: 'El teléfono ya está registrado',
code: 'PHONE_ALREADY_EXISTS',
});
}
throw err;
} finally {
client.release();
}
}
);
// ──────────────── PATCH /tutores/:id ────────────────
fastify.patch(
'/tutores/:id',
{
schema: {
params: {
type: 'object',
required: ['id'],
properties: { id: { type: 'string', format: 'uuid' } },
},
body: {
type: 'object',
minProperties: 1,
properties: {
telefono: { type: 'string', pattern: '^[0-9]{10}$' },
nombre: { type: 'string', minLength: 1 },
correo: { type: 'string' },
},
},
},
},
async (req, reply) => {
const { id } = req.params;
const updates = [];
const values = [id];
let i = 2;
if (req.body.telefono !== undefined) {
updates.push(`telefono = $${i++}`);
values.push(req.body.telefono.replace(/\D/g, ''));
}
if (req.body.nombre !== undefined) {
updates.push(`nombre = $${i++}`);
values.push(req.body.nombre);
}
if (req.body.correo !== undefined) {
updates.push(`correo = $${i++}`);
values.push(req.body.correo);
}
try {
const { rows } = await fastify.db.query(
`UPDATE tutores SET ${updates.join(', ')} WHERE id = $1 RETURNING ${TUTOR_RETURN_COLS}`,
values
);
if (rows.length === 0) {
return reply.code(404).send({
error: 'Tutor no encontrado',
code: 'TUTOR_NOT_FOUND',
});
}
req.log.info({ tutorId: id }, 'Tutor actualizado');
return rows[0];
} catch (err) {
if (err.code === '23505') {
return reply.code(409).send({
error: 'El teléfono ya está en uso',
code: 'PHONE_CONFLICT',
});
}
throw err;
}
}
);
}
+160
View File
@@ -0,0 +1,160 @@
import { syncVisitaToSheets } from '../services/sheets-sync.js';
function formatMexFechaHora(date) {
const parts = new Intl.DateTimeFormat('en-GB', {
timeZone: 'America/Mexico_City',
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).formatToParts(date);
const g = (type) => parts.find((p) => p.type === type).value;
return {
fecha: `${g('day')}/${g('month')}/${g('year')}`,
hora: `${g('hour')}:${g('minute')}`,
};
}
export default async function visitasRoutes(fastify) {
fastify.post(
'/visitas',
{
schema: {
body: {
type: 'object',
required: [
'tutor_id',
'nino_ids',
'tipo_servicio',
'metodo_pago',
'firma_base64',
],
properties: {
tutor_id: { type: 'string', format: 'uuid' },
nino_ids: {
type: 'array',
minItems: 1,
items: { type: 'string', format: 'uuid' },
},
tipo_servicio: { type: 'string', enum: ['hora', 'daypass'] },
metodo_pago: { type: 'string', enum: ['mostrador', 'applepay'] },
firma_base64: { type: 'string', minLength: 1 },
},
},
},
},
async (req, reply) => {
const { tutor_id, nino_ids, tipo_servicio, metodo_pago, firma_base64 } =
req.body;
// Validar que todos los nino_ids pertenecen a este tutor
const {
rows: [{ count }],
} = await fastify.db.query(
`SELECT COUNT(*)::int AS count FROM ninos
WHERE tutor_id = $1 AND id = ANY($2::uuid[])`,
[tutor_id, nino_ids]
);
if (count !== nino_ids.length) {
return reply.code(404).send({
error: 'Uno o más niños no existen o no pertenecen a este tutor',
code: 'INVALID_NINOS',
});
}
// Transacción: insertar visita + visita_ninos
const client = await fastify.db.getClient();
let visita;
try {
await client.query('BEGIN');
const {
rows: [v],
} = await client.query(
`INSERT INTO visitas (tutor_id, tipo_servicio, metodo_pago, firma_base64)
VALUES ($1, $2, $3, $4)
RETURNING id, tutor_id, tipo_servicio, metodo_pago, hora_entrada`,
[tutor_id, tipo_servicio, metodo_pago, firma_base64]
);
visita = v;
for (const ninoId of nino_ids) {
await client.query(
'INSERT INTO visita_ninos (visita_id, nino_id) VALUES ($1, $2)',
[visita.id, ninoId]
);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
// Datos para respuesta + payload de Sheets (después del COMMIT, el trigger
// ya incrementó total_visitas)
const {
rows: [tutor],
} = await fastify.db.query(
`SELECT id, nombre, telefono, correo, total_visitas
FROM tutores WHERE id = $1`,
[tutor_id]
);
const { rows: ninosActivos } = await fastify.db.query(
`SELECT id, nombre, edad_registro AS edad, relacion, alergias
FROM ninos WHERE tutor_id = $1 AND activo = TRUE`,
[tutor_id]
);
const idsSet = new Set(nino_ids);
const ninosEnVisita = ninosActivos.filter((n) => idsSet.has(n.id));
req.log.info(
{
visitaId: visita.id,
tutorId: tutor_id,
ninos: nino_ids.length,
tipo_servicio,
},
'Visita creada'
);
// Fire-and-forget a Google Sheets (no await)
const { fecha, hora } = formatMexFechaHora(new Date(visita.hora_entrada));
syncVisitaToSheets({
fecha,
hora,
tutor_nombre: tutor.nombre,
tutor_telefono: tutor.telefono,
tutor_correo: tutor.correo || '',
tipo_servicio,
metodo_pago,
ninos: ninosEnVisita.map((n) => ({
nombre: n.nombre,
edad: n.edad,
relacion: n.relacion,
alergias: n.alergias || '',
})),
todos_ninos: ninosActivos.map((n) => ({
nombre: n.nombre,
edad: n.edad,
})),
num_visita: tutor.total_visitas,
firma_capturada: !!firma_base64,
});
return reply.code(201).send({
id: visita.id,
tutor_id: visita.tutor_id,
tipo_servicio: visita.tipo_servicio,
metodo_pago: visita.metodo_pago,
hora_entrada: visita.hora_entrada,
num_visita_del_tutor: tutor.total_visitas,
ninos_en_visita: ninosEnVisita.map((n) => ({
id: n.id,
nombre: n.nombre,
})),
});
}
);
}
+45
View File
@@ -0,0 +1,45 @@
import { request } from 'node:https';
import { URL } from 'node:url';
import { config } from '../config.js';
export function syncVisitaToSheets(payload) {
if (!config.sheetsSyncEnabled || !config.sheetsWebhookUrl) {
return;
}
try {
const url = new URL(config.sheetsWebhookUrl);
const body = JSON.stringify(payload);
const req = request(
{
method: 'POST',
hostname: url.hostname,
path: url.pathname + url.search,
headers: {
'Content-Type': 'text/plain;charset=utf-8',
'Content-Length': Buffer.byteLength(body),
},
timeout: 5000,
},
(res) => {
// Drenamos para liberar el socket, no nos importa el contenido
res.resume();
}
);
req.on('error', (err) => {
console.warn('[sheets-sync] Error (no crítico):', err.message);
});
req.on('timeout', () => {
req.destroy();
console.warn('[sheets-sync] Timeout (no crítico)');
});
req.write(body);
req.end();
} catch (err) {
console.warn('[sheets-sync] Excepción (no crítico):', err.message);
}
}
+51
View File
@@ -0,0 +1,51 @@
services:
postgres:
image: postgres:16-alpine
container_name: wonderloo_postgres
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
# Se monta SOLO 001_initial.sql para evitar auto-ejecución del seed dev.
# 002_seed_dev.sql se aplicará manualmente cuando queramos datos de prueba.
- ./backend/src/db/migrations/001_initial.sql:/docker-entrypoint-initdb.d/001_initial.sql:ro
ports:
- "127.0.0.1:5432:5432" # solo localhost, no expuesto público
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
api:
build:
context: ./backend
dockerfile: Dockerfile
container_name: wonderloo_api
restart: unless-stopped
env_file: .env
environment:
# Override: el container corre en modo producción (JSON logs, sin pino-pretty)
# aunque .env esté en development para ejecuciones locales de npm run dev.
NODE_ENV: production
depends_on:
postgres:
condition: service_healthy
ports:
- "127.0.0.1:3001:3001" # solo localhost, no expuesto público
frontend:
image: nginx:alpine
container_name: wonderloo_frontend
restart: unless-stopped
volumes:
- ./frontend:/usr/share/nginx/html:ro
ports:
- "127.0.0.1:8080:80"
volumes:
postgres_data:
driver: local
+266
View File
@@ -0,0 +1,266 @@
# WONDERLOO — BRIEF MAESTRO PARA CLAUDE CODE
> **Lee este archivo primero.** Contiene el contexto completo, arquitectura y orden de construcción.
> Los detalles técnicos de cada módulo están en los archivos numerados (`01-*.md`, `02-*.md`, etc.).
---
## 1. Contexto del proyecto
**Cliente final:** Wonderloo Indoor Park (ludoteca infantil en Lomas de Angelópolis, Puebla, MX)
**Proveedor/ejecutor:** Collina Systems
**Modelo comercial:** Collina gestiona el servicio como SaaS. El cliente usa el sistema, Collina opera la infraestructura.
**Estado actual (abril 2026):**
- Hay un demo estático ya hosteado en `wonderloo.collinasystems.com.mx` (archivo `wonderloo.html` incluido)
- El demo guarda datos en un Google Sheet vía Apps Script
- La dueña de Wonderloo ya lo vio en reunión y quedamos de entregar prototipo el jueves
**Lo que construimos ahora:**
Migrar del demo estático + Sheets a una arquitectura real self-hosted, manteniendo Sheets como **espejo de lectura** (la dueña ya lo tiene como su mini-dashboard).
---
## 2. Arquitectura objetivo
```
┌─────────────────────────────────────────────────────────────┐
│ registro.wonderlooindoorpark.com │
│ (dominio del cliente, DNS apunta al VPS de Collina) │
└──────────────────────────┬──────────────────────────────────┘
│ HTTPS (Let's Encrypt)
▼
┌─────────────────────────────────────────────────────────────┐
│ VPS DE COLLINA │
│ ┌──────────┐ │
│ │ Nginx │ ← SSL termination, reverse proxy │
│ └────┬─────┘ │
│ │ │
│ ├─► / (archivos estáticos) → wonderloo.html │
│ │ │
│ └─► /api/* (reverse proxy) → Node API (puerto │
│ interno 3001) │
│ │ │
│ ▼ │
│ ┌────────────────────────┐ │
│ │ Fastify API (Docker) │ │
│ └───────────┬────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────┐ │
│ │ PostgreSQL 16 (Docker)│ │
│ └────────────────────────┘ │
│ │ │
└──────────────────────────────────────────┼───────────────────┘
│
│ fire-and-forget
▼
┌──────────────────────────┐
│ Google Apps Script │
│ (webhook existente) │
└──────────┬───────────────┘
▼
┌──────────────────────────┐
│ Google Sheet (espejo) │
│ dueña ya tiene acceso │
└──────────────────────────┘
```
**Decisiones clave:**
1. **PostgreSQL es la fuente de verdad.** Google Sheets es espejo. Si Sheets falla, la DB ya tiene todo.
2. **El frontend es HTML estático** servido por Nginx. No hay build step, no hay SSR. El archivo actual (`wonderloo.html`) se modifica para que hable con la API en vez de con el mock DB local.
3. **El API es un solo servicio Node** (Fastify) en Docker. Junto con Postgres en otro container, orquestados con `docker-compose`.
4. **Nginx corre en el host del VPS**, no en Docker. Esto simplifica el manejo de SSL con certbot y permite servir múltiples subdominios en el mismo servidor si Collina suma más clientes.
5. **El Apps Script webhook se llama desde el backend**, no desde el navegador. Así la URL del webhook no queda expuesta en el HTML público.
---
## 3. Stack técnico
| Capa | Tecnología | Por qué |
|------|-----------|---------|
| Frontend | HTML + React (vía CDN) + Babel standalone | Ya existe, funciona, no merece sobre-ingeniería |
| API | Node.js 20 LTS + Fastify | Rápido, logger built-in, schema validation con JSON Schema |
| DB | PostgreSQL 16 | SQL real, triggers, UUIDs nativos |
| Driver DB | `pg` (node-postgres) con prepared statements | Sin ORM — el schema es simple, las queries son ~10. ORM sería overkill. |
| Container | Docker + Docker Compose | Reproducible, un `docker compose up -d` y listo |
| Reverse proxy | Nginx (host, no Docker) | SSL + static files + proxy a API |
| SSL | Let's Encrypt via certbot | Gratis, auto-renewal |
| Logging | Pino (default de Fastify) | JSON logs, rápido, estándar |
| Env | `.env` files con `dotenv` | Simple, explícito |
**Sin:** Redis, message queues, Kubernetes, microservicios. Es un solo local con ~200 visitas/mes proyectadas. Sobre-ingeniería mata el proyecto.
---
## 4. Estructura del repositorio
```
wonderloo-checkin/
├── README.md ← este archivo (00-BRIEF.md renombrado al repo)
├── docker-compose.yml ← orquesta api + postgres
├── .env.example ← variables de entorno template
├── .gitignore
│
├── frontend/
│ └── wonderloo.html ← HTML modificado para hablar con /api
│
├── backend/
│ ├── Dockerfile
│ ├── package.json
│ ├── package-lock.json
│ └── src/
│ ├── index.js ← entry point de Fastify
│ ├── config.js ← lee envs
│ ├── db/
│ │ ├── client.js ← pool de pg
│ │ └── migrations/
│ │ └── 001_initial.sql ← schema completo
│ ├── routes/
│ │ ├── tutores.js ← lookup, create, update
│ │ ├── ninos.js ← add child to existing tutor
│ │ ├── visitas.js ← create visit (main check-in)
│ │ └── precios.js ← GET prices
│ └── services/
│ └── sheets-sync.js ← fire-and-forget al Apps Script
│
├── deploy/
│ ├── nginx.conf ← config completa para nginx
│ ├── deploy.sh ← script de deploy (git pull + restart)
│ └── init-letsencrypt.sh ← bootstrap del SSL
│
└── docs/
├── 01-SCHEMA.md ← decisiones del schema con explicación
├── 02-API.md ← spec de endpoints
├── 03-DEPLOY.md ← paso a paso del deploy al VPS
└── 04-DNS.md ← instrucciones para Wonderloo (cliente)
```
---
## 5. Build order (orden sugerido de tareas)
### Fase A — Backend local (Claude Code puede empezar aquí)
1. **Inicializar el repo** con la estructura de arriba
2. **Backend Fastify base:**
- `npm init`, instalar `fastify`, `pg`, `dotenv`, `pino-pretty`
- `src/index.js` con health check en `GET /api/health`
- `src/config.js` que lee env vars
3. **Schema SQL:** Crear `src/db/migrations/001_initial.sql` (ver `docs/01-SCHEMA.md`)
4. **Cliente de DB:** `src/db/client.js` con pool de `pg`
5. **Rutas:** implementar en orden
- `routes/tutores.js` — lookup por teléfono, crear, actualizar
- `routes/ninos.js` — agregar niño a tutor existente
- `routes/visitas.js` — crear visita + append en `visita_ninos`
- `routes/precios.js` — GET de precios
6. **Sheets sync service** — `services/sheets-sync.js` que llama al Apps Script después de crear visita exitosamente
7. **Docker Compose local:** levantar Postgres + API y correr migraciones
### Fase B — Frontend integrado
8. **Modificar `wonderloo.html`:**
- Borrar el `INITIAL_DB` hardcoded
- Borrar la función `syncToSheets` (ahora lo hace el backend)
- Reemplazar las escrituras/lecturas del mock DB por `fetch` al API
- Agregar constante `API_BASE` al inicio del script
9. **Probar end-to-end local:** docker compose arriba, abrir `wonderloo.html`, hacer registros, verificar que aparezcan en la DB y en el Sheet
### Fase C — Deploy al VPS
10. **Subir repo al VPS** (git clone desde GitHub/GitLab)
11. **Instalar Docker, Docker Compose, Nginx, Certbot** en el host
12. **Configurar Nginx** con `deploy/nginx.conf` para:
- Servir `frontend/wonderloo.html` en `/`
- Proxy pass de `/api/*` a `http://localhost:3001`
13. **Obtener SSL** para `registro.wonderlooindoorpark.com` (necesita DNS ya apuntando al VPS)
14. **Levantar Docker Compose:** `docker compose up -d`
15. **Smoke test:** `curl https://registro.wonderlooindoorpark.com/api/health` debe devolver `{"status":"ok"}`
### Fase D — Handoff al cliente
16. **Documentar para Wonderloo** el procedimiento DNS (en `docs/04-DNS.md`)
17. **Compartir Google Sheet** con el correo de la dueña
18. **Generar QR** apuntando a `https://registro.wonderlooindoorpark.com`
---
## 6. Variables de entorno
`.env.example`:
```bash
# ══════════ API ══════════
NODE_ENV=production
API_PORT=3001
API_HOST=0.0.0.0
LOG_LEVEL=info
# ══════════ DATABASE ══════════
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=wonderloo
POSTGRES_USER=wonderloo_app
POSTGRES_PASSWORD= # generar con: openssl rand -base64 32
# ══════════ GOOGLE SHEETS MIRROR ══════════
SHEETS_WEBHOOK_URL=https://script.google.com/macros/s/XXXX/exec
SHEETS_SYNC_ENABLED=true
# ══════════ CORS ══════════
# Dominios permitidos (separados por coma)
ALLOWED_ORIGINS=https://registro.wonderlooindoorpark.com,https://wonderloo.collinasystems.com.mx
```
---
## 7. Reglas de negocio (invariantes)
Estas reglas son independientes de la implementación y deben respetarse siempre:
1. **WhatsApp es el identificador único del tutor.** No hay auth tradicional.
2. **Un tutor puede tener 1–4 niños.** Cada uno con su propia relación con el tutor.
3. **Los niños agregados desde el flujo "Ya tengo cuenta" se persisten permanentemente.**
4. **Cambio de teléfono = UPDATE atómico.** El registro se re-indexa con el nuevo número.
5. **La responsiva se firma en cada visita** (requisito legal).
6. **Cada visita registra qué niños específicos asistieron** (no todos los registrados).
7. **Precios vienen de la tabla `precios`,** no hardcodeados.
8. **Si el sync a Sheets falla, NO se bloquea el registro.** La DB es la fuente de verdad.
9. **El frontend no conoce la URL del webhook de Sheets.** Solo el backend.
---
## 8. Lo que NO se construye ahora
Explícitamente fuera de scope para no desbordar:
- Panel de admin para staff (viene después)
- Envío automático de WhatsApp (Fase 02)
- Dashboard con gráficas (Fase 03)
- Módulo de reservas de fiestas
- Autenticación multi-tenant (si Collina suma más clientes, se replantea)
- CI/CD automatizado — por ahora el deploy es SSH + script manual
---
## 9. Contacto y handoff
**El jueves 24 de abril 2026** se le entrega a la dueña de Wonderloo:
- URL funcional: `https://registro.wonderlooindoorpark.com`
- Acceso de lectura al Google Sheet (espejo)
- QR físico impreso para poner en la entrada del parque
Para los siguientes pasos (Fase 02 en adelante), se abre conversación comercial con el cliente después del jueves.
---
## 10. Archivos de referencia
Todos los archivos `docs/*.md` complementan este brief. Léelos en este orden:
1. `docs/01-SCHEMA.md` — decisiones del schema, SQL comentado
2. `docs/02-API.md` — endpoints con request/response examples
3. `docs/03-DEPLOY.md` — comandos exactos para el VPS
4. `docs/04-DNS.md` — lo que el cliente debe configurar (si necesitas pasárselo)
El archivo `frontend/wonderloo.html` original (el que ya está en producción como demo estático) se incluye en el repo como punto de partida. Se modifica, no se re-escribe.
+300
View File
@@ -0,0 +1,300 @@
# 01 — Schema de Base de Datos
## Filosofía
Tres categorías de datos, reflejadas en el schema:
- 🟢 **Usuario captura** (campos en el formulario del tutor)
- 🔵 **Sistema genera** (triggers, timestamps, contadores)
- 🟡 **Staff captura** (columnas existentes pero llenadas desde panel admin futuro — NO en el formulario de check-in)
La regla: la DB es rica, el formulario es mínimo. Cada campo extra en el formulario es un usuario que abandona.
---
## Migración inicial
**Archivo:** `backend/src/db/migrations/001_initial.sql`
```sql
-- ═══════════════════════════════════════════════════════════
-- Wonderloo Indoor Park — Schema inicial
-- ═══════════════════════════════════════════════════════════
-- Para UUIDs nativos sin extensión extra
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
-- ══════════════ TUTORES ══════════════
CREATE TABLE tutores (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
nombre TEXT NOT NULL,
telefono TEXT NOT NULL UNIQUE,
correo TEXT,
canal_adquisicion TEXT,
codigo_postal TEXT,
notas_internas TEXT,
total_visitas INTEGER DEFAULT 0,
ultima_visita TIMESTAMPTZ,
primera_visita TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_tutores_telefono ON tutores(telefono);
CREATE INDEX idx_tutores_ultima_visita ON tutores(ultima_visita);
-- ══════════════ NIÑOS ══════════════
CREATE TABLE ninos (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
tutor_id UUID NOT NULL REFERENCES tutores(id) ON DELETE CASCADE,
nombre TEXT NOT NULL,
fecha_nacimiento DATE,
edad_registro INTEGER NOT NULL CHECK (edad_registro BETWEEN 1 AND 17),
genero TEXT,
relacion TEXT NOT NULL,
alergias TEXT,
activo BOOLEAN DEFAULT TRUE,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_ninos_tutor ON ninos(tutor_id);
CREATE INDEX idx_ninos_cumple ON ninos(fecha_nacimiento);
CREATE INDEX idx_ninos_activo ON ninos(activo) WHERE activo = TRUE;
-- ══════════════ VISITAS ══════════════
CREATE TABLE visitas (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
tutor_id UUID NOT NULL REFERENCES tutores(id),
tipo_servicio TEXT NOT NULL CHECK (tipo_servicio IN ('hora', 'daypass')),
metodo_pago TEXT NOT NULL CHECK (metodo_pago IN ('mostrador', 'applepay')),
firma_base64 TEXT NOT NULL,
responsiva_aceptada BOOLEAN NOT NULL DEFAULT TRUE,
hora_entrada TIMESTAMPTZ DEFAULT NOW(),
hora_salida TIMESTAMPTZ,
duracion_minutos INTEGER,
num_adultos INTEGER DEFAULT 1,
notas_staff TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_visitas_tutor ON visitas(tutor_id);
CREATE INDEX idx_visitas_fecha ON visitas(hora_entrada);
CREATE INDEX idx_visitas_servicio ON visitas(tipo_servicio);
-- ══════════════ VISITA_NIÑOS (M:N) ══════════════
CREATE TABLE visita_ninos (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
visita_id UUID NOT NULL REFERENCES visitas(id) ON DELETE CASCADE,
nino_id UUID NOT NULL REFERENCES ninos(id),
UNIQUE(visita_id, nino_id)
);
CREATE INDEX idx_visita_ninos_visita ON visita_ninos(visita_id);
CREATE INDEX idx_visita_ninos_nino ON visita_ninos(nino_id);
-- ══════════════ PRECIOS ══════════════
CREATE TABLE precios (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
concepto TEXT NOT NULL UNIQUE,
monto DECIMAL(10,2) NOT NULL,
activo BOOLEAN DEFAULT TRUE,
updated_at TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO precios (concepto, monto) VALUES
('nino_hora', 235.00),
('nino_daypass', 285.00),
('adulto_hora', 99.00),
('adulto_daypass', 199.00),
('hora_extra', 55.00),
('calcetas', 49.00);
-- ══════════════ FEEDBACK (estructura lista, se usa en Fase 02) ══════════════
CREATE TABLE feedback (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
visita_id UUID NOT NULL REFERENCES visitas(id),
rating INTEGER CHECK (rating BETWEEN 1 AND 5),
comentario TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- ══════════════ TRIGGERS ══════════════
-- 1) Al crear una visita, incrementa stats del tutor
CREATE OR REPLACE FUNCTION actualizar_stats_tutor()
RETURNS TRIGGER AS $$
BEGIN
UPDATE tutores
SET total_visitas = total_visitas + 1,
ultima_visita = NEW.hora_entrada,
primera_visita = COALESCE(primera_visita, NEW.hora_entrada),
updated_at = NOW()
WHERE id = NEW.tutor_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_nueva_visita
AFTER INSERT ON visitas
FOR EACH ROW
EXECUTE FUNCTION actualizar_stats_tutor();
-- 2) Al registrar salida, calcula duración
CREATE OR REPLACE FUNCTION calcular_duracion()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.hora_salida IS NOT NULL AND OLD.hora_salida IS NULL THEN
NEW.duracion_minutos = EXTRACT(EPOCH FROM (NEW.hora_salida - NEW.hora_entrada)) / 60;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_checkout
BEFORE UPDATE ON visitas
FOR EACH ROW
EXECUTE FUNCTION calcular_duracion();
-- 3) Update automático de updated_at en tutores
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_tutores_updated
BEFORE UPDATE ON tutores
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
-- ══════════════ VISTA PARA DASHBOARD FUTURO ══════════════
CREATE VIEW v_metricas_diarias AS
SELECT
DATE(v.hora_entrada) AS fecha,
COUNT(DISTINCT v.id) AS total_visitas,
COUNT(DISTINCT vn.nino_id) AS total_ninos,
COUNT(DISTINCT v.tutor_id) AS tutores_unicos,
SUM(CASE WHEN v.tipo_servicio = 'daypass' THEN 1 ELSE 0 END) AS daypass_count,
SUM(CASE WHEN v.tipo_servicio = 'hora' THEN 1 ELSE 0 END) AS hora_count,
AVG(v.duracion_minutos) FILTER (WHERE v.duracion_minutos IS NOT NULL) AS duracion_promedio_min
FROM visitas v
LEFT JOIN visita_ninos vn ON v.id = vn.visita_id
GROUP BY DATE(v.hora_entrada)
ORDER BY fecha DESC;
```
---
## Explicación por tabla
### `tutores`
- `telefono` es UNIQUE — es el identificador de facto. No es PK porque el usuario puede cambiarlo y no queremos re-cascadear FKs.
- `canal_adquisicion`, `codigo_postal`, `notas_internas` son columnas 🟡 que quedan nullable — se llenan desde el panel admin futuro. **NO aparecen en el formulario.**
- `total_visitas` se actualiza automáticamente por trigger. El frontend solo hace SELECT.
### `ninos`
- `edad_registro` es la edad al momento de registrarse. Sirve como fallback cuando `fecha_nacimiento` es null.
- Si `fecha_nacimiento` existe, la edad actual se calcula con `EXTRACT(YEAR FROM AGE(fecha_nacimiento))` en queries de dashboard.
- `activo` permite "retirar" niños que ya crecieron sin borrar historial.
- `genero` queda como opcional futuro — no se pide en el formulario.
### `visitas`
- `firma_base64` guarda la firma como data URL. Para MVP está OK. Si crece mucho, moverla a archivo en disco + guardar path.
- `hora_salida`, `duracion_minutos`, `num_adultos`, `notas_staff` son 🟡 — panel futuro.
- El trigger `trg_nueva_visita` mantiene los contadores del tutor en sincronía. El API no tiene que hacer UPDATEs manuales.
### `visita_ninos`
- Clave compuesta única (`visita_id`, `nino_id`) — evita duplicados.
- ON DELETE CASCADE solo en `visita_id` — si se borra una visita, se limpia. Pero si se borra un niño, falla (se asume que primero se debe marcar `activo = false`, no borrar).
### `precios`
- La tabla se pre-puebla con los precios actuales (abril 2026).
- Cambiar un precio: `UPDATE precios SET monto = X WHERE concepto = 'nino_hora';`. Cero deploy.
- Se puede agregar `fecha_vigencia` después si requieren histórico.
### `feedback`
- Vacía al inicio. Se llena desde Fase 02 cuando mandemos WhatsApp post-visita.
---
## Queries frecuentes (referencia para las rutas del API)
### Lookup de tutor por teléfono
```sql
SELECT t.*,
COALESCE(
json_agg(
json_build_object(
'id', n.id,
'nombre', n.nombre,
'edad', n.edad_registro,
'fecha_nacimiento', n.fecha_nacimiento,
'relacion', n.relacion,
'alergias', n.alergias
)
) FILTER (WHERE n.id IS NOT NULL AND n.activo = TRUE),
'[]'::json
) AS ninos
FROM tutores t
LEFT JOIN ninos n ON n.tutor_id = t.id
WHERE t.telefono = $1
GROUP BY t.id;
```
### Crear visita con niños (dentro de transacción)
```sql
BEGIN;
INSERT INTO visitas (tutor_id, tipo_servicio, metodo_pago, firma_base64)
VALUES ($1, $2, $3, $4)
RETURNING id;
-- Por cada nino_id seleccionado:
INSERT INTO visita_ninos (visita_id, nino_id) VALUES ($visita_id, $nino_id);
COMMIT;
```
### Agregar niño a tutor existente
```sql
INSERT INTO ninos (tutor_id, nombre, edad_registro, fecha_nacimiento, relacion, alergias)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
```
### Cambiar teléfono del tutor
```sql
UPDATE tutores SET telefono = $1 WHERE id = $2 RETURNING *;
```
(El índice UNIQUE rechaza el update si el nuevo número ya está en uso. El API debe capturar el error `23505` y devolver 409.)
---
## Seed data opcional (para desarrollo local)
Útil para probar el flujo de "Ya tengo cuenta":
```sql
-- Ejecutar SOLO en desarrollo
INSERT INTO tutores (nombre, telefono, correo) VALUES
('Luis Wonderloo', '2222392995', ''),
('Valeria Wonderloo', '2211173907', '');
-- Niños de Luis
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 1 Wonderloo', 6, 'Papá' FROM tutores WHERE telefono = '2222392995';
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 2 Wonderloo', 4, 'Papá' FROM tutores WHERE telefono = '2222392995';
-- Niños de Valeria
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 1 Wonderloo', 5, 'Mamá' FROM tutores WHERE telefono = '2211173907';
INSERT INTO ninos (tutor_id, nombre, edad_registro, relacion)
SELECT id, 'Niño 2 Wonderloo', 3, 'Mamá' FROM tutores WHERE telefono = '2211173907';
```
+381
View File
@@ -0,0 +1,381 @@
# 02 — API Spec
**Base URL en producción:** `https://registro.wonderlooindoorpark.com/api`
**Base URL local:** `http://localhost:3001/api`
**Formato:** JSON en request y response.
**Errores:** siempre devuelven `{ "error": string, "code": string }` con el status HTTP apropiado.
---
## Endpoints
### `GET /api/health`
Health check. Retorna `{ "status": "ok", "timestamp": "..." }`.
---
### `GET /api/precios`
Retorna precios vigentes.
**Response 200:**
```json
{
"nino_hora": 235,
"nino_daypass": 285,
"adulto_hora": 99,
"adulto_daypass": 199,
"hora_extra": 55,
"calcetas": 49
}
```
---
### `POST /api/tutores/lookup`
Busca tutor por teléfono. Retorna datos completos + niños activos.
**Request:**
```json
{ "telefono": "2222392995" }
```
**Response 200 (encontrado):**
```json
{
"id": "uuid-del-tutor",
"nombre": "Luis Wonderloo",
"telefono": "2222392995",
"correo": "",
"total_visitas": 3,
"ultima_visita": "2026-04-15T19:30:00Z",
"primera_visita": "2026-01-10T15:00:00Z",
"ninos": [
{
"id": "uuid-nino-1",
"nombre": "Niño 1 Wonderloo",
"edad": 6,
"fecha_nacimiento": null,
"relacion": "Papá",
"alergias": ""
}
]
}
```
**Response 404 (no encontrado):**
```json
{ "error": "Tutor no encontrado", "code": "TUTOR_NOT_FOUND" }
```
---
### `POST /api/tutores`
Crea un tutor nuevo con sus niños. Para flujo "Crear cuenta".
**Request:**
```json
{
"nombre": "María García López",
"telefono": "2211234567",
"correo": "maria@correo.com",
"ninos": [
{
"nombre": "Sofía García",
"edad": 5,
"fecha_nacimiento": "2021-03-15",
"relacion": "Mamá",
"alergias": ""
}
]
}
```
**Response 201:**
```json
{
"id": "uuid-del-tutor",
"nombre": "María García López",
"telefono": "2211234567",
"correo": "maria@correo.com",
"ninos": [
{ "id": "uuid-nino-1", "nombre": "Sofía García", "edad": 5, ... }
]
}
```
**Response 409 (teléfono ya existe):**
```json
{ "error": "El teléfono ya está registrado", "code": "PHONE_ALREADY_EXISTS" }
```
**Response 400 (datos inválidos):**
```json
{ "error": "Se requiere al menos un niño", "code": "VALIDATION_ERROR" }
```
---
### `PATCH /api/tutores/:id`
Actualiza datos del tutor. Caso de uso principal: cambio de número de WhatsApp.
**Request:**
```json
{ "telefono": "2219999999" }
```
**Response 200:**
```json
{
"id": "uuid-del-tutor",
"telefono": "2219999999",
...
}
```
**Response 409 (el nuevo teléfono ya está en uso por otro tutor):**
```json
{ "error": "El teléfono ya está en uso", "code": "PHONE_CONFLICT" }
```
---
### `POST /api/tutores/:id/ninos`
Agrega un niño nuevo a un tutor existente. Se usa desde el flujo "Ya tengo cuenta" cuando el tutor quiere registrar a un hijo adicional.
**Request:**
```json
{
"nombre": "Niño 3 Wonderloo",
"edad": 2,
"fecha_nacimiento": "2024-01-15",
"relacion": "Papá",
"alergias": ""
}
```
**Response 201:**
```json
{
"id": "uuid-del-nuevo-nino",
"tutor_id": "uuid-tutor",
"nombre": "Niño 3 Wonderloo",
"edad": 2,
...
}
```
---
### `POST /api/visitas`
**El endpoint principal.** Crea una visita y la asocia con los niños seleccionados.
Dispara el sync a Google Sheets (fire-and-forget).
**Request:**
```json
{
"tutor_id": "uuid-del-tutor",
"nino_ids": ["uuid-nino-1", "uuid-nino-2"],
"tipo_servicio": "daypass",
"metodo_pago": "mostrador",
"firma_base64": "data:image/png;base64,iVBORw0KGgo..."
}
```
**Validaciones:**
- `tipo_servicio` debe ser `"hora"` o `"daypass"`
- `metodo_pago` debe ser `"mostrador"` o `"applepay"`
- `nino_ids` debe tener al menos 1 elemento
- `firma_base64` no puede estar vacío
**Response 201:**
```json
{
"id": "uuid-de-la-visita",
"tutor_id": "uuid-del-tutor",
"tipo_servicio": "daypass",
"metodo_pago": "mostrador",
"hora_entrada": "2026-04-24T18:35:00Z",
"num_visita_del_tutor": 4,
"ninos_en_visita": [
{ "id": "uuid-nino-1", "nombre": "Niño 1 Wonderloo" },
{ "id": "uuid-nino-2", "nombre": "Niño 2 Wonderloo" }
]
}
```
**Response 400 (validación):**
```json
{ "error": "Se requiere al menos un niño seleccionado", "code": "VALIDATION_ERROR" }
```
**Response 404 (tutor/niño no existe):**
```json
{ "error": "Uno o más niños no existen o no pertenecen a este tutor", "code": "INVALID_NINOS" }
```
---
## Flujo completo desde el frontend
### Escenario A: Tutor nuevo
```
1. POST /api/tutores
body: { nombre, telefono, correo, ninos: [...] }
→ response: { id, ninos: [{ id, ... }] }
2. POST /api/visitas
body: {
tutor_id: id del paso 1,
nino_ids: todos los ids del paso 1,
tipo_servicio, metodo_pago, firma_base64
}
→ response: { id de visita }
```
### Escenario B: Tutor de regreso
```
1. POST /api/tutores/lookup
body: { telefono }
→ response: { id, ninos: [...], total_visitas, ultima_visita, ... }
2. (opcional) PATCH /api/tutores/:id si cambió el teléfono
3. (opcional) POST /api/tutores/:id/ninos si quiere agregar un niño nuevo
→ response: { id del nuevo niño }
4. POST /api/visitas
body: {
tutor_id,
nino_ids: solo los seleccionados en checkboxes,
tipo_servicio, metodo_pago, firma_base64
}
```
---
## Implementación de `services/sheets-sync.js`
Se ejecuta **después** de un INSERT exitoso en `visitas`. Fire-and-forget, no bloquea la respuesta al cliente.
```javascript
// backend/src/services/sheets-sync.js
import { request } from 'node:https';
import { URL } from 'node:url';
import { config } from '../config.js';
export function syncVisitaToSheets(payload) {
if (!config.sheetsSyncEnabled || !config.sheetsWebhookUrl) {
return;
}
try {
const url = new URL(config.sheetsWebhookUrl);
const body = JSON.stringify(payload);
const req = request(
{
method: 'POST',
hostname: url.hostname,
path: url.pathname + url.search,
headers: {
'Content-Type': 'text/plain;charset=utf-8',
'Content-Length': Buffer.byteLength(body),
},
timeout: 5000,
},
(res) => {
// Drenamos para liberar el socket, no nos importa el contenido
res.resume();
}
);
req.on('error', (err) => {
console.warn('[sheets-sync] Error (no crítico):', err.message);
});
req.on('timeout', () => {
req.destroy();
console.warn('[sheets-sync] Timeout (no crítico)');
});
req.write(body);
req.end();
} catch (err) {
console.warn('[sheets-sync] Excepción (no crítico):', err.message);
}
}
```
**Payload que se envía** (mismo formato que ya espera el Apps Script existente):
```json
{
"fecha": "24/04/2026",
"hora": "14:35",
"tutor_nombre": "Luis Wonderloo",
"tutor_telefono": "2222392995",
"tutor_correo": "",
"tipo_servicio": "daypass",
"metodo_pago": "mostrador",
"ninos": [
{ "nombre": "Niño 1", "edad": 6, "relacion": "Papá", "alergias": "" }
],
"todos_ninos": [
{ "nombre": "Niño 1", "edad": 6 },
{ "nombre": "Niño 2", "edad": 4 }
],
"num_visita": 4,
"firma_capturada": true
}
```
---
## Notas de implementación para Fastify
- Usa **JSON Schema** en la definición de rutas para validar request bodies automáticamente.
- Usa **transacciones** (`BEGIN`/`COMMIT`) para operaciones que tocan múltiples tablas (crear tutor + niños + visita + visita_ninos).
- Usa **prepared statements** del driver `pg` para evitar inyección.
- El error `23505` de Postgres (unique violation) en `telefono` debe mapearse a HTTP 409.
### Ejemplo de ruta con validación
```javascript
// backend/src/routes/tutores.js
export default async function (fastify) {
fastify.post('/tutores/lookup', {
schema: {
body: {
type: 'object',
required: ['telefono'],
properties: {
telefono: { type: 'string', pattern: '^[0-9]{10}$' }
}
}
},
handler: async (request, reply) => {
const { telefono } = request.body;
const tutor = await fastify.db.getTutorByPhone(telefono);
if (!tutor) {
return reply.code(404).send({
error: 'Tutor no encontrado',
code: 'TUTOR_NOT_FOUND'
});
}
return tutor;
}
});
}
```
+375
View File
@@ -0,0 +1,375 @@
# 03 — Deploy al VPS de Collina
Guía paso a paso para dejar el sistema corriendo en producción.
---
## 0. Pre-requisitos
- VPS con Ubuntu 22.04 LTS (o similar)
- Acceso SSH con usuario sudoer
- Dominio `wonderloo.collinasystems.com.mx` ya apuntando al VPS (ya existe, ahí vive el demo actual)
- El cliente (Wonderloo) debe haber creado el CNAME para `registro.wonderlooindoorpark.com` apuntando al VPS. Ver `docs/04-DNS.md`.
---
## 1. Instalar dependencias en el host
```bash
# Actualizar sistema
sudo apt update && sudo apt upgrade -y
# Docker + Docker Compose
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker $USER
# Cerrar sesión y volver a entrar para que el cambio de grupo aplique
# Nginx (en el host, NO en Docker)
sudo apt install -y nginx
# Certbot para SSL
sudo apt install -y certbot python3-certbot-nginx
# Utilidades
sudo apt install -y git curl jq
```
---
## 2. Clonar el repo
```bash
# Como user sudoer (no root)
cd ~
git clone https://github.com/collina-systems/wonderloo-checkin.git
cd wonderloo-checkin
```
---
## 3. Configurar variables de entorno
```bash
cp .env.example .env
nano .env
```
Rellenar con los valores de producción:
```bash
NODE_ENV=production
API_PORT=3001
API_HOST=0.0.0.0
LOG_LEVEL=info
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=wonderloo
POSTGRES_USER=wonderloo_app
POSTGRES_PASSWORD=<generar con: openssl rand -base64 32>
SHEETS_WEBHOOK_URL=https://script.google.com/macros/s/XXXX/exec
SHEETS_SYNC_ENABLED=true
ALLOWED_ORIGINS=https://registro.wonderlooindoorpark.com
```
---
## 4. `docker-compose.yml`
```yaml
services:
postgres:
image: postgres:16-alpine
container_name: wonderloo_postgres
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./backend/src/db/migrations:/docker-entrypoint-initdb.d:ro
ports:
- "127.0.0.1:5432:5432" # solo localhost, no expuesto público
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
api:
build:
context: ./backend
dockerfile: Dockerfile
container_name: wonderloo_api
restart: unless-stopped
env_file: .env
depends_on:
postgres:
condition: service_healthy
ports:
- "127.0.0.1:3001:3001" # solo localhost, Nginx hace el proxy
volumes:
postgres_data:
driver: local
```
**Notas de seguridad:**
- Los puertos de Postgres y API solo escuchan en `127.0.0.1` — **nunca** expuestos públicamente. El único puerto público es 80/443 vía Nginx.
- Las migraciones SQL se ejecutan **automáticamente** la primera vez que arranca el container de Postgres (por el volumen `/docker-entrypoint-initdb.d`).
---
## 5. `backend/Dockerfile`
```dockerfile
FROM node:20-alpine AS base
WORKDIR /app
# Dependencias
COPY package*.json ./
RUN npm ci --omit=dev
# Código
COPY src ./src
ENV NODE_ENV=production
EXPOSE 3001
USER node
CMD ["node", "src/index.js"]
```
---
## 6. Configurar Nginx
### Archivo: `/etc/nginx/sites-available/registro.wonderlooindoorpark.com`
```nginx
server {
listen 80;
server_name registro.wonderlooindoorpark.com;
# Redirect a HTTPS — certbot lo agregará automáticamente pero lo dejamos explícito
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name registro.wonderlooindoorpark.com;
# Los certificados los genera certbot más abajo
ssl_certificate /etc/letsencrypt/live/registro.wonderlooindoorpark.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/registro.wonderlooindoorpark.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# Headers de seguridad básicos
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# ── Frontend estático ──
root /home/USUARIO/wonderloo-checkin/frontend;
index wonderloo.html;
location = / {
try_files /wonderloo.html =404;
}
location / {
try_files $uri $uri/ /wonderloo.html =404;
}
# ── API proxy ──
location /api/ {
proxy_pass http://127.0.0.1:3001/api/;
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_read_timeout 30s;
}
# Limits razonables (firma base64 puede pesar algunos KB)
client_max_body_size 2M;
}
```
**Reemplazar `USUARIO`** con el usuario real donde está clonado el repo.
### Activar el sitio
```bash
sudo ln -s /etc/nginx/sites-available/registro.wonderlooindoorpark.com \
/etc/nginx/sites-enabled/
sudo nginx -t # validar sintaxis
```
---
## 7. Obtener certificado SSL
**Pre-requisito:** el DNS de `registro.wonderlooindoorpark.com` ya debe apuntar al VPS (puede tardar hasta 48h tras crear el CNAME — usualmente 5 minutos).
Verificar con:
```bash
dig +short registro.wonderlooindoorpark.com
# Debe devolver la IP del VPS
```
Obtener el certificado:
```bash
sudo certbot --nginx -d registro.wonderlooindoorpark.com \
--non-interactive --agree-tos \
--email devops@collinasystems.com.mx
# Verificar auto-renewal
sudo systemctl status certbot.timer
```
---
## 8. Levantar los containers
```bash
cd ~/wonderloo-checkin
docker compose up -d --build
docker compose ps # debe mostrar ambos "running" y "healthy"
docker compose logs -f api # ver logs del API
```
Primera vez: las migraciones corren automáticamente al crear la DB. Revisar:
```bash
docker compose exec postgres psql -U wonderloo_app -d wonderloo -c "\dt"
# Debe listar: tutores, ninos, visitas, visita_ninos, precios, feedback
```
---
## 9. Recargar Nginx
```bash
sudo systemctl reload nginx
```
---
## 10. Smoke test
```bash
# Health check (desde el VPS mismo)
curl -s https://registro.wonderlooindoorpark.com/api/health | jq
# Debe devolver:
# { "status": "ok", "timestamp": "..." }
# Precios
curl -s https://registro.wonderlooindoorpark.com/api/precios | jq
# Lookup (debe devolver 404 con mensaje claro)
curl -s -X POST https://registro.wonderlooindoorpark.com/api/tutores/lookup \
-H "Content-Type: application/json" \
-d '{"telefono":"0000000000"}' | jq
```
Desde un navegador: abrir `https://registro.wonderlooindoorpark.com` — debe cargar el formulario. DevTools → Network: las llamadas a `/api/*` deben retornar 200.
---
## 11. Deploy de cambios posteriores
Script `deploy/deploy.sh`:
```bash
#!/bin/bash
set -e
cd ~/wonderloo-checkin
git pull origin main
# Si cambió el frontend, solo reload de nginx
# Si cambió el backend, rebuild + restart
docker compose build api
docker compose up -d --no-deps api
echo "✓ Deploy completo"
```
Hacerlo ejecutable: `chmod +x deploy/deploy.sh`
Uso: `./deploy/deploy.sh`
---
## 12. Backup de la DB
**Automatizable con cron.** Por ahora, manual:
```bash
# Dump completo
docker compose exec postgres pg_dump -U wonderloo_app wonderloo > backup-$(date +%F).sql
# Restore (si hiciera falta)
docker compose exec -T postgres psql -U wonderloo_app wonderloo < backup-2026-04-24.sql
```
Idealmente:
```bash
# /etc/cron.d/wonderloo-backup
0 3 * * * user cd /home/user/wonderloo-checkin && docker compose exec -T postgres pg_dump -U wonderloo_app wonderloo | gzip > /home/user/backups/wonderloo-$(date +\%F).sql.gz
```
---
## 13. Logs
```bash
# API en tiempo real
docker compose logs -f api
# Todo
docker compose logs -f
# Nginx
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
```
---
## 14. Troubleshooting
| Problema | Diagnóstico |
|----------|-------------|
| `curl /api/health` da 502 | El container del API no está corriendo (`docker compose ps`) o Nginx no puede conectar al puerto 3001. |
| `curl /api/health` da 404 | Nginx no tiene el `location /api/` configurado o no se recargó. |
| El HTML carga pero las llamadas a `/api/*` fallan con CORS | `ALLOWED_ORIGINS` en `.env` no incluye el dominio correcto. |
| Registros no aparecen en Sheets | Revisar logs del API: `docker compose logs api | grep sheets`. Verificar `SHEETS_WEBHOOK_URL` en `.env`. |
| Migraciones no corrieron | Eliminar el volumen: `docker compose down -v && docker compose up -d`. Esto recrea la DB desde cero. |
| SSL expiró | `sudo certbot renew` y revisar por qué falló el auto-renewal. |
---
## 15. Hardening opcional (post-MVP)
- Fail2ban para proteger SSH
- UFW con solo puertos 22, 80, 443 abiertos
- Deshabilitar login root por SSH, solo keys
- Backups automáticos con cron o restic
- Monitoring con Uptime Kuma o healthchecks.io
- Rate limiting en Nginx para `/api/*`
Nada de esto bloquea el demo del jueves.
+91
View File
@@ -0,0 +1,91 @@
# 04 — DNS Setup (instrucciones para Wonderloo)
> Este documento es para compartir con el cliente (dueña de Wonderloo) o con quien administra su dominio.
> El objetivo: apuntar `registro.wonderlooindoorpark.com` al servidor de Collina Systems.
---
## Qué necesitamos que configures
Un registro **CNAME** (o **A**) en el DNS de `wonderlooindoorpark.com`.
### Opción A: Si usas Wix (el sitio wonderlooindoorpark.com está hecho en Wix)
1. Ingresa a tu cuenta de Wix → **Dominios**
2. Selecciona `wonderlooindoorpark.com`
3. Click en **"Avanzado"** → **"Editar registros DNS"** o **"Administrar DNS"**
4. En la sección de **CNAME**, agregar uno nuevo:
| Campo | Valor |
|-------|-------|
| Tipo | CNAME |
| Nombre / Host | `registro` |
| Apunta a / Destino | `wonderloo.collinasystems.com.mx` |
| TTL | 3600 (o el default) |
5. Guardar.
### Opción B: Si el dominio está en otro proveedor (GoDaddy, Namecheap, Cloudflare, etc.)
Mismo concepto: agregar un CNAME con:
- **Nombre / Host:** `registro`
- **Valor / Destino:** `wonderloo.collinasystems.com.mx`
### Opción C: Si el proveedor no permite CNAME en subdominio
(Raro, pero pasa.) Usar un registro tipo **A** apuntando a la IP del servidor de Collina:
- **Nombre / Host:** `registro`
- **Valor:** (la IP pública del VPS — Collina te la proporciona)
---
## Cuánto tarda en propagarse
Entre 5 minutos y 48 horas, dependiendo del proveedor y tu red. La mayoría de las veces es casi inmediato.
### Cómo verificar que ya funciona
Desde una terminal (Mac/Linux):
```bash
dig +short registro.wonderlooindoorpark.com
```
O desde cualquier navegador, entrar a:
```
https://www.whatsmydns.net/#CNAME/registro.wonderlooindoorpark.com
```
Cuando muestre `wonderloo.collinasystems.com.mx` (o una IP) como respuesta, está listo.
---
## Qué pasa después
Una vez que el DNS propaga, Collina:
1. Genera el certificado SSL automáticamente (Let's Encrypt)
2. Activa el sitio en `https://registro.wonderlooindoorpark.com`
3. Confirma contigo que todo está funcionando
---
## Contacto
Cualquier duda con esta configuración, escríbenos a **soporte@collinasystems.com.mx** (o al correo que acordemos) y te ayudamos en tiempo real.
---
## Preguntas frecuentes
**¿Esto afecta mi página principal `wonderlooindoorpark.com`?**
No. Solo estás creando un subdominio nuevo (`registro.wonderlooindoorpark.com`). Tu página principal sigue funcionando exactamente igual en Wix.
**¿Puedo cambiar después a otro proveedor si quiero?**
Sí. El sistema de check-in es portable. Si en el futuro quieres moverlo, se actualiza el CNAME y listo.
**¿Qué pasa si alguien entra directo a `registro.wonderlooindoorpark.com` desde su navegador?**
Ve el formulario de registro. Es el mismo que se abre al escanear el QR.
**¿El sistema funciona si el internet del parque se cae?**
El sistema requiere internet. Si el WiFi del parque se cae, el iPad del mostrador no puede registrar. Como respaldo se puede seguir usando la responsiva en papel temporalmente.
+35
View File
@@ -0,0 +1,35 @@
# Prompt inicial para Claude Code
Copia este bloque entero y pégalo como primer mensaje en Claude Code. Ten listos en la carpeta de trabajo: `00-BRIEF.md`, `01-SCHEMA.md`, `02-API.md`, `03-DEPLOY.md`, `04-DNS.md` y `wonderloo.html`.
---
```
Voy a construir un sistema de check-in digital para Wonderloo Indoor Park, un cliente de Collina Systems. Ya hay un demo estático funcionando en producción (wonderloo.html) que guarda en un Google Sheet. Ahora migramos a una arquitectura real con:
- Frontend HTML estático (modificación del existente)
- API Node.js + Fastify
- PostgreSQL self-hosted en Docker
- Google Sheets como espejo de lectura (el webhook existente se sigue usando, pero ahora llamado desde el backend)
- Deploy en un VPS propio de Collina, servido en el subdominio del cliente (registro.wonderlooindoorpark.com)
Los archivos en esta carpeta son el brief completo:
- 00-BRIEF.md — LÉELO PRIMERO. Contexto, arquitectura, stack, estructura de repo, orden de construcción.
- 01-SCHEMA.md — SQL completo de la DB y explicación por tabla.
- 02-API.md — Spec de endpoints con requests/responses.
- 03-DEPLOY.md — Guía paso a paso del deploy al VPS.
- 04-DNS.md — Documentación para el cliente (no es para construir, es para compartir).
- wonderloo.html — El frontend existente que se modifica (no se re-escribe).
Por favor lee los 4 primeros archivos en orden, luego:
1. Crea la estructura de carpetas del repo como está en 00-BRIEF sección 4.
2. Empieza con la Fase A del build order (backend local, secciones 1–7 de la Fase A en el brief).
3. Después de cada sub-tarea, muéstrame qué hiciste y pídeme confirmación antes de seguir.
No hagas deploy al VPS todavía. Primero terminamos backend + frontend en local y los probamos con docker compose. Cuando eso funcione, pasamos a Fase C.
Trabajo con: Node 20, Docker, VS Code. El VPS de Collina ya existe y tiene dominio wonderloo.collinasystems.com.mx funcionando.
```
```
+736
View File
@@ -0,0 +1,736 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Wonderloo Indoor Park</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.2/babel.min.js"></script>
</head>
<body style="margin:0;padding:0;">
<div id="root"></div>
<script type="text/babel" data-presets="react">
const { useState, useRef, useEffect } = React;
const COLORS = {
warmBg: "#FFF9F0", cream: "#FFF5E6", bark: "#8B6914",
leaf: "#4CAF50", leafDark: "#2E7D32", sky: "#E3F2FD",
pink: "#E91E63", pinkSoft: "#FCE4EC", blue: "#1976D2",
orange: "#FF9800", orangeSoft: "#FFF3E0", text: "#3E2723",
textLight: "#6D4C41", border: "#D7CCC8", white: "#FFFFFF",
error: "#D32F2F", success: "#2E7D32",
};
// ═══════════════════════════════════════════════════════════
// API CONFIG
// En producción el HTML vive bajo el mismo host que /api.
// En dev (localhost o file://) apunta a http://localhost:3001.
// ═══════════════════════════════════════════════════════════
const API_BASE = (() => {
if (window.location.protocol === "file:" || window.location.origin.includes("localhost")) {
return "http://localhost:3001/api";
}
return `${window.location.origin}/api`;
})();
// Debug — útil para validar que el origin/protocol se resuelven como esperamos
console.log("[wonderloo] origin:", window.location.origin, "protocol:", window.location.protocol, "API_BASE:", API_BASE);
async function apiFetch(path, options = {}) {
const url = `${API_BASE}${path}`;
const res = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
...(options.headers || {}),
},
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code;
err.status = res.status;
throw err;
}
return data;
}
// Convierte un tutor del API al shape que el UI espera (children, visitas, ultimaVisita)
function normalizeTutor(api) {
return {
id: api.id,
nombre: api.nombre,
telefono: api.telefono,
correo: api.correo || "",
children: (api.ninos || []).map((n) => ({
id: n.id,
nombre: n.nombre,
edad: String(n.edad ?? ""),
cumple: n.fecha_nacimiento || "",
alergias: n.alergias || "",
relacion: n.relacion || "",
})),
visitas: api.total_visitas ?? 0,
ultimaVisita: api.ultima_visita
? new Date(api.ultima_visita).toLocaleDateString("es-MX", { year: "numeric", month: "long", day: "numeric" })
: null,
};
}
const RELACIONES = [
{ value: "Mamá", label: "Mamá" }, { value: "Papá", label: "Papá" },
{ value: "Abuelo/a", label: "Abuelo/a" }, { value: "Tío/a", label: "Tío/a" },
{ value: "Nana", label: "Nana" }, { value: "Hermano/a", label: "Hermano/a mayor" },
{ value: "Otro", label: "Otro tutor" },
];
const TreeIcon = ({ color1, color2, size = 40 }) => (
<svg width={size} height={size} viewBox="0 0 40 40" fill="none">
<rect x="18" y="28" width="4" height="10" rx="1" fill="#8B6914" />
<circle cx="20" cy="18" r="12" fill={color1} opacity="0.9" />
<circle cx="14" cy="14" r="7" fill={color2} opacity="0.8" />
<circle cx="26" cy="16" r="6" fill={color1} opacity="0.7" />
</svg>
);
const WonderlooLogo = () => (
<div style={{ display: "flex", alignItems: "flex-end", gap: "3px", justifyContent: "center" }}>
<TreeIcon color1="#1976D2" color2="#0D47A1" size={28} />
<TreeIcon color1="#E91E63" color2="#AD1457" size={34} />
<TreeIcon color1="#FF9800" color2="#F57F17" size={30} />
<TreeIcon color1="#4CAF50" color2="#2E7D32" size={26} />
</div>
);
const ProgressDots = ({ current, total }) => (
<div style={{ display: "flex", gap: "8px", justifyContent: "center", margin: "16px 0" }}>
{Array.from({ length: total }, (_, i) => (
<div key={i} style={{ width: i === current ? "28px" : "10px", height: "10px", borderRadius: "5px", background: i === current ? COLORS.bark : i < current ? COLORS.leaf : COLORS.border, transition: "all 0.4s cubic-bezier(0.4, 0, 0.2, 1)" }} />
))}
</div>
);
const SignaturePad = ({ onSign }) => {
const canvasRef = useRef(null);
const [isDrawing, setIsDrawing] = useState(false);
const [hasContent, setHasContent] = useState(false);
useEffect(() => { const c = canvasRef.current; if (!c) return; const ctx = c.getContext("2d"); const r = c.getBoundingClientRect(); c.width = r.width * 2; c.height = r.height * 2; ctx.scale(2, 2); ctx.strokeStyle = COLORS.text; ctx.lineWidth = 2.5; ctx.lineCap = "round"; ctx.lineJoin = "round"; }, []);
const getPos = (e) => { const r = canvasRef.current.getBoundingClientRect(); const t = e.touches ? e.touches[0] : e; return { x: t.clientX - r.left, y: t.clientY - r.top }; };
const startDraw = (e) => { e.preventDefault(); const ctx = canvasRef.current.getContext("2d"); const p = getPos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); setIsDrawing(true); };
const draw = (e) => { if (!isDrawing) return; e.preventDefault(); const ctx = canvasRef.current.getContext("2d"); const p = getPos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); setHasContent(true); };
const endDraw = (e) => { if (!isDrawing) return; e.preventDefault(); setIsDrawing(false); if (hasContent) onSign(canvasRef.current.toDataURL()); };
const clear = () => { const c = canvasRef.current; c.getContext("2d").clearRect(0, 0, c.width, c.height); setHasContent(false); onSign(null); };
return (
<div>
<div style={{ position: "relative", border: `2px dashed ${COLORS.border}`, borderRadius: "16px", overflow: "hidden", background: COLORS.white, touchAction: "none" }}>
<canvas ref={canvasRef} style={{ width: "100%", height: "150px", cursor: "crosshair", display: "block" }} onMouseDown={startDraw} onMouseMove={draw} onMouseUp={endDraw} onMouseLeave={endDraw} onTouchStart={startDraw} onTouchMove={draw} onTouchEnd={endDraw} />
{!hasContent && <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none", color: COLORS.border, fontFamily: "'Nunito', sans-serif", fontSize: "16px" }}>Firma aquí con tu dedo ✍️</div>}
</div>
{hasContent && <button onClick={clear} style={{ marginTop: "8px", background: "none", border: "none", color: COLORS.error, fontFamily: "'Nunito', sans-serif", fontSize: "14px", cursor: "pointer", padding: "4px 8px" }}>Borrar firma</button>}
</div>
);
};
const InputField = ({ label, icon, value, onChange, type = "text", placeholder, required = true, options, helperText, large }) => (
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: "15px", color: COLORS.text, marginBottom: "6px" }}>
{icon && <span style={{ marginRight: "6px" }}>{icon}</span>}{label}
{!required && <span style={{ fontWeight: 400, color: COLORS.textLight, fontSize: "13px" }}> (opcional)</span>}
</label>
{options ? (
<select value={value} onChange={(e) => onChange(e.target.value)} style={{ width: "100%", padding: "14px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: "17px", fontFamily: "'Nunito', sans-serif", color: value ? COLORS.text : COLORS.textLight, background: COLORS.white, appearance: "none", backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238B6914' d='M6 8L1 3h10z'/%3E%3C/svg%3E\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 16px center", outline: "none", boxSizing: "border-box" }}>
<option value="">{placeholder || "Selecciona..."}</option>
{options.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
</select>
) : (
<input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={{ width: "100%", padding: large ? "18px 16px" : "14px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: large ? "22px" : "17px", fontFamily: "'Nunito', sans-serif", color: COLORS.text, fontWeight: large ? 700 : 400, background: COLORS.white, outline: "none", boxSizing: "border-box", textAlign: large ? "center" : "left", letterSpacing: large ? "2px" : "normal", transition: "border-color 0.2s" }} onFocus={(e) => e.target.style.borderColor = COLORS.bark} onBlur={(e) => e.target.style.borderColor = COLORS.border} />
)}
{helperText && <p style={{ margin: "4px 0 0 4px", fontSize: "13px", color: COLORS.textLight, fontFamily: "'Nunito', sans-serif" }}>{helperText}</p>}
</div>
);
const Btn = ({ children, onClick, disabled, variant = "primary" }) => {
const S = { primary: { bg: COLORS.bark, c: COLORS.white, sh: "0 4px 16px rgba(139,105,20,0.3)", bd: "none" }, success: { bg: COLORS.leaf, c: COLORS.white, sh: "0 4px 16px rgba(76,175,80,0.3)", bd: "none" }, outline: { bg: "transparent", c: COLORS.bark, sh: "none", bd: `2px solid ${COLORS.bark}` }, subtle: { bg: COLORS.cream, c: COLORS.bark, sh: "none", bd: "none" } };
const s = S[variant] || S.primary;
return <button onClick={onClick} disabled={disabled} style={{ width: "100%", padding: "16px 24px", borderRadius: "16px", background: disabled ? COLORS.border : s.bg, color: disabled ? COLORS.textLight : s.c, border: disabled ? "none" : s.bd, fontSize: "18px", fontWeight: 800, fontFamily: "'Nunito', sans-serif", cursor: disabled ? "not-allowed" : "pointer", boxShadow: disabled ? "none" : s.sh, transition: "all 0.2s ease", letterSpacing: "0.3px" }}>{children}</button>;
};
const Card = ({ children, style }) => <div style={{ background: COLORS.white, borderRadius: "20px", padding: "20px", boxShadow: "0 2px 12px rgba(0,0,0,0.06)", ...style }}>{children}</div>;
const RESPONSIVA = `Por medio de la presente, manifiesto que soy padre, madre o tutor del menor antes mencionado y autorizo su ingreso a la ludoteca Wonderloo Indoor Park®, ubicada en Paseo Opera número 11, Distrito Sonata en Lomas de Angelópolis II, Locales 7, 8, 9, en la Ciudad de San Andrés Cholula, Puebla C.P. 72830.
Declaro bajo protesta de decir verdad que:
1. Entiendo y acepto que la ludoteca es un espacio destinado a la recreación infantil, donde el personal encargado supervisará a los niños. Sin embargo, dicha supervisión no exime ni sustituye la responsabilidad del padre, madre o tutor legal.
2. Acepto que el menor a mi cargo deberá cumplir con el reglamento interno de la ludoteca y que, en caso de cualquier incidente, seré contactado de inmediato.
3. Libero de toda responsabilidad a la ludoteca y a su personal por cualquier accidente que pudiera ocurrir dentro de sus instalaciones.
4. En caso de emergencia, comprendo y acepto que el personal de la ludoteca no cuenta con la capacitación para brindar atención médica especializada ni para realizar el traslado del menor a un centro de salud en caso de ser necesario.
5. Acepto y estoy de acuerdo con el reglamento del establecimiento así como los reglamentos internos de cada área.`;
const Fonts = () => <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet" />;
const Shell = ({ children: ch, bg }) => (
<div style={{ minHeight: "100vh", background: bg || `linear-gradient(180deg, ${COLORS.warmBg} 0%, ${COLORS.cream} 100%)`, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "24px", fontFamily: "'Nunito', sans-serif", boxSizing: "border-box" }}>
<Fonts />
<div style={{ maxWidth: "420px", width: "100%", animation: "fadeUp 0.5s ease-out" }}>{ch}</div>
<style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } } @keyframes popIn { from { transform:scale(0); } to { transform:scale(1); } } * { -webkit-tap-highlight-color: transparent; } input, select { font-size: 17px !important; }`}</style>
</div>
);
const ToastBanner = ({ toast }) => (
<div style={{
position: "fixed", bottom: "100px", left: "16px", right: "16px",
maxWidth: "420px", margin: "0 auto",
background: toast.type === "success" ? COLORS.leaf : COLORS.error,
color: COLORS.white, padding: "14px 18px", borderRadius: "14px",
boxShadow: "0 8px 32px rgba(0,0,0,0.25)",
fontFamily: "'Nunito', sans-serif", fontSize: "14px", fontWeight: 700,
textAlign: "center", zIndex: 200,
animation: "fadeUp 0.3s ease-out"
}}>
{toast.message}
</div>
);
function WonderlooCheckin() {
const [mode, setMode] = useState(null);
const [step, setStep] = useState(0);
const [animDir, setAnimDir] = useState("right");
const [lookupPhone, setLookupPhone] = useState("");
const [foundUser, setFoundUser] = useState(null);
const [lookupError, setLookupError] = useState(false);
const [lookupLoading, setLookupLoading] = useState(false);
const [selectedChildren, setSelectedChildren] = useState([]);
const [addingNewChild, setAddingNewChild] = useState(false);
const [newChildForReturn, setNewChildForReturn] = useState({ nombre: "", edad: "", cumple: "", alergias: "", relacion: "" });
const [editingPhone, setEditingPhone] = useState(false);
const [newPhone, setNewPhone] = useState("");
const [tutorData, setTutorData] = useState({ nombre: "", telefono: "", correo: "" });
const [children, setChildren] = useState([{ nombre: "", edad: "", cumple: "", alergias: "", relacion: "" }]);
const [servicio, setServicio] = useState("");
const [metodoPago, setMetodoPago] = useState("");
const [aceptaResponsiva, setAceptaResponsiva] = useState(false);
const [signature, setSignature] = useState(null);
const [submitted, setSubmitted] = useState(false);
const [precios, setPrecios] = useState(null);
const [preciosLoading, setPreciosLoading] = useState(true);
const [toast, setToast] = useState(null);
const [submitLoading, setSubmitLoading] = useState(false);
const [currentTime] = useState(new Date().toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" }));
const [currentDate] = useState(new Date().toLocaleDateString("es-MX", { weekday: "long", year: "numeric", month: "long", day: "numeric" }));
useEffect(() => {
apiFetch("/precios")
.then((p) => setPrecios(p))
.catch(() => setToast({ message: "No pudimos cargar los precios. Recarga la página.", type: "error" }))
.finally(() => setPreciosLoading(false));
}, []);
useEffect(() => {
if (!toast) return;
const t = setTimeout(() => setToast(null), 4000);
return () => clearTimeout(t);
}, [toast]);
const resetAll = () => {
setSubmitted(false); setMode(null); setStep(0); setServicio(""); setMetodoPago("");
setSignature(null); setAceptaResponsiva(false); setFoundUser(null);
setLookupPhone(""); setLookupError(false); setSelectedChildren([]);
setAddingNewChild(false); setNewChildForReturn({ nombre: "", edad: "", cumple: "", alergias: "", relacion: "" });
setEditingPhone(false); setNewPhone("");
setTutorData({ nombre: "", telefono: "", correo: "" });
setChildren([{ nombre: "", edad: "", cumple: "", alergias: "", relacion: "" }]);
};
const goNext = () => { setAnimDir("right"); setStep(s => s + 1); };
const goBack = () => {
setAnimDir("left");
if (step === 0) { setMode(null); setFoundUser(null); setLookupPhone(""); setLookupError(false); setSelectedChildren([]); setEditingPhone(false); }
else setStep(s => s - 1);
};
const addChild = () => { if (children.length < 4) setChildren([...children, { nombre: "", edad: "", cumple: "", alergias: "", relacion: "" }]); };
const removeChild = (i) => { if (children.length > 1) setChildren(children.filter((_, idx) => idx !== i)); };
const updateChild = (i, f, v) => { const u = [...children]; u[i] = { ...u[i], [f]: v }; setChildren(u); };
const toggleChildSelection = (idx) => setSelectedChildren(prev => prev.includes(idx) ? prev.filter(i => i !== idx) : [...prev, idx]);
const handleLookup = async () => {
setLookupLoading(true);
setLookupError(false);
try {
const clean = lookupPhone.replace(/\D/g, "");
const apiTutor = await apiFetch("/tutores/lookup", {
method: "POST",
body: JSON.stringify({ telefono: clean }),
});
const tutor = normalizeTutor(apiTutor);
setFoundUser(tutor);
setSelectedChildren(tutor.children.map((_, i) => i));
} catch (err) {
if (err.status === 404) {
setLookupError(true);
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message || "Error inesperado", type: "error" });
}
} finally {
setLookupLoading(false);
}
};
const confirmAddNewChild = async () => {
if (!newChildForReturn.nombre || !newChildForReturn.edad || !newChildForReturn.relacion || !foundUser) return;
try {
const apiNino = await apiFetch(`/tutores/${foundUser.id}/ninos`, {
method: "POST",
body: JSON.stringify({
nombre: newChildForReturn.nombre,
edad: parseInt(newChildForReturn.edad, 10),
fecha_nacimiento: newChildForReturn.cumple || undefined,
relacion: newChildForReturn.relacion,
alergias: newChildForReturn.alergias || undefined,
}),
});
const newChild = {
id: apiNino.id,
nombre: apiNino.nombre,
edad: String(apiNino.edad ?? ""),
cumple: apiNino.fecha_nacimiento || "",
alergias: apiNino.alergias || "",
relacion: apiNino.relacion,
};
const newIdx = foundUser.children.length;
setFoundUser(prev => ({ ...prev, children: [...prev.children, newChild] }));
setSelectedChildren(prev => [...prev, newIdx]);
setNewChildForReturn({ nombre: "", edad: "", cumple: "", alergias: "", relacion: "" });
setAddingNewChild(false);
} catch (err) {
if (err.code === "MAX_CHILDREN_REACHED") {
setToast({ message: "Este tutor ya tiene el máximo de 4 niños activos.", type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message, type: "error" });
}
}
};
const confirmPhoneChange = async () => {
const clean = newPhone.replace(/\D/g, "");
if (clean.length < 10 || !foundUser) return;
try {
const apiTutor = await apiFetch(`/tutores/${foundUser.id}`, {
method: "PATCH",
body: JSON.stringify({ telefono: clean }),
});
setFoundUser(prev => ({ ...prev, telefono: apiTutor.telefono }));
setEditingPhone(false);
setNewPhone("");
} catch (err) {
if (err.code === "PHONE_CONFLICT") {
setToast({ message: "Ese número ya pertenece a otro tutor.", type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message, type: "error" });
}
}
};
const handleSubmit = async () => {
setSubmitLoading(true);
try {
let tutorId;
let ninoIds;
if (mode === "new") {
const clean = tutorData.telefono.replace(/\D/g, "");
const created = await apiFetch("/tutores", {
method: "POST",
body: JSON.stringify({
nombre: tutorData.nombre,
telefono: clean,
correo: tutorData.correo || "",
ninos: children.map((c) => ({
nombre: c.nombre,
edad: parseInt(c.edad, 10),
fecha_nacimiento: c.cumple || undefined,
relacion: c.relacion,
alergias: c.alergias || undefined,
})),
}),
});
tutorId = created.id;
ninoIds = created.ninos.map((n) => n.id);
} else if (foundUser) {
tutorId = foundUser.id;
ninoIds = selectedChildren.map((idx) => foundUser.children[idx].id);
}
await apiFetch("/visitas", {
method: "POST",
body: JSON.stringify({
tutor_id: tutorId,
nino_ids: ninoIds,
tipo_servicio: servicio,
metodo_pago: metodoPago,
firma_base64: signature,
}),
});
setSubmitted(true);
} catch (err) {
if (err.code === "PHONE_ALREADY_EXISTS") {
setToast({ message: 'Este teléfono ya está registrado. ¿Intenta con "Ya tengo cuenta"?', type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message || "Error inesperado", type: "error" });
}
} finally {
setSubmitLoading(false);
}
};
const newSteps = ["tutor", "children", "service", "responsiva"];
const retSteps = ["select_children", "service", "responsiva"];
const activeSteps = mode === "ret_confirmed" ? retSteps : newSteps;
const currentStepName = activeSteps[step];
const totalSteps = activeSteps.length;
const isLastStep = step === totalSteps - 1;
const activeChildren = mode === "ret_confirmed" ? (foundUser?.children || []).filter((_, i) => selectedChildren.includes(i)) : children;
const activeName = foundUser ? foundUser.nombre : tutorData.nombre;
const activePhone = foundUser ? foundUser.telefono : tutorData.telefono;
const canProceed = () => {
switch (currentStepName) {
case "tutor": return tutorData.nombre && tutorData.telefono;
case "children": return children.every(c => c.nombre && c.edad && c.relacion);
case "select_children": return selectedChildren.length > 0 && !addingNewChild;
case "service": return !!servicio && !!metodoPago;
case "responsiva": return aceptaResponsiva && signature;
default: return false;
}
};
if (preciosLoading) {
return (
<React.Fragment>
<Shell>
<div style={{ textAlign: "center" }}>
<div style={{ marginBottom: "20px" }}><WonderlooLogo /></div>
<h1 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "32px", fontWeight: 700, color: COLORS.text, margin: "0 0 2px 0" }}>wonderloo</h1>
<p style={{ fontSize: "13px", color: COLORS.textLight, margin: "0 0 28px 0", letterSpacing: "2.5px", textTransform: "uppercase", fontWeight: 600 }}>indoor park</p>
<p style={{ fontSize: "14px", color: COLORS.textLight }}>Cargando…</p>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === null) {
return (
<React.Fragment>
<Shell>
<div style={{ textAlign: "center" }}>
<div style={{ marginBottom: "20px" }}><WonderlooLogo /></div>
<h1 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "32px", fontWeight: 700, color: COLORS.text, margin: "0 0 2px 0" }}>wonderloo</h1>
<p style={{ fontSize: "13px", color: COLORS.textLight, margin: "0 0 36px 0", letterSpacing: "2.5px", textTransform: "uppercase", fontWeight: 600 }}>indoor park</p>
<Card style={{ padding: "28px 24px", marginBottom: "16px" }}>
<p style={{ fontSize: "22px", fontWeight: 800, color: COLORS.text, margin: "0 0 6px 0", fontFamily: "'Fredoka', sans-serif" }}>¡Bienvenidos! 🎉</p>
<p style={{ fontSize: "15px", color: COLORS.textLight, margin: "0 0 28px 0", lineHeight: 1.5 }}>Registra tu visita para que los pequeños puedan entrar a jugar</p>
<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
<Btn onClick={() => { setMode("new"); setStep(0); }}>Crear cuenta 🌟</Btn>
<Btn variant="outline" onClick={() => { setMode("returning"); setStep(0); }}>Ya tengo cuenta 📱</Btn>
</div>
</Card>
<p style={{ fontSize: "12px", color: COLORS.textLight, margin: 0 }}>{currentDate} · {currentTime}</p>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === "returning" && !foundUser) {
return (
<React.Fragment>
<Shell>
<button onClick={() => { setMode(null); setLookupPhone(""); setLookupError(false); }} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0", marginBottom: "12px" }}>← Inicio</button>
<Card style={{ padding: "28px 24px" }}>
<div style={{ textAlign: "center", marginBottom: "24px" }}>
<span style={{ fontSize: "48px" }}>📱</span>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "12px 0 6px 0" }}>¡Hola de nuevo!</h2>
<p style={{ fontSize: "15px", color: COLORS.textLight, margin: 0, lineHeight: 1.5 }}>Ingresa tu número de WhatsApp</p>
</div>
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: "15px", color: COLORS.text, marginBottom: "6px" }}>
<span style={{ marginRight: "6px" }}>📱</span>Tu número de WhatsApp
</label>
<input type="tel" value={lookupPhone} onChange={(e) => { setLookupPhone(e.target.value); setLookupError(false); }} placeholder="Ej: 221 123 4567" style={{ width: "100%", padding: "18px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: "22px", fontFamily: "'Nunito', sans-serif", color: COLORS.text, fontWeight: 700, background: COLORS.white, outline: "none", boxSizing: "border-box", textAlign: "center", letterSpacing: "2px" }} onFocus={(e) => e.target.style.borderColor = COLORS.bark} onBlur={(e) => e.target.style.borderColor = COLORS.border} />
</div>
{lookupError && (
<div style={{ background: "#FFEBEE", borderRadius: "12px", padding: "14px 16px", marginBottom: "16px", animation: "fadeUp 0.3s ease-out" }}>
<p style={{ margin: "0 0 6px 0", fontSize: "14px", color: COLORS.error, fontWeight: 700 }}>No encontramos ese número 🤔</p>
<button onClick={() => { setMode("new"); setStep(0); setLookupError(false); }} style={{ marginTop: "6px", background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "14px", cursor: "pointer", textDecoration: "underline" }}>Crear cuenta nueva →</button>
</div>
)}
<Btn onClick={handleLookup} disabled={lookupPhone.replace(/\D/g, "").length < 10 || lookupLoading}>
{lookupLoading ? "Buscando..." : "Buscar mi cuenta →"}
</Btn>
<p style={{ fontSize: "12px", color: COLORS.textLight, textAlign: "center", marginTop: "16px" }}>
💡 <strong>Demo:</strong> prueba <strong>2222392995</strong> ó <strong>2211173907</strong>
</p>
</Card>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === "returning" && foundUser) {
return (
<React.Fragment>
<Shell>
<button onClick={() => { setFoundUser(null); setLookupPhone(""); setSelectedChildren([]); setEditingPhone(false); }} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0", marginBottom: "12px" }}>← Otro número</button>
<Card style={{ padding: "24px", marginBottom: "16px" }}>
<div style={{ textAlign: "center", marginBottom: "20px" }}>
<div style={{ width: "72px", height: "72px", borderRadius: "50%", background: `linear-gradient(135deg, ${COLORS.orangeSoft}, ${COLORS.pinkSoft})`, display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px", fontSize: "32px" }}>👋</div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "22px", color: COLORS.text, margin: "0 0 2px 0" }}>¡Hola, {foundUser.nombre.split(" ")[0]}!</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: 0 }}>
{foundUser.ultimaVisita
? `Visita #${foundUser.visitas + 1} · Última: ${foundUser.ultimaVisita}`
: "¡Tu primera visita con nosotros!"}
</p>
</div>
<div style={{ background: COLORS.cream, borderRadius: "14px", padding: "14px", marginBottom: "16px" }}>
{!editingPhone ? (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div>
<div style={{ fontSize: "12px", fontWeight: 700, color: COLORS.bark }}>WhatsApp registrado</div>
<div style={{ fontSize: "16px", fontWeight: 700, color: COLORS.text, marginTop: "2px" }}>📱 {foundUser.telefono}</div>
</div>
<button onClick={() => { setEditingPhone(true); setNewPhone(foundUser.telefono); }} style={{ background: COLORS.white, border: `1px solid ${COLORS.border}`, borderRadius: "10px", padding: "6px 12px", fontSize: "13px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Cambiar</button>
</div>
) : (
<div>
<div style={{ fontSize: "12px", fontWeight: 700, color: COLORS.bark, marginBottom: "8px" }}>Nuevo número de WhatsApp</div>
<InputField label="" type="tel" value={newPhone} onChange={setNewPhone} placeholder="Nuevo número" large />
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
<button onClick={() => setEditingPhone(false)} style={{ padding: "10px", borderRadius: "12px", background: COLORS.white, border: `1px solid ${COLORS.border}`, color: COLORS.textLight, fontSize: "14px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer" }}>Cancelar</button>
<button onClick={confirmPhoneChange} disabled={newPhone.replace(/\D/g, "").length < 10} style={{ padding: "10px", borderRadius: "12px", background: newPhone.replace(/\D/g, "").length >= 10 ? COLORS.leaf : COLORS.border, border: "none", color: COLORS.white, fontSize: "14px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: newPhone.replace(/\D/g, "").length >= 10 ? "pointer" : "not-allowed" }}>Guardar ✓</button>
</div>
</div>
)}
</div>
{!editingPhone && <Btn onClick={() => { setMode("ret_confirmed"); setStep(0); }}>Soy yo — continuar →</Btn>}
</Card>
<p style={{ fontSize: "12px", color: COLORS.textLight, textAlign: "center" }}>
¿No eres tú? <button onClick={() => { setFoundUser(null); setLookupPhone(""); }} style={{ background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "12px", cursor: "pointer", textDecoration: "underline" }}>Buscar otro número</button>
</p>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (submitted) {
return (
<React.Fragment>
<Shell bg={`linear-gradient(180deg, #E8F5E9 0%, ${COLORS.warmBg} 100%)`}>
<div style={{ textAlign: "center" }}>
<div style={{ width: "100px", height: "100px", borderRadius: "50%", background: COLORS.leaf, display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 24px", boxShadow: "0 8px 32px rgba(76,175,80,0.3)", animation: "popIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55)" }}>
<span style={{ fontSize: "48px", color: COLORS.white }}>✓</span>
</div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "28px", color: COLORS.text, margin: "0 0 8px 0" }}>¡Registro completo!</h2>
<p style={{ fontSize: "16px", color: COLORS.textLight, margin: "0 0 24px 0", lineHeight: 1.5 }}>
{activeName.split(" ")[0]}, todo está listo.<br />
{activeChildren.length === 1 ? `${activeChildren[0].nombre} ya puede` : "Los pequeños ya pueden"} pasar a divertirse 🎈
</p>
<Card style={{ padding: "20px", marginBottom: "16px", textAlign: "left" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontWeight: 700, color: COLORS.text }}>Resumen</span>
<span style={{ background: servicio === "daypass" ? COLORS.pinkSoft : COLORS.orangeSoft, color: servicio === "daypass" ? COLORS.pink : COLORS.orange, padding: "4px 12px", borderRadius: "8px", fontSize: "13px", fontWeight: 700 }}>{servicio === "daypass" ? "DAYPASS" : "1 HORA"}</span>
</div>
<div style={{ fontSize: "14px", color: COLORS.textLight, lineHeight: 1.8 }}>
<div>👤 {activeName}</div>
<div>📱 {activePhone}</div>
{activeChildren.map((c, i) => <div key={i}>👶 {c.nombre}, {c.edad} años ({c.relacion})</div>)}
<div>🕐 Entrada: {currentTime}</div>
<div>💳 {metodoPago === "mostrador" ? "Pago en mostrador" : "Apple Pay"}</div>
</div>
</Card>
<div style={{ marginTop: "24px" }}><WonderlooLogo /></div>
<button onClick={resetAll} style={{ marginTop: "20px", background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "15px", cursor: "pointer", textDecoration: "underline" }}>Nuevo registro</button>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
const stepLabels = { tutor: "Responsable", children: "Niño(s)", select_children: "¿Quién viene?", service: "Entrada", responsiva: "Firma" };
const renderStep = () => {
switch (currentStepName) {
case "tutor":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Tus datos 👤</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Información del responsable</p>
<InputField label="Nombre completo" icon="👤" value={tutorData.nombre} onChange={(v) => setTutorData({ ...tutorData, nombre: v })} placeholder="Ej: María García López" />
<InputField label="WhatsApp" icon="📱" type="tel" value={tutorData.telefono} onChange={(v) => setTutorData({ ...tutorData, telefono: v })} placeholder="Ej: 221 123 4567" helperText="Este será tu identificador para futuras visitas" />
<InputField label="Correo electrónico" icon="📧" type="email" value={tutorData.correo} onChange={(v) => setTutorData({ ...tutorData, correo: v })} placeholder="Ej: maria@correo.com" required={false} />
</div>);
case "children":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Datos de los pequeños 👶</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Niños que ingresan hoy (1 a 11 años)</p>
{children.map((child, idx) => (
<Card key={idx} style={{ marginBottom: "16px", padding: "16px", border: `2px solid ${COLORS.cream}`, boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "16px", fontWeight: 600, color: COLORS.bark }}>{children.length > 1 ? `Niño ${idx + 1}` : "Datos del niño/a"}</span>
{children.length > 1 && <button onClick={() => removeChild(idx)} style={{ background: COLORS.pinkSoft, border: "none", borderRadius: "8px", padding: "4px 10px", fontSize: "13px", color: COLORS.pink, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Quitar ✕</button>}
</div>
<InputField label="Nombre del niño/a" value={child.nombre} onChange={(v) => updateChild(idx, "nombre", v)} placeholder="Nombre completo" />
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
<InputField label="Edad" type="number" value={child.edad} onChange={(v) => updateChild(idx, "edad", v)} placeholder="Años" />
<InputField label="Cumpleaños" type="date" value={child.cumple} onChange={(v) => updateChild(idx, "cumple", v)} required={false} />
</div>
<InputField label="Parentesco contigo" icon="👨‍👩‍👧" value={child.relacion} onChange={(v) => updateChild(idx, "relacion", v)} options={RELACIONES} placeholder="¿Qué eres del niño/a?" />
<InputField label="Alergias o notas médicas" value={child.alergias} onChange={(v) => updateChild(idx, "alergias", v)} placeholder="Ej: Alergia al cacahuate" required={false} />
</Card>
))}
{children.length < 4 && <button onClick={addChild} style={{ width: "100%", padding: "14px", borderRadius: "14px", border: `2px dashed ${COLORS.bark}`, background: COLORS.cream, color: COLORS.bark, fontSize: "16px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer" }}>+ Agregar otro niño</button>}
</div>);
case "select_children":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>¿Quién viene hoy? 👶</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Selecciona a los niños que asisten</p>
{(foundUser?.children || []).map((child, idx) => {
const sel = selectedChildren.includes(idx);
return (
<button key={idx} onClick={() => toggleChildSelection(idx)} style={{ width: "100%", display: "flex", alignItems: "center", gap: "14px", padding: "16px 18px", borderRadius: "16px", marginBottom: "12px", border: sel ? `3px solid ${COLORS.leaf}` : `2px solid ${COLORS.border}`, background: sel ? "#E8F5E9" : COLORS.white, cursor: "pointer", transition: "all 0.2s ease", textAlign: "left", boxSizing: "border-box" }}>
<div style={{ width: "32px", height: "32px", borderRadius: "10px", flexShrink: 0, background: sel ? COLORS.leaf : COLORS.white, border: `2px solid ${sel ? COLORS.leaf : COLORS.border}`, display: "flex", alignItems: "center", justifyContent: "center", transition: "all 0.2s" }}>
{sel && <span style={{ color: COLORS.white, fontSize: "18px", fontWeight: 900 }}>✓</span>}
</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: "16px", fontWeight: 700, color: COLORS.text, fontFamily: "'Nunito', sans-serif" }}>{child.nombre}</div>
<div style={{ fontSize: "13px", color: COLORS.textLight, marginTop: "2px" }}>
{child.edad} años · {child.relacion}
{child.alergias && <span style={{ color: COLORS.error, fontWeight: 700 }}> · ⚠️ {child.alergias}</span>}
</div>
</div>
</button>
);
})}
{!addingNewChild ? (
<button onClick={() => setAddingNewChild(true)} style={{ width: "100%", padding: "14px", borderRadius: "14px", border: `2px dashed ${COLORS.bark}`, background: COLORS.cream, color: COLORS.bark, fontSize: "16px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer", marginTop: "4px" }}>+ Agregar un niño nuevo</button>
) : (
<Card style={{ marginTop: "8px", padding: "16px", border: `2px solid ${COLORS.bark}`, boxShadow: "0 4px 16px rgba(139,105,20,0.1)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "16px", fontWeight: 600, color: COLORS.bark }}>Nuevo niño/a</span>
<button onClick={() => setAddingNewChild(false)} style={{ background: COLORS.pinkSoft, border: "none", borderRadius: "8px", padding: "4px 10px", fontSize: "13px", color: COLORS.pink, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Cancelar ✕</button>
</div>
<InputField label="Nombre" value={newChildForReturn.nombre} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, nombre: v })} placeholder="Nombre del niño/a" />
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
<InputField label="Edad" type="number" value={newChildForReturn.edad} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, edad: v })} placeholder="Años" />
<InputField label="Cumpleaños" type="date" value={newChildForReturn.cumple} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, cumple: v })} required={false} />
</div>
<InputField label="Parentesco contigo" icon="👨‍👩‍👧" value={newChildForReturn.relacion} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, relacion: v })} options={RELACIONES} placeholder="¿Qué eres del niño/a?" />
<InputField label="Alergias o notas médicas" value={newChildForReturn.alergias} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, alergias: v })} placeholder="Ej: Alergia al cacahuate" required={false} />
<Btn onClick={confirmAddNewChild} disabled={!newChildForReturn.nombre || !newChildForReturn.edad || !newChildForReturn.relacion}>Agregar a mi cuenta ✓</Btn>
</Card>
)}
</div>);
case "service":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Tipo de entrada 🎟️</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>{foundUser ? `${foundUser.nombre.split(" ")[0]}, selecciona el servicio` : "Selecciona el servicio para hoy"}</p>
{[
{ id: "hora", title: "1 Hora", price: `$${precios.nino_hora}`, desc: "60 minutos · 10 min de tolerancia", extra: `Hora adicional: $${precios.hora_extra}`, color: COLORS.orangeSoft, accent: COLORS.orange, icon: "⏱️" },
{ id: "daypass", title: "Daypass", price: `$${precios.nino_daypass}`, desc: "Tiempo ilimitado hasta el cierre", extra: "¡Juega todo lo que quieras!", color: COLORS.pinkSoft, accent: COLORS.pink, icon: "🌟" },
].map((o) => (
<button key={o.id} onClick={() => setServicio(o.id)} style={{ width: "100%", padding: "18px", borderRadius: "18px", border: servicio === o.id ? `3px solid ${o.accent}` : `2px solid ${COLORS.border}`, background: servicio === o.id ? o.color : COLORS.white, cursor: "pointer", textAlign: "left", marginBottom: "12px", transition: "all 0.2s ease", display: "block", boxSizing: "border-box", boxShadow: servicio === o.id ? `0 4px 20px ${o.accent}22` : "0 1px 4px rgba(0,0,0,0.04)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div>
<div style={{ fontSize: "20px", fontWeight: 800, color: COLORS.text, fontFamily: "'Fredoka', sans-serif" }}>{o.icon} {o.title}</div>
<div style={{ fontSize: "14px", color: COLORS.textLight, marginTop: "3px" }}>{o.desc}</div>
<div style={{ fontSize: "12px", color: o.accent, marginTop: "3px", fontWeight: 700 }}>{o.extra}</div>
</div>
<div style={{ fontSize: "26px", fontWeight: 900, color: o.accent, fontFamily: "'Fredoka', sans-serif" }}>{o.price}</div>
</div>
</button>
))}
<Card style={{ padding: "14px 16px", background: COLORS.sky, boxShadow: "none", marginBottom: "20px" }}>
<p style={{ margin: 0, fontSize: "13px", color: COLORS.blue, lineHeight: 1.5 }}>💡 Precios por niño. Adultos: Daypass ${precios.adulto_daypass}, 1 Hora ${precios.adulto_hora}. Calcetas: ${precios.calcetas}.</p>
</Card>
<h3 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "20px", color: COLORS.text, margin: "0 0 4px 0" }}>Método de pago 💳</h3>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 16px 0" }}>¿Cómo deseas pagar?</p>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
{[
{ id: "mostrador", icon: "🏪", label: "En mostrador", sub: "Efectivo o tarjeta" },
{ id: "applepay", icon: "", label: "Apple Pay", sub: "Pago instantáneo", isApple: true },
].map((pm) => (
<button key={pm.id} onClick={() => setMetodoPago(pm.id)} style={{ padding: "18px 14px", borderRadius: "16px", border: metodoPago === pm.id ? `3px solid ${COLORS.bark}` : `2px solid ${COLORS.border}`, background: metodoPago === pm.id ? COLORS.cream : COLORS.white, cursor: "pointer", textAlign: "center", transition: "all 0.2s", boxSizing: "border-box" }}>
<div style={{ fontSize: "32px", marginBottom: "6px" }}>{pm.isApple ? "🍎" : pm.icon}</div>
<div style={{ fontSize: "15px", fontWeight: 800, color: COLORS.text, fontFamily: "'Nunito', sans-serif" }}>{pm.label}</div>
<div style={{ fontSize: "12px", color: COLORS.textLight, marginTop: "2px" }}>{pm.sub}</div>
</button>
))}
</div>
</div>);
case "responsiva":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Responsiva y firma ✍️</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 16px 0" }}>Último paso — lee y firma</p>
<div style={{ maxHeight: "200px", overflowY: "auto", padding: "16px", background: COLORS.white, borderRadius: "14px", border: `1px solid ${COLORS.border}`, marginBottom: "16px", fontSize: "13px", color: COLORS.textLight, lineHeight: 1.7, whiteSpace: "pre-line" }}>{RESPONSIVA}</div>
<label style={{ display: "flex", alignItems: "flex-start", gap: "12px", marginBottom: "20px", cursor: "pointer", padding: "14px 16px", borderRadius: "14px", background: aceptaResponsiva ? "#E8F5E9" : COLORS.cream, border: `2px solid ${aceptaResponsiva ? COLORS.leaf : COLORS.border}`, transition: "all 0.2s" }}>
<div onClick={() => setAceptaResponsiva(!aceptaResponsiva)} style={{ width: "28px", height: "28px", borderRadius: "8px", flexShrink: 0, background: aceptaResponsiva ? COLORS.leaf : COLORS.white, border: `2px solid ${aceptaResponsiva ? COLORS.leaf : COLORS.border}`, display: "flex", alignItems: "center", justifyContent: "center", marginTop: "2px", cursor: "pointer", transition: "all 0.2s" }}>
{aceptaResponsiva && <span style={{ color: COLORS.white, fontSize: "16px", fontWeight: 900 }}>✓</span>}
</div>
<span style={{ fontSize: "15px", color: COLORS.text, fontWeight: 600, lineHeight: 1.5 }}>He leído y acepto la responsiva y el reglamento de Wonderloo Indoor Park</span>
</label>
{aceptaResponsiva && <div style={{ animation: "fadeUp 0.3s ease-out" }}><p style={{ fontSize: "15px", fontWeight: 700, color: COLORS.text, margin: "0 0 8px 0" }}>Tu firma:</p><SignaturePad onSign={setSignature} /></div>}
</div>);
default: return null;
}
};
return (
<React.Fragment>
<div style={{ minHeight: "100vh", background: `linear-gradient(180deg, ${COLORS.warmBg} 0%, ${COLORS.cream} 100%)`, fontFamily: "'Nunito', sans-serif" }}>
<Fonts />
<div style={{ position: "sticky", top: 0, zIndex: 10, background: `${COLORS.warmBg}F0`, backdropFilter: "blur(12px)", padding: "12px 20px 4px", borderBottom: `1px solid ${COLORS.cream}` }}>
<div style={{ maxWidth: "420px", margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
<button onClick={goBack} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0" }}>← Atrás</button>
<span style={{ fontSize: "14px", color: COLORS.textLight, fontWeight: 600 }}>{stepLabels[currentStepName]} · Paso {step + 1} de {totalSteps}</span>
<div style={{ width: "60px" }} />
</div>
<div style={{ maxWidth: "420px", margin: "0 auto" }}><ProgressDots current={step} total={totalSteps} /></div>
</div>
<div style={{ maxWidth: "420px", margin: "0 auto", padding: "20px 20px 100px" }}>{renderStep()}</div>
<div style={{ position: "fixed", bottom: 0, left: 0, right: 0, padding: "16px 20px", background: `linear-gradient(0deg, ${COLORS.warmBg} 80%, ${COLORS.warmBg}00 100%)` }}>
<div style={{ maxWidth: "420px", margin: "0 auto" }}>
<Btn onClick={isLastStep ? handleSubmit : goNext} disabled={submitLoading || !canProceed()} variant={isLastStep ? "success" : "primary"}>{submitLoading ? "Registrando..." : (isLastStep ? "Firmar y registrar ✓" : "Continuar →")}</Btn>
</div>
</div>
<style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } } @keyframes popIn { from { transform:scale(0); } to { transform:scale(1); } } * { -webkit-tap-highlight-color: transparent; } input, select { font-size: 17px !important; }`}</style>
</div>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<WonderlooCheckin />);
</script>
</body>
</html>