commit 37bb88c440200a6ca746ca21fccfc11d4bdd12a6 Author: Jorem Juárez Date: Mon Apr 20 18:32:29 2026 -0600 feat: initial commit — frontend + backend + docker + schema diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a42489c --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6c20bee --- /dev/null +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..48f7f56 --- /dev/null +++ b/README.md @@ -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. diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..dbb23e6 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,6 @@ +node_modules +npm-debug.log +.env +.env.* +Dockerfile +.dockerignore diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..3f0ce1f --- /dev/null +++ b/backend/Dockerfile @@ -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"] diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..05f585c --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,1144 @@ +{ + "name": "wonderloo-api", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "wonderloo-api", + "version": "0.1.0", + "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" + } + }, + "node_modules/@fastify/ajv-compiler": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.5.tgz", + "integrity": "sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^3.0.0" + } + }, + "node_modules/@fastify/cors": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-10.1.0.tgz", + "integrity": "sha512-MZyBCBJtII60CU9Xme/iE4aEy8G7QpzGR8zkdXZkDFt7ElEMachbE61tfhAG/bvSaULlqlf0huMT12T7iqEmdQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^5.0.0", + "mnemonist": "0.40.0" + } + }, + "node_modules/@fastify/error": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz", + "integrity": "sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.0.3.tgz", + "integrity": "sha512-uik7yYHkLr6fxd8hJSZ8c+xF4WafPK+XzneQDPU+D10r5X19GW8lJcom2YijX2+qtFF1ENJlHXKFM9ouXNJYgQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^6.0.0" + } + }, + "node_modules/@fastify/forwarded": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.1.tgz", + "integrity": "sha512-JqDochHFqXs3C3Ml3gOY58zM7OqO9ENqPo0UqAjAjH8L01fRZqwX9iLeX34//kiJubF7r2ZQHtBRU36vONbLlw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz", + "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@fastify/proxy-addr": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.0.tgz", + "integrity": "sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dev": true, + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/abstract-logging": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", + "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", + "license": "MIT" + }, + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/avvio": { + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.2.0.tgz", + "integrity": "sha512-2t/sy01ArdHHE0vRH5Hsay+RtCZt3dLPji7W7/MMOCEgze5b7SNDC4j5H6FnVgPkI1MTNFGzHdHrVXDDl7QSSQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastq": "^1.17.1" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-copy": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz", + "integrity": "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-6.3.0.tgz", + "integrity": "sha512-oRCntNDY/329HJPlmdNLIdogNtt6Vyjb1WuT01Soss3slIdyUp8kAcDU3saQTOquEK8KFVfwIIF7FebxUAu+yA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.2.0", + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^3.0.0", + "json-schema-ref-resolver": "^3.0.0", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastify": { + "version": "5.8.5", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.5.tgz", + "integrity": "sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^4.0.5", + "@fastify/error": "^4.0.0", + "@fastify/fast-json-stringify-compiler": "^5.0.0", + "@fastify/proxy-addr": "^5.0.0", + "abstract-logging": "^2.0.1", + "avvio": "^9.0.0", + "fast-json-stringify": "^6.0.0", + "find-my-way": "^9.0.0", + "light-my-request": "^6.0.0", + "pino": "^9.14.0 || ^10.1.0", + "process-warning": "^5.0.0", + "rfdc": "^1.3.1", + "secure-json-parse": "^4.0.0", + "semver": "^7.6.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/fastify-plugin": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz", + "integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/find-my-way": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.5.0.tgz", + "integrity": "sha512-VW2RfnmscZO5KgBY5XVyKREMW5nMZcxDy+buTOsL+zIPnBlbKm+00sgzoQzq1EVh4aALZLfKdwv6atBGcjvjrQ==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/help-me": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", + "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ipaddr.js": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.3.0.tgz", + "integrity": "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/json-schema-ref-resolver": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz", + "integrity": "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/light-my-request": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz", + "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "dependencies": { + "cookie": "^1.0.1", + "process-warning": "^4.0.0", + "set-cookie-parser": "^2.6.0" + } + }, + "node_modules/light-my-request/node_modules/process-warning": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz", + "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mnemonist": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.40.0.tgz", + "integrity": "sha512-kdd8AFNig2AD5Rkih7EPCXhu/iMvwevQFX/uEiGhZyPZi7fHqOoF4V4kHLpCfysxXMgQ4B52kdPMCwARshKvEg==", + "license": "MIT", + "dependencies": { + "obliterator": "^2.0.4" + } + }, + "node_modules/obliterator": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz", + "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==", + "license": "MIT" + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/pg": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", + "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.12.0", + "pg-pool": "^3.13.0", + "pg-protocol": "^1.13.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.3.0" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", + "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", + "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.13.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", + "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", + "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/pino": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", + "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-11.3.0.tgz", + "integrity": "sha512-oXwn7ICywaZPHmu3epHGU2oJX4nPmKvHvB/bwrJHlGcbEWaVcotkpyVHMKLKmiVryWYByNp0jpgAcXpFJDXJzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "colorette": "^2.0.7", + "dateformat": "^4.6.3", + "fast-copy": "^3.0.2", + "fast-safe-stringify": "^2.1.1", + "help-me": "^5.0.0", + "joycon": "^3.1.1", + "minimist": "^1.2.6", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pump": "^3.0.0", + "readable-stream": "^4.0.0", + "secure-json-parse": "^2.4.0", + "sonic-boom": "^4.0.1", + "strip-json-comments": "^3.1.1" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-pretty/node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "dev": true, + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ret": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", + "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex2": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz", + "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/secure-json-parse": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", + "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/thread-stream": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.0.0.tgz", + "integrity": "sha512-4iMVL6HAINXWf1ZKZjIPcz5wYaOdPhtO8ATvZ+Xqp3BTdaqtAwQkNmKORqcIo5YkQqGXq5cwfswDwMqqQNrpJA==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/toad-cache": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz", + "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..ebd6520 --- /dev/null +++ b/backend/package.json @@ -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" + } +} diff --git a/backend/src/config.js b/backend/src/config.js new file mode 100644 index 0000000..05754e7 --- /dev/null +++ b/backend/src/config.js @@ -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), +}; diff --git a/backend/src/db/client.js b/backend/src/db/client.js new file mode 100644 index 0000000..78e9637 --- /dev/null +++ b/backend/src/db/client.js @@ -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; + } + }, +}; diff --git a/backend/src/db/migrations/001_initial.sql b/backend/src/db/migrations/001_initial.sql new file mode 100644 index 0000000..2848d16 --- /dev/null +++ b/backend/src/db/migrations/001_initial.sql @@ -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; diff --git a/backend/src/db/migrations/002_seed_dev.sql b/backend/src/db/migrations/002_seed_dev.sql new file mode 100644 index 0000000..33aeffd --- /dev/null +++ b/backend/src/db/migrations/002_seed_dev.sql @@ -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; diff --git a/backend/src/index.js b/backend/src/index.js new file mode 100644 index 0000000..179f6ab --- /dev/null +++ b/backend/src/index.js @@ -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); +} diff --git a/backend/src/routes/ninos.js b/backend/src/routes/ninos.js new file mode 100644 index 0000000..843df0e --- /dev/null +++ b/backend/src/routes/ninos.js @@ -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); + } + ); +} diff --git a/backend/src/routes/precios.js b/backend/src/routes/precios.js new file mode 100644 index 0000000..57d1ef6 --- /dev/null +++ b/backend/src/routes/precios.js @@ -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; + }); +} diff --git a/backend/src/routes/tutores.js b/backend/src/routes/tutores.js new file mode 100644 index 0000000..cd6bfe5 --- /dev/null +++ b/backend/src/routes/tutores.js @@ -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; + } + } + ); +} diff --git a/backend/src/routes/visitas.js b/backend/src/routes/visitas.js new file mode 100644 index 0000000..aa9fa66 --- /dev/null +++ b/backend/src/routes/visitas.js @@ -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, + })), + }); + } + ); +} diff --git a/backend/src/services/sheets-sync.js b/backend/src/services/sheets-sync.js new file mode 100644 index 0000000..d679b04 --- /dev/null +++ b/backend/src/services/sheets-sync.js @@ -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); + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a521e60 --- /dev/null +++ b/docker-compose.yml @@ -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 diff --git a/docs/00-BRIEF.md b/docs/00-BRIEF.md new file mode 100644 index 0000000..48f7f56 --- /dev/null +++ b/docs/00-BRIEF.md @@ -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. diff --git a/docs/01-SCHEMA.md b/docs/01-SCHEMA.md new file mode 100644 index 0000000..dfb1426 --- /dev/null +++ b/docs/01-SCHEMA.md @@ -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'; +``` diff --git a/docs/02-API.md b/docs/02-API.md new file mode 100644 index 0000000..12b3792 --- /dev/null +++ b/docs/02-API.md @@ -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; + } + }); +} +``` diff --git a/docs/03-DEPLOY.md b/docs/03-DEPLOY.md new file mode 100644 index 0000000..25e97e5 --- /dev/null +++ b/docs/03-DEPLOY.md @@ -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= + +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. diff --git a/docs/04-DNS.md b/docs/04-DNS.md new file mode 100644 index 0000000..b5f634f --- /dev/null +++ b/docs/04-DNS.md @@ -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. diff --git a/docs/PROMPT-CLAUDE-CODE.md b/docs/PROMPT-CLAUDE-CODE.md new file mode 100644 index 0000000..5dabf5c --- /dev/null +++ b/docs/PROMPT-CLAUDE-CODE.md @@ -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. +``` +``` diff --git a/frontend/wonderloo.html b/frontend/wonderloo.html new file mode 100644 index 0000000..ee7181b --- /dev/null +++ b/frontend/wonderloo.html @@ -0,0 +1,736 @@ + + + + + +Wonderloo Indoor Park + + + + + +
+ + +