From 11dfca65b7f4b83a47b12da7d60de412876cb496 Mon Sep 17 00:00:00 2001 From: JuanBerro-back Date: Sun, 25 Oct 2026 09:54:29 -0500 Subject: [PATCH] Security hardening + enterprise email for production - Disable demo seeding by default; bootstrap admin from ADMIN_USERNAME/ADMIN_PASSWORD - Neutralize legacy demo-hash accounts on startup in production - Enforce JWT HS256/12h, fresh DB identity per request and Socket.IO handshake - Socket.IO: remove client:identify, derive rooms only from token, fail-closed CORS - Fix products IDOR, delivery-code leak/bypass, XupAI abuse, dashboard tenant leaks - Restrict subscription plans to admin, bounded pagination, no fake dashboard data - helmet CSP/HSTS + equivalent headers in vercel.json/Caddyfile, generic error handler - Enterprise email: SMTP/Resend/EmailJS with HTML+text, retries, Reply-To/BCC - Admin email diagnostics endpoints and npm run email:test script - Deployment: Dockerfile, docker-compose, Caddyfile, render.yaml, CI, .env.production.example - Bump express/nodemailer to patched releases (npm audit: 0 vulnerabilities) - Docs: SECURITY-AUDIT.md, MIGRACION-BACKEND.md, EMAIL-ENTERPRISE.md --- .dockerignore | 15 ++ .env.example | 51 ++--- .env.production.example | 77 ++++++++ .github/workflows/ci.yml | 41 ++++ .gitignore | 31 ++- Caddyfile | 25 +++ Dockerfile | 41 ++++ EMAIL-ENTERPRISE.md | 209 +++++++++++++++++++++ MIGRACION-BACKEND.md | 175 +++++++++++++++++ README BACKEND.md | 69 ++++++- SECURITY-AUDIT.md | 251 +++++++++++++++++++++++++ docker-compose.yml | 103 ++++++++++ package-lock.json | 82 ++++++-- package.json | 10 +- render.yaml | 51 +++++ scripts/email-test.ts | 39 ++++ scripts/smoke.ts | 8 +- src/app.ts | 66 +++++-- src/config/db.ts | 165 ++++++++++++++-- src/config/schemaSql.ts | 2 +- src/lib/email.ts | 386 ++++++++++++++++++++++++++++++++++++-- src/lib/migrations.ts | 98 ++-------- src/lib/oc.ts | 5 +- src/lib/realtime.ts | 104 +++++++--- src/middleware/auth.ts | 47 +++-- src/middleware/error.ts | 24 ++- src/routes/admin.ts | 94 +++++++--- src/routes/auth.ts | 88 +++++++-- src/routes/dashboard.ts | 95 +++------- src/routes/deliveries.ts | 344 ++++++++++++++++++++++++++++----- src/routes/invoices.ts | 3 +- src/routes/orders.ts | 48 ++++- src/routes/products.ts | 81 ++++---- src/routes/restaurants.ts | 23 ++- src/routes/reviews.ts | 50 +++-- src/routes/suppliers.ts | 18 +- src/routes/users.ts | 6 + src/routes/xupai.ts | 107 ++++++++--- src/server.ts | 95 ++++++++-- vercel.json | 33 ++++ 40 files changed, 2743 insertions(+), 517 deletions(-) create mode 100644 .dockerignore create mode 100644 .env.production.example create mode 100644 .github/workflows/ci.yml create mode 100644 Caddyfile create mode 100644 Dockerfile create mode 100644 EMAIL-ENTERPRISE.md create mode 100644 MIGRACION-BACKEND.md create mode 100644 SECURITY-AUDIT.md create mode 100644 docker-compose.yml create mode 100644 render.yaml create mode 100644 scripts/email-test.ts create mode 100644 vercel.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..99abfe7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +# Dependencias y artefactos +node_modules +dist +.git +.github +*.log + +# Secretos +.env +.env.* +!.env.example +!.env.production.example + +# Base de datos local +pgdata diff --git a/.env.example b/.env.example index 9ab3352..697e88f 100644 --- a/.env.example +++ b/.env.example @@ -1,36 +1,39 @@ -# ============================================================ -# Backend Xupply / Hackathon - Variables de entorno -# Copia este archivo a .env y ajusta los valores. -# ============================================================ - PORT=4000 - -# Base de datos PostgreSQL (local o en la nube: Neon, Render, Supabase...) -DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/xupply - -# Obligatorio en produccion (el servidor no arranca sin esto fuera de desarrollo). -# Genera uno con: +DATABASE_URL=postgres://postgres:postgres@localhost:5432/xupply +# Obligatorio. Genera uno con: # node -e "console.log(require('crypto').randomBytes(48).toString('hex'))" JWT_SECRET=change-me-to-a-long-random-value - -# Lista blanca de origenes permitidos (CORS HTTP + Socket.IO), separados por coma. -# Si se deja vacio se permite cualquier origen (solo recomendado en desarrollo). +JWT_EXPIRES_IN=12h CLIENT_ORIGIN=http://localhost:5173 -# Notificaciones por email (EmailJS) - opcional +# --- Correo transaccional --- +# En local puedes dejarlo vacío: los correos se omiten sin romper la app. +MAIL_PROVIDER= +MAIL_FROM= +MAIL_FROM_NAME=Xupply +MAIL_REPLY_TO= +MAIL_BCC= +APP_URL=http://localhost:5173 +MAIL_COMPANY_NAME=Xupply +MAIL_COMPANY_ADDRESS=Bucaramanga, Santander, Colombia + +# SMTP empresarial +# SMTP_HOST=smtp.gmail.com +# SMTP_PORT=587 +# SMTP_SECURE=false +# SMTP_USER=tu-correo@tudominio.com +# SMTP_PASS=tu-contrasena-de-aplicacion + +# Resend (alternativa) +# RESEND_API_KEY=re_... + +# EmailJS (legacy) EMAILJS_SERVICE_ID= EMAILJS_TEMPLATE_ID= EMAILJS_PUBLIC_KEY= EMAILJS_PRIVATE_KEY= -# Agente XupAI (DeepSeek) - opcional -# La clave puede ir en XUPAI_API_KEY, DEEPSEEK_API_KEY u OPENAI_API_KEY. -XUPAI_API_KEY= -DEEPSEEK_API_KEY= +# Agente XupAI (DeepSeek) +DEEPSEEK_API_KEY=sk-your-deepseek-api-key XUPAI_MODEL=deepseek-chat XUPAI_BASE_URL=https://api.deepseek.com - -# Notas: -# - En Vercel tambien se detectan automaticamente POSTGRES_URL, POSTGRES_URL_NON_POOLING, -# POSTGRES_PRISMA_URL y las variables POSTGRES_HOST/USER/PASSWORD/DATABASE. -# - PGSSLMODE=require fuerza SSL si tu proveedor lo necesita. diff --git a/.env.production.example b/.env.production.example new file mode 100644 index 0000000..b8291cd --- /dev/null +++ b/.env.production.example @@ -0,0 +1,77 @@ +# ============================================================ +# Xupply Backend - variables de entorno para PRODUCCIÓN +# Copia este archivo a .env.production (nunca lo subas al repo). +# Genera secretos con: openssl rand -base64 48 +# ============================================================ + +NODE_ENV=production +DOMAIN=xupply.example.com +PORT=4420 + +# --- PostgreSQL --- +POSTGRES_DB=xupply +POSTGRES_USER=xupply +POSTGRES_PASSWORD=CAMBIA_ESTA_CONTRASENA_LARGA +# Docker Compose: host "db". Render/Vercel/Neon/Supabase: usa la URL que te den. +DATABASE_URL=postgres://xupply:CAMBIA_ESTA_CONTRASENA_LARGA@db:5432/xupply + +# --- Autenticación --- +# Obligatorio. El servidor se niega a arrancar en producción sin este valor. +JWT_SECRET=CAMBIA_ESTE_SECRETO_POR_UNO_ALEATORIO_DE_64_CARACTERES +JWT_EXPIRES_IN=12h + +# Origen(es) permitidos para CORS, separados por coma. Sin esto, en producción +# no se acepta ningún origen cruzado (fail-closed). +CLIENT_ORIGIN=https://xupply.example.com + +# --- Bootstrap del administrador --- +# Solo se usa la primera vez, cuando la base de datos no tiene usuarios. +# La contraseña debe tener 12+ caracteres. Elimina estas variables después. +ADMIN_USERNAME=admin +ADMIN_PASSWORD=CAMBIA_ESTA_CONTRASENA_DE_ADMIN + +# NUNCA activar en producción: crea usuarios demo con contraseñas conocidas. +SEED_DEMO_DATA=false + +# --- Agente XupAI (opcional) --- +# Opción 1: DeepSeek (recomendado) +DEEPSEEK_API_KEY=sk-your-deepseek-api-key +XUPAI_MODEL=deepseek-chat +XUPAI_BASE_URL=https://api.deepseek.com + +# Opción 2: variable genérica +# XUPAI_API_KEY=sk-your-deepseek-or-openai-key + +# --- Correo transaccional enterprise --- +# Rellena estos valores con datos reales: los placeholders no envían correo. +# smtp | resend | emailjs (vacío = autodetección) +MAIL_PROVIDER=smtp +# Usa SIEMPRE un dominio corporativo verificado. Nunca gmail.com/hotmail.com en producción. +MAIL_FROM=notificaciones@tudominio.com +MAIL_FROM_NAME=Xupply +# Bandeja de entrada enterprise que recibe las respuestas de los clientes. +MAIL_REPLY_TO=soporte@tudominio.com +# Copia oculta de auditoría (opcional, recomendado en enterprise). +MAIL_BCC=auditoria@tudominio.com +APP_URL=https://tudominio.com +MAIL_COMPANY_NAME=Xupply +MAIL_COMPANY_ADDRESS=Bucaramanga, Santander, Colombia + +# SMTP empresarial (Google Workspace, Microsoft 365, Amazon SES, Zoho...) +# Google Workspace: smtp.gmail.com:587 con contraseña de aplicación. +# Microsoft 365: smtp.office365.com:587 (requiere SMTP AUTH habilitado). +# Amazon SES: email-smtp..amazonaws.com:587 con credenciales SMTP. +SMTP_HOST=smtp.tudominio.com +SMTP_PORT=587 +SMTP_SECURE=false +SMTP_USER=notificaciones@tudominio.com +SMTP_PASS=CAMBIA_ESTA_CONTRASENA + +# Alternativa recomendada: Resend (DKIM/SPF gestionados, HTTPS sin problemas en serverless) +# RESEND_API_KEY=re_xxxxxxxxx + +# EmailJS (legacy, solo si no usas SMTP/Resend) +EMAILJS_SERVICE_ID= +EMAILJS_TEMPLATE_ID= +EMAILJS_PUBLIC_KEY= +EMAILJS_PRIVATE_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7da52a6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + branches: [main, master, Backend] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-test: + name: Typecheck, build y auditoría + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Node 20 + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Instalar dependencias + run: npm ci --no-audit --no-fund + + - name: Typecheck + run: npm run typecheck + + - name: Build + run: npm run build + + - name: Auditar dependencias de producción + run: npm audit --omit=dev --audit-level=high diff --git a/.gitignore b/.gitignore index df66990..da55139 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,31 @@ +# Secrets and local configuration +.env +.env.production +.env.*.local +*.local + +# Dependencies and generated output node_modules/ dist/ -.env -*.log \ No newline at end of file +*.tsbuildinfo + +# Local databases and runtime files +pgdata/ +pg.log +*.pid +*.log + +# IDE and OS files +.vscode/ +.idea/ +.DS_Store +Thumbs.db + +# Android releases and keystores +dist-apk/ +release-manual/ +*.jks +*.apk + +# Docker local +docker-compose.override.yml diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..5aa966d --- /dev/null +++ b/Caddyfile @@ -0,0 +1,25 @@ +{$DOMAIN} { + encode zstd gzip + + # Cabeceras de seguridad. La CSP se aplica aquí (borde) además de helmet, + # para defensa en profundidad. + header { + -Server + -X-Powered-By + Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https: wss:; manifest-src 'self'; worker-src 'self' blob:; upgrade-insecure-requests" + X-Content-Type-Options "nosniff" + X-Frame-Options "DENY" + Referrer-Policy "strict-origin-when-cross-origin" + Permissions-Policy "camera=(), microphone=(), payment=(), usb=(), geolocation=(self)" + Cross-Origin-Opener-Policy "same-origin" + Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" + } + + # Socket.IO necesita el upgrade de WebSocket: reverse_proxy lo soporta por defecto. + reverse_proxy app:4420 { + header_up X-Real-IP {remote_host} + health_uri /health + health_interval 30s + health_timeout 5s + } +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7a9fe20 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,41 @@ +# syntax=docker/dockerfile:1 + +# ---------- Build (TypeScript -> dist) ---------- +FROM node:20-bookworm-slim AS build +WORKDIR /app + +COPY package*.json ./ +RUN npm ci --no-audit --no-fund + +COPY tsconfig*.json index.ts index.js ./ +COPY src ./src + +RUN npm run build + +# ---------- Dependencias de producción (sin devDependencies) ---------- +FROM node:20-bookworm-slim AS prod-deps +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev --no-audit --no-fund + +# ---------- Runtime ---------- +FROM node:20-bookworm-slim AS runtime +ENV NODE_ENV=production \ + PORT=4420 +WORKDIR /app + +COPY --from=prod-deps /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist +COPY --from=build /app/package.json ./package.json +COPY --from=build /app/index.js ./index.js + +# Ejecutar como usuario sin privilegios (node:node, uid/gid 1000). +USER node + +EXPOSE 4420 +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4420)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" + +CMD ["node", "dist/server.js"] diff --git a/EMAIL-ENTERPRISE.md b/EMAIL-ENTERPRISE.md new file mode 100644 index 0000000..4f4fda9 --- /dev/null +++ b/EMAIL-ENTERPRISE.md @@ -0,0 +1,209 @@ +# Correo enterprise y entregabilidad (anti-spam) + +Guía para que Xupply envíe correos transaccionales (pedidos, facturas, pruebas) desde un **dominio corporativo** y lleguen a la **bandeja de entrada**, no a spam. + +--- + +## 1. Cómo funciona en el código + +`src/lib/email.ts` soporta tres proveedores y autodetecta el que esté configurado: + +| Prioridad | Proveedor | Variables | Recomendado para | +|---|---|---|---| +| 1 | **SMTP** | `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS` | Google Workspace, Microsoft 365, Amazon SES, Zoho | +| 2 | **Resend** | `RESEND_API_KEY` | Startups/hackathon, DKIM automático | +| 3 | **EmailJS** (legacy) | `EMAILJS_*` | Compatibilidad con la configuración anterior | + +Si no hay ninguno, el correo se omite con un warning; **nunca rompe** la creación de un pedido o factura. + +### Variables nuevas + +```env +MAIL_PROVIDER=smtp # smtp | resend | emailjs | vacío = autodetectar +MAIL_FROM=notificaciones@tudominio.com +MAIL_FROM_NAME=Xupply +MAIL_REPLY_TO=soporte@tudominio.com +MAIL_BCC=auditoria@tudominio.com # opcional: copia oculta de auditoría +APP_URL=https://tudominio.com +MAIL_COMPANY_NAME=Xupply +MAIL_COMPANY_ADDRESS=Bucaramanga, Santander, Colombia + +# SMTP +SMTP_HOST=smtp.tudominio.com +SMTP_PORT=587 +SMTP_SECURE=false # true solo para puerto 465 +SMTP_USER=notificaciones@tudominio.com +SMTP_PASS=... + +# o Resend +# RESEND_API_KEY=re_... +``` + +> `MAIL_FROM` debe pertenecer al **mismo dominio** de `SMTP_USER`. Si no coincide, SPF/DKIM fallan y el correo cae en spam. + +--- + +## 2. "Entrada de correo enterprise" (buzón real) + +Para que los clientes puedan **responder** y tú recibas en un buzón corporativo: + +1. Crea el dominio y los buzones en tu proveedor: + - `notificaciones@tudominio.com` → remitente automático. + - `soporte@tudominio.com` → bandeja que recibe respuestas (`MAIL_REPLY_TO`). + - `auditoria@tudominio.com` → copia oculta de todos los envíos (`MAIL_BCC`), opcional. + - `dmarc@tudominio.com` → reportes DMARC. +2. Configura `MAIL_REPLY_TO=soporte@tudominio.com`. Así el cliente responde a una persona, no a `no-reply`. +3. No uses `no-reply@` como `MAIL_FROM` si esperas respuestas; usa `notificaciones@`. +4. Verifica que el buzón `soporte@` tenga IMAP/SMTP activo y que el proveedor permita SMTP AUTH. + +> En Google Workspace o Microsoft 365 el buzón ya existe como "entrada" corporativa; Xupply solo necesita credenciales SMTP de ese buzón. + +--- + +## 3. Configuración DNS (la clave para no caer en spam) + +Añade estos registros en el panel DNS de tu dominio. Sustituye `tudominio.com` y los valores por los que te dé el proveedor. + +### 3.1 SPF — autoriza a tu proveedor + +Un solo registro TXT en la raíz: + +| Proveedor | Registro SPF | +|---|---| +| Google Workspace | `v=spf1 include:_spf.google.com ~all` | +| Microsoft 365 | `v=spf1 include:spf.protection.outlook.com ~all` | +| Amazon SES | `v=spf1 include:amazonses.com ~all` | +| Resend | `v=spf1 include:amazonses.com ~all` (Resend usa SES) | +| Zoho | `v=spf1 include:zoho.com ~all` | + +**No tengas dos registros SPF**: se invalidan. Si ya existe uno, fusiónalo. + +### 3.2 DKIM — firma criptográfica + +El proveedor te da registros CNAME/TXT con un selector (por ejemplo `google._domainkey`, `selector1._domainkey`, `resend._domainkey`). Añádelos **tal cual**. DKIM es el factor que más pesa para Gmail/Outlook. + +- Google Workspace: Admin → Apps → Google Workspace → Gmail → Autenticar correo. +- Microsoft 365: Defender → Email authentication → DKIM → habilitar dominio. +- Amazon SES: Verified identities → DKIM → CNAMEs. +- Resend: Domains → Add domain → copiar registros. + +### 3.3 DMARC — política y reportes + +TXT en `_dmarc.tudominio.com`: + +``` +v=DMARC1; p=quarantine; rua=mailto:dmarc@tudominio.com; ruf=mailto:dmarc@tudominio.com; adkim=s; aspf=s; pct=100 +``` + +- Empieza con `p=none` si estás migrando, revisa reportes 1–2 semanas y luego pasa a `quarantine` y `reject`. +- `adkim=s; aspf=s` exige alineación estricta: el dominio de `MAIL_FROM` debe coincidir con el que firma. +- `rua` te envía reportes agregados; úsalos para detectar fallos. + +### 3.4 Registro MX y PTR + +- **MX**: solo necesario para el buzón de entrada (`soporte@`). El proveedor de correo te da los MX. +- **PTR / rDNS**: si usas un VPS con SMTP propio, configura el registro inverso a tu dominio. Sin PTR, Gmail penaliza. +- **No abras el puerto 25** en VPS cloud (bloqueado por AWS/GCP/Azure); usa el puerto 587 de tu proveedor. + +### 3.5 Verificación + +```powershell +# SPF +nslookup -type=TXT tudominio.com + +# DMARC +nslookup -type=TXT _dmarc.tudominio.com + +# DKIM (ejemplo con selector de Google) +nslookup -type=TXT google._domainkey.tudominio.com +``` + +Herramientas online: MXToolbox, Google Admin Toolbox (Messageheader), mail-tester.com. + +--- + +## 4. Buenas prácticas de contenido + +El código ya aplica varias: + +- HTML **y** texto plano (`multipart/alternative`). +- Remitente con nombre (`Xupply `). +- `Reply-To` a un buzón real. +- `Message-ID` generado por el proveedor. +- Cabeceras `X-Mailer` y `X-Auto-Response-Suppress`. +- Sin imágenes externas obligatorias ni adjuntos pesados. +- Footer con empresa y dirección física (CAN-SPAM). + +Recomendaciones adicionales: + +- No uses mayúsculas sostenidas ni signos `!!!` en asuntos. +- Evita palabras típicas de spam: "gratis", "urgente", "100% garantizado", "haz clic aquí". +- Incluye siempre el nombre del destinatario cuando lo tengas. +- No envíes correos masivos desde el mismo dominio transaccional; usa un subdominio (`mail.tudominio.com`) o un proveedor separado. +- Calienta el dominio: primeros días pocos envíos, luego aumenta. +- Si haces campañas, añade `List-Unsubscribe`; los transaccionales (pedido/factura) no lo necesitan. + +--- + +## 5. Prueba en local / producción + +### 5.1 Script de prueba + +```powershell +cd C:\ruta\a\hackathon-xupply +npm run email:test -- tu-correo@tudominio.com +``` + +Muestra proveedor, `From`, `Reply-To`, advertencias y envía un correo real. Revisa **Recibidos** y **Spam**. + +### 5.2 Endpoint de administración + +Con un token de administrador: + +```http +GET /api/admin/email/status → proveedor, from, reply_to, warnings +POST /api/admin/email/test → envía a tu propio correo (cooldown 60 s) +``` + +No acepta destinatarios arbitrarios: solo el correo del administrador autenticado, para evitar que se use como relay. + +### 5.3 Prueba de entregabilidad + +1. Envía a una cuenta Gmail, una Outlook y una corporativa. +2. Revisa "Mostrar original" → `SPF: PASS`, `DKIM: PASS`, `DMARC: PASS`. +3. Usa mail-tester.com: apunta a 10/10. +4. Si cae en spam, revisa en este orden: DKIM → SPF → DMARC → reputación del dominio → contenido. + +--- + +## 6. Diagnóstico rápido + +| Síntoma | Causa probable | Solución | +|---|---|---| +| `535 Authentication failed` | Contraseña normal en vez de "contraseña de aplicación" / SMTP AUTH deshabilitado | Genera App Password (Google) o habilita SMTP AUTH (M365) | +| `From` se reescribe o se rechaza | `MAIL_FROM` no es el usuario SMTP ni un alias autorizado | Usa el mismo buzón o configura el alias en el proveedor | +| Llega a spam en Gmail | DKIM/SPF/DMARC ausentes o mal alineados | Revisa DNS y alineación de dominios | +| `550 5.7.1` | IP/dominio sin reputación o PTR incorrecto | Usa el SMTP del proveedor, no un VPS directo | +| Correo omitido en logs | Sin proveedor configurado | Define `MAIL_PROVIDER` + credenciales | +| Funciona en local y no en Vercel | Variables no cargadas en Production | Configúralas en Vercel → Settings → Environment Variables y redeploy | +| Timeout en Vercel | Puerto SMTP bloqueado o proveedor lento | Usa Resend (HTTPS) o el SMTP de un proveedor con puerto 587 | + +> **Vercel**: las funciones serverless pueden tardar en cerrar conexiones SMTP. Para volumen alto usa **Resend** (HTTP) o un backend persistente (Render/VPS). El código reintenta 3 veces con backoff y nunca bloquea la respuesta HTTP. + +--- + +## 7. Checklist de activación + +- [ ] Dominio corporativo comprado y DNS gestionado. +- [ ] Buzones `notificaciones@`, `soporte@`, `dmarc@` creados. +- [ ] SPF publicado (un solo registro). +- [ ] DKIM publicado y verificado en el proveedor. +- [ ] DMARC publicado (`p=none` → `quarantine` → `reject`). +- [ ] `MAIL_FROM` y `SMTP_USER` del mismo dominio. +- [ ] `MAIL_REPLY_TO=soporte@...` y `MAIL_BCC=auditoria@...`. +- [ ] Variables cargadas en Vercel/Render/Docker. +- [ ] `npm run email:test -- tu-correo@...` → llega a Recibidos. +- [ ] `GET /api/admin/email/status` sin warnings. +- [ ] Prueba real: crear pedido → el proveedor recibe correo; emitir factura → el cliente recibe correo. +- [ ] Revisar SPF/DKIM/DMARC en "Mostrar original". +- [ ] mail-tester.com ≥ 9/10. diff --git a/MIGRACION-BACKEND.md b/MIGRACION-BACKEND.md new file mode 100644 index 0000000..c261777 --- /dev/null +++ b/MIGRACION-BACKEND.md @@ -0,0 +1,175 @@ +# Hackathon-Xupply — Backend de producción + +Este repositorio (`cheche2813/Hackathon-Xupply`) contiene **solo el backend** de Xupply +(Express + TypeScript + PostgreSQL + Socket.IO). Es la versión endurecida y migrada +desde `JuanBerro-back/xupply-D` (`app/server`), lista para desplegar en producción. + +- **Auditoría y hallazgos:** `SECURITY-AUDIT.md` +- **Correo enterprise (SPF/DKIM/DMARC):** `EMAIL-ENTERPRISE.md` +- **Variables de entorno:** `.env.example` (local) y `.env.production.example` (producción) + +--- + +## 1. Qué cambió respecto al código anterior + +### Seguridad (P0/P1) + +| Área | Antes | Ahora | +|---|---|---| +| Usuarios demo | `admin` / `demo1234` creados siempre | Solo con `SEED_DEMO_DATA=true`; en producción se **neutralizan** las cuentas heredadas | +| Bootstrap de admin | Ninguno | `ADMIN_USERNAME` + `ADMIN_PASSWORD` (12+ caracteres) si la BD está vacía | +| Productos de proveedor | IDOR (leer/editar/borrar ajenos) | Ownership obligatorio + whitelist de campos + roles | +| Socket.IO | Sin autenticación (`client:identify`) | Handshake con JWT HS256, identidad fresca desde BD, salas derivadas del token | +| Planes | Cualquier usuario se cambiaba de plan | `admin` únicamente, planes en lista blanca | +| Código de entrega | Visible para todos / sin límite | Visible solo a roles autorizados, confirmación con rate limit y comparación en tiempo constante | +| XupAI | Sin límite, estado enviado por el cliente | 30 req/10 min, propuestas en servidor con TTL, topes de tamaño | +| CORS / proxy | `*` | Lista blanca `CLIENT_ORIGIN`, fail-closed en producción, `trust proxy` | +| Errores | Stack traces al cliente | `{ error, requestId }` genérico + log interno | +| Cabeceras | Ninguna | `helmet` (CSP, HSTS, nosniff, frame-options, referrer-policy) + equivalentes en Vercel/Caddy | +| Dashboard | Datos de otros inquilinos y cifras inventadas | Filtrado por `restaurant_id`, sin fallbacks falsos | +| Reseñas | Spam y columnas arbitrarias | 1 por usuario/proveedor, rating 1–5, whitelist | +| Admin | `LIMIT` arbitrario | Paginación acotada (100 / 200) | +| Migraciones | `UPDATE` peligrosos al arrancar | DDL idempotente; sin mutaciones de datos demo | + +### Correo enterprise + +`src/lib/email.ts` soporta SMTP corporativo, Resend y EmailJS (legacy) con autodetección: + +- HTML + texto plano, `Reply-To`, `BCC` de auditoría, cabeceras anti-spam. +- Reintentos con backoff; `sendEmail()` nunca lanza (no rompe pedidos ni facturas). +- Diagnóstico: `GET /api/admin/email/status` y `POST /api/admin/email/test` (solo admin, solo su propio correo). +- Script: `npm run email:test -- correo@dominio.com`. + +Detalle completo en `EMAIL-ENTERPRISE.md`. + +--- + +## 2. Requisitos + +- Node.js 20+ +- PostgreSQL 14+ (16 recomendado) +- Opcional: Docker / Docker Compose para despliegue con TLS automático + +--- + +## 3. Ejecución local + +```bash +npm ci +cp .env.example .env # completa DATABASE_URL y JWT_SECRET +npm run dev # tsx watch src/server.ts +``` + +El esquema se crea/actualiza automáticamente al arrancar (`ensureServerInitialized`). +Sin `SEED_DEMO_DATA=true` no se crean datos de demostración. + +Verificación: + +```bash +npm run typecheck +npm run build +npm start # node dist/server.js +curl http://localhost:4000/health +``` + +--- + +## 4. Variables de entorno imprescindibles + +| Variable | Obligatoria | Descripción | +|---|---|---| +| `DATABASE_URL` | Sí | Cadena de conexión PostgreSQL (`postgres://user:pass@host:5432/db`). | +| `JWT_SECRET` | Sí en producción | 64+ caracteres aleatorios. El servidor no arranca en producción sin él. | +| `JWT_EXPIRES_IN` | Recomendado | `12h` por defecto. | +| `CLIENT_ORIGIN` | Sí en producción | Origen(es) del frontend separados por coma. Sin esto no se acepta CORS cruzado. | +| `SEED_DEMO_DATA` | Sí | `false` en producción (valor por defecto). | +| `ADMIN_USERNAME` / `ADMIN_PASSWORD` | Primer arranque | Crea el administrador inicial si la BD no tiene usuarios. | +| `MAIL_*`, `SMTP_*`, `RESEND_API_KEY` | Para enviar correo | Ver `EMAIL-ENTERPRISE.md`. | +| `DEEPSEEK_API_KEY` / `XUPAI_API_KEY` | Opcional | Agente XupAI. | + +> Genera el secreto JWT con: +> `node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"` + +--- + +## 5. Opciones de despliegue + +### 5.1 Vercel (solo API) + +`vercel.json` ya define el preset Express, el build y las cabeceras de seguridad. + +1. Importa el repo en Vercel. +2. Settings → Environment Variables: `DATABASE_URL`, `JWT_SECRET`, `JWT_EXPIRES_IN`, + `CLIENT_ORIGIN`, `SEED_DEMO_DATA=false`, `ADMIN_USERNAME`, `ADMIN_PASSWORD` y las de correo. +3. Deploy. + +> **Limitación:** Vercel es serverless; **Socket.IO no funciona** ahí. La app debe usar +> polling HTTP o desplegar el backend en Render/VPS/Docker para tiempo real. + +### 5.2 Render + +`render.yaml` crea el servicio y la base de datos. Define en el panel `CLIENT_ORIGIN`, +`ADMIN_USERNAME`, `ADMIN_PASSWORD` y las variables de correo (`sync: false`). +`JWT_SECRET` se genera automáticamente. + +### 5.3 Docker Compose + Caddy (recomendado para producción real) + +```bash +cp .env.production.example .env.production # completa TODOS los valores +docker compose up -d --build +``` + +- `app`: Node 20, usuario `node`, filesystem de solo lectura, `cap_drop: ALL`, healthcheck. +- `db`: PostgreSQL 16 con volumen persistente (el esquema lo crea la app). +- `caddy`: TLS automático (Let's Encrypt) para `DOMAIN`, cabeceras de seguridad y proxy WebSocket. + +Verifica: + +```bash +curl -I https://TU_DOMINIO/health +``` + +### 5.4 Docker suelto + +```bash +docker build -t xupply-backend . +docker run --env-file .env.production -p 4420:4420 xupply-backend +``` + +--- + +## 6. Checklist de puesta en producción + +- [ ] `JWT_SECRET` nuevo y aleatorio (invalida sesiones anteriores). +- [ ] Contraseña de PostgreSQL rotada. +- [ ] `SEED_DEMO_DATA=false`. +- [ ] `ADMIN_USERNAME` / `ADMIN_PASSWORD` definidos en el primer arranque. +- [ ] `CLIENT_ORIGIN` con el dominio real del frontend. +- [ ] Variables de correo cargadas y `npm run email:test -- tu-correo@...` recibido en **Recibidos**. +- [ ] SPF, DKIM y DMARC publicados (ver `EMAIL-ENTERPRISE.md`). +- [ ] Logs `[SECURITY]` revisados: cuentas demo bloqueadas. +- [ ] `/health` responde `200` y no filtra información. +- [ ] Cabeceras verificadas (`content-security-policy`, `strict-transport-security`, `x-frame-options`, `x-content-type-options`). +- [ ] Login real, catálogo, pedido, entrega con código y factura probados. +- [ ] Socket.IO probado **solo** en host persistente (no Vercel). + +Consulta de control de cuentas demo: + +```sql +SELECT id, username, is_active FROM users +WHERE username IN ('admin','gerente','empleado','proveedor','domiciliario'); +``` + +--- + +## 7. Notas de la migración + +- El código se copió desde `xupply-D/app/server` (`src`, `scripts`, `package.json`, + `package-lock.json`, `tsconfig*`, `.env.example`) y se adaptaron los archivos de + despliegue a la raíz de este repo (backend-only). +- `src/lib/migrations.ts` ya **no** ejecuta `UPDATE` sobre usuarios/entregas al arrancar; + las columnas necesarias (`vehicle_type`, `driver_id`, etc.) viven en `schemaSql.ts` + o en migraciones idempotentes. +- El frontend (`app/web`) y la app Android siguen en `xupply-D`. Para construir el APK, + actualiza `DEFAULT_RENDER_URL` con el nuevo dominio del backend. +- La app móvil no usa cookies: sigue enviando `Authorization: Bearer `. diff --git a/README BACKEND.md b/README BACKEND.md index 013934b..4d6e054 100644 --- a/README BACKEND.md +++ b/README BACKEND.md @@ -49,7 +49,13 @@ Backend completo de la plataforma B2B: catálogo, pedidos, inventario (FEFO), fa PORT=4000 DATABASE_URL=postgres://usuario:password@localhost:5432/xupply JWT_SECRET= + JWT_EXPIRES_IN=12h CLIENT_ORIGIN=http://localhost:5173 + # Producción: nunca true (crea usuarios demo con contraseña conocida) + SEED_DEMO_DATA=false + # Solo el primer arranque con la base vacía + ADMIN_USERNAME=admin + ADMIN_PASSWORD= ``` 3. **Base de datos**: crea la base en PostgreSQL (por ejemplo `xupply`) y arranca el servidor; el esquema se crea/actualiza solo. Si prefieres hacerlo manual: @@ -77,6 +83,7 @@ Backend completo de la plataforma B2B: catálogo, pedidos, inventario (FEFO), fa | `npm start` | Ejecuta el build (`dist/server.js`) | | `npm run typecheck` | Verificación de tipos (src + scripts) | | `npm run smoke` | Pruebas de humo del API (requiere server + BD) | +| `npm run email:test -- correo@dominio.com` | Envía un correo real de prueba (ver `EMAIL-ENTERPRISE.md`) | | `npx tsx insert_vehicles.ts` | Siembra vehículos demo | | `node scripts/populate_mock_data.js` | Datos mock adicionales | @@ -107,19 +114,73 @@ Backend completo de la plataforma B2B: catálogo, pedidos, inventario (FEFO), fa | `/api/admin` | Panel de administración | | `/health` | Estado del servicio + base de datos | -Tiempo real: Socket.IO sobre el mismo servidor (salas por usuario, proveedor, pedido y entrega; GPS de entregas solo a partes autorizadas). +Tiempo real: Socket.IO sobre el mismo servidor (salas por usuario, proveedor, pedido y entrega; GPS de entregas solo a partes autorizadas). Requiere un host persistente: **no funciona en Vercel serverless** (usa Render, VPS o Docker). --- -## 👥 Usuarios demo (contraseña: `demo1234`) +## 🔐 Seguridad -`admin`, `gerente`, `empleado`, `proveedor`, `domiciliario` — **cambiar contraseñas en producción**. +Este repo es la versión endurecida tras la auditoría (`SECURITY-AUDIT.md`): + +- Sin usuarios ni contraseñas demo. Los datos de demostración solo se crean con `SEED_DEMO_DATA=true`. +- Administrador inicial vía `ADMIN_USERNAME` / `ADMIN_PASSWORD` (12+ caracteres). +- En producción, las cuentas heredadas que aún usan el hash demo se **desactivan** al arrancar (`neutralizeDemoCredentials`). +- `JWT_SECRET` obligatorio en producción; tokens de 12 h, `HS256`, identidad revalidada contra la BD en cada petición y handshake. +- Socket.IO exige JWT y deriva las salas del token; no existe `client:identify`. +- CORS fail-closed con lista blanca `CLIENT_ORIGIN`. +- Cabeceras `helmet` (CSP, HSTS, `nosniff`, `X-Frame-Options`, `Referrer-Policy`) también en Vercel y Caddy. +- Errores genéricos con `requestId` (sin stack traces al cliente). + +> Si heredaste una base de datos con usuarios demo, al desplegar esta versión y reiniciar se bloquean automáticamente. Revisa los logs `[SECURITY]`. + +--- + +## ✉️ Correo transaccional + +`src/lib/email.ts` soporta tres proveedores con autodetección: + +| Prioridad | Proveedor | Variables | +|---|---|---| +| 1 | SMTP empresarial | `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS` | +| 2 | Resend | `RESEND_API_KEY` | +| 3 | EmailJS (legacy) | `EMAILJS_*` | + +```env +MAIL_PROVIDER=smtp +MAIL_FROM=notificaciones@tudominio.com +MAIL_FROM_NAME=Xupply +MAIL_REPLY_TO=soporte@tudominio.com +MAIL_BCC=auditoria@tudominio.com +APP_URL=https://tudominio.com +``` + +- Usa un **dominio corporativo** (nunca Gmail/Hotmail) y publica **SPF, DKIM y DMARC** para que el correo llegue a Recibidos. +- Diagnóstico admin: `GET /api/admin/email/status` y `POST /api/admin/email/test` (solo al correo del admin autenticado). +- Guía completa (Google Workspace, Microsoft 365, SES, Resend, DNS y diagnóstico): **`EMAIL-ENTERPRISE.md`**. + +--- + +## 🚀 Despliegue + +| Plataforma | Archivo | Notas | +|---|---|---| +| Vercel | `vercel.json` | Solo API; sin Socket.IO. Define las variables en el panel. | +| Render | `render.yaml` | Servicio + base de datos; `JWT_SECRET` autogenerado. | +| Docker Compose + Caddy | `docker-compose.yml`, `Caddyfile` | TLS automático, hardening, WebSocket soportado. | + +```bash +cp .env.production.example .env.production +docker compose up -d --build +``` + +Pasos, variables y checklist completos: **`MIGRACION-BACKEND.md`**. --- -## 🔐 Notas +## 📌 Notas - `JWT_SECRET` es obligatorio en producción; sin él el servidor no arranca (falla cerrado). - `CLIENT_ORIGIN` funciona como lista blanca de CORS (HTTP y Socket.IO). - El login no tiene atajos: solo `bcrypt.compare` contra el hash real. - Los cambios de rol/contraseña invalidan sesiones vía `token_version`. +- No subas `.env`, `.env.production` ni claves al repositorio. diff --git a/SECURITY-AUDIT.md b/SECURITY-AUDIT.md new file mode 100644 index 0000000..263a227 --- /dev/null +++ b/SECURITY-AUDIT.md @@ -0,0 +1,251 @@ +# Auditoría de Seguridad — Xupply Backend + +**Repositorio:** `cheche2813/Hackathon-Xupply` (backend, raíz del repo) +**Origen de los cambios:** auditoría sobre `JuanBerro-back/xupply-D` HEAD y despliegue `https://xupply-d.vercel.app` +**Fecha:** 2026-10-25 +**Alcance:** API Express + Socket.IO (`src`), configuración de despliegue (Vercel, Render, Docker, Caddy) y base de datos PostgreSQL. Las correcciones de SPA (`app/web`) se aplicaron en `xupply-D`; este repo contiene únicamente el backend. +**Objetivo:** dejar el backend listo para la fase de producción. + +--- + +## 1. Resumen ejecutivo + +Se identificaron **3 vulnerabilidades críticas (P0)** y **12 de severidad alta/media (P1)**. Todas las de código están corregidas en esta rama. Quedan **3 riesgos aceptados/documentados** que requieren una decisión de producto o infraestructura. + +| # | Hallazgo | Severidad | Estado | +|---|---|---|---| +| 1 | Credenciales de administrador por defecto (`admin` / `demo1234`) | **P0 — Crítica** | Corregido | +| 2 | IDOR / escritura cruzada en productos de proveedor | **P0 — Crítica** | Corregido | +| 3 | Socket.IO sin autenticación (suplantación de rol y salas) | **P0 — Crítica** | Corregido | +| 4 | Cambio de plan de suscripción por cualquier usuario | P1 — Alta | Corregido | +| 5 | Fuga y bypass del código de confirmación de entrega | P1 — Alta | Corregido | +| 6 | Abuso de XupAI (coste/DoS) y propuestas manipulables | P1 — Alta | Corregido | +| 7 | CORS abierto y `trust proxy` mal configurado | P1 — Alta | Corregido | +| 8 | Fuga de detalles internos en errores 500 | P1 — Alta | Corregido | +| 9 | Ausencia de cabeceras de seguridad | P1 — Alta | Corregido | +| 10 | Fuga entre inquilinos y datos falsos en dashboard | P1 — Alta | Corregido | +| 11 | Bypass de estado `entregado` y usuarios sin inquilino | P1 — Alta | Corregido | +| 12 | Spam de reseñas y asignación arbitraria de columnas | P1 — Alta | Corregido | +| 13 | CRUD de vehículos y sucursales sin aislamiento | P1 — Media/Alta | Corregido | +| 14 | Paginación sin límite en panel admin | P1 — Media | Corregido | +| 15 | Siembra de datos demo y `UPDATE` peligrosos al arrancar | P1 — Media | Corregido | +| 16 | JWT en `localStorage` (robo vía XSS) | P2 — Media | Mitigado / aceptado | +| 17 | Precios de factura controlados por el cliente | P2 — Media | Aceptado (documentado) | +| 18 | Rate limiting en memoria (no distribuido) | P3 — Baja | Documentado | +| 19 | Socket.IO no funciona en Vercel (serverless) | P2 — Operativo | Documentado | + +--- + +## 2. Hallazgos críticos (P0) + +### 2.1 Credenciales de administrador por defecto — CRÍTICO + +**Evidencia (despliegue en vivo, antes del fix):** + +``` +POST https://xupply-d.vercel.app/api/auth/login +{"username":"admin","password":"demo1234"} +→ 200 OK + token con role=admin +``` + +Las credenciales también estaban visibles en la SPA (`app/web/src/pages/Login.tsx` en `xupply-D`), en `README.md` y en `LEER-YA.txt`. Cualquier persona con acceso a la URL podía tomar el control total de la plataforma (usuarios, pedidos, facturación, auditoría). + +**Causa raíz:** el esquema semilla creaba cinco usuarios (`admin`, `gerente`, `empleado`, `proveedor`, `domiciliario`) con el mismo hash bcrypt de `demo1234`, y ese esquema se aplicaba en todos los entornos. + +**Corrección aplicada:** + +- `src/config/db.ts`: `shouldSeedDemoData()` — los datos demo solo se siembran con `SEED_DEMO_DATA=true` (por defecto `false` en producción/Vercel). +- `ensureBootstrapAdmin()`: crea un único administrador a partir de `ADMIN_USERNAME` / `ADMIN_PASSWORD` (mínimo 12 caracteres), nunca credenciales por defecto. +- `neutralizeDemoCredentials()`: en producción, cualquier cuenta heredada que todavía use el hash demo es **desactivada**, se le asigna un hash aleatorio y se invalidan sus tokens. Si coincide con `ADMIN_USERNAME` y hay `ADMIN_PASSWORD`, se rota a la contraseña nueva. +- Se eliminaron las credenciales de demostración del frontend en `xupply-D` (`Login.tsx`, `README.md`, `LEER-YA.txt`); este repo no contiene interfaz. +- `Xupply_postgresql.sql` y `schema.sql` no incluyen usuarios demo; `docker-compose.yml` no monta SQL como init (el esquema lo crea la app), así que no se recrean cuentas con contraseña conocida. + +> ⚠️ **Acción obligatoria al desplegar:** el fix de código no borra las cuentas ya existentes en la base de datos de producción. Al arrancar la nueva versión con `SEED_DEMO_DATA=false`, `neutralizeDemoCredentials()` las bloquea automáticamente. Verifica los logs `[SECURITY]`. + +### 2.2 IDOR en productos de proveedor — CRÍTICO + +**Evidencia:** `GET/PUT/DELETE /api/products/:id` no comprobaba que el producto perteneciera al proveedor del usuario. Un proveedor podía leer, editar y borrar el catálogo de otro cambiando el `id`. + +**Corrección:** `src/routes/products.ts` + +- Lectura/edición/borrado exigen `product.supplier_id === req.user.supplier_id` (o `admin`). +- `POST` fuerza el `supplier_id` del token, ignorando el del body. +- `roleRequired('proveedor_admin', 'admin')` en escritura. +- Validación de precios, stock y campos permitidos (whitelist). + +### 2.3 Socket.IO sin autenticación — CRÍTICO + +**Evidencia:** cualquier cliente podía conectarse sin token y ejecutar `client:identify` con `role=admin`, uniéndose a salas como `admins` y recibiendo pedidos, GPS y auditoría de toda la plataforma. + +**Corrección:** + +- `src/server.ts`: middleware de handshake que exige JWT (`auth.token` o `?token=`), valida `HS256`, consulta la BD y verifica `is_active` + `token_version`. Una sesión revocada ya no puede reconectarse. +- `src/lib/realtime.ts`: las salas se derivan **solo** de la identidad del token (`user:`, `restaurant:`, `supplier:`, `admins`). Se eliminó `client:identify` y los parámetros de identidad por query. +- `join:delivery` y `delivery:position` validan que el usuario sea el conductor asignado, el proveedor dueño o un administrador. +- CORS de Socket.IO fail-closed en producción. +- El cliente web de `xupply-D` (`app/web/src/lib/socket.ts`) envía únicamente el JWT; no existe `client:identify`. + +--- + +## 3. Hallazgos altos (P1) + +### 3.1 Plan de suscripción gratuito +`POST /api/auth/subscription-plan` permitía a cualquier usuario con restaurante cambiarse a un plan premium. Ahora exige `roleRequired('admin')` y valida el plan contra una lista permitida. + +### 3.2 Código de confirmación de entrega +El código se devolvía en las respuestas de pedidos/entregas y `POST /api/deliveries/:id/confirm` no limitaba intentos ni roles. + +- `redactDelivery()` + `canSeeConfirmationCode()`: el código solo lo ven `admin`, el proveedor dueño y el domiciliario asignado. +- `POST /:id/confirm`: solo `gerente`, `empleado` y `admin`; rate limit de 5 intentos / 10 minutos; comparación en tiempo constante. +- `PATCH /:id/status` y `PATCH /api/orders/:id/status` bloquean el paso a `entregado` para roles no autorizados (evita cerrar entregas sin el código). + +### 3.3 Abuso de XupAI +`POST /api/xupai/chat` no tenía límite y aceptaba propuestas/estado enviados por el cliente, lo que permitía quemar créditos del proveedor de IA y confirmar acciones sin pasar por el flujo real. + +- Rate limit por usuario: 30 peticiones / 10 minutos. +- Estado de propuestas en servidor (`pendingProposals`, TTL 10 minutos). +- Topes de longitud de mensaje e historial. +- Los errores del proveedor ya no se reenvían al cliente. + +### 3.4 CORS y proxy +- `CLIENT_ORIGIN` ahora es una lista blanca real. En producción, sin lista, **no se permite ningún origen cruzado** (antes `*`). +- Se eliminó el `*` de `render.yaml`. +- `app.set('trust proxy', 1)` para que `req.ip` (rate limit y auditoría) use la IP real detrás de Vercel/Caddy. + +### 3.5 Fuga de información en errores +`errorHandler` devolvía `err.message` y stack traces. Ahora: + +- Responde `{ error, requestId }` genérico en 500. +- Solo expone mensajes marcados con `expose`/`status < 500`. +- Registra el detalle completo en logs del servidor. + +### 3.6 Cabeceras de seguridad +No había CSP, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy` ni HSTS. + +- `helmet` en `app.ts` con CSP completa (scripts propios, estilos inline, fuentes de Google, imágenes https), HSTS, `X-Frame-Options: DENY`, `nosniff` y `Referrer-Policy`. +- CSP y cabeceras equivalentes en `vercel.json` y `Caddyfile` (defensa en profundidad). +- `x-powered-by` deshabilitado. +- Límite de body JSON a `1mb`. + +### 3.7 Dashboard: fuga entre inquilinos y datos falsos +`/api/dashboard/*` mezclaba datos de otros restaurantes y usaba `.catch()` que devolvía cifras inventadas. Ahora: + +- Cada consulta filtra por el `restaurant_id` real del usuario. +- Se eliminaron todos los fallbacks fabricados. +- Las alertas de stock y el directorio de prospectos respetan el inquilino y solo exponen campos públicos. + +### 3.8 Bypass de estados y usuarios sin inquilino +- `entregado` solo lo puede fijar `admin` en los endpoints de pedidos. +- Los cambios de estado están acotados por rol. +- Los usuarios sin restaurante/proveedor se rechazan por defecto (default-deny) en lugar de permitir acceso global. + +### 3.9 Reseñas +- Whitelist de columnas (evita inyección de campos). +- `rating` entero entre 1 y 5. +- Verificación de que el proveedor exista. +- Una reseña por usuario y proveedor (índice único). + +### 3.10 Vehículos y sucursales +- El CRUD de vehículos valida el `supplier_id` del token. +- Asignación de conductor/vehículo valida que pertenezcan al mismo proveedor. +- Las sucursales se validan contra el restaurante del usuario antes de usarlas en pedidos. + +### 3.11 Paginación del panel admin +`/api/admin/users` y `/api/admin/audit` aceptaban `limit` arbitrario (hasta agotar memoria). Ahora `pagination()` limita a 100 usuarios y 200 filas de auditoría. + +### 3.12 Arranque peligroso +- Se eliminaron `UPDATE users SET supplier_id = 1` y el reseteo de inquilinos al arrancar. +- Se eliminó `repairLegacySeedPasswords()`. +- Migraciones idempotentes: columnas e índices con `IF NOT EXISTS`, índice único de reseñas, `driver_id` en vehículos. + +--- + +## 4. Riesgos aceptados / pendientes + +| Riesgo | Motivo | Mitigación actual | Recomendación | +|---|---|---|---| +| **JWT en `localStorage`** | Cambiar a cookies `httpOnly` implica rehacer el flujo de auth en web + Android. | CSP estricta, tokens de 12 h, `token_version` y validación en BD en cada petición y handshake. | Migrar a cookies `httpOnly` + `SameSite=Strict` y CSRF token en la fase 2. | +| **Precios de factura** (`unit_price` del cliente) | La UI permite precios libres (facturación POS). Solo afecta la contabilidad del propio restaurante; no hay cruce de inquilinos. | Totales recalculados en servidor; validación de cantidades. | Si se requiere integridad fiscal, calcular desde el catálogo y bloquear precios manuales. | +| **Rate limit en memoria** | Sin Redis en la arquitectura actual. | Límites por proceso y por usuario/IP. | Usar Upstash Redis / rate-limit distribuido si se escala a varias instancias. | +| **Socket.IO en Vercel** | Vercel es serverless; no mantiene conexiones persistentes. | La app funciona con polling HTTP; `server.ts` no intenta escuchar en Vercel. | Desplegar el backend en Render/VPS/Docker para tiempo real. | +| **Sin MFA** | Fuera del alcance de la hackathon. | Contraseñas bcrypt (12 rounds), sesiones cortas. | Añadir TOTP para roles `admin`/`gerente`. | + +--- + +## 5. Verificación realizada + +- `npm run typecheck` sin errores (`tsc --noEmit` + `tsconfig.smoke.json`). +- `npm run build` sin errores. +- `npm audit` → 0 vulnerabilidades. +- Verificación en copia limpia: `npm ci` + `typecheck` tras aplicar el parche. +- Pruebas manuales contra el despliegue en vivo (antes del fix): login demo, `/health`, cabeceras, `/socket.io`. +- Revisión estática de todos los routers, middleware, migraciones y configuración de despliegue. + +--- + +## 6. Checklist de despliegue seguro + +1. **Rotar secretos inmediatamente** + - `JWT_SECRET` nuevo (64+ caracteres aleatorios): invalida todas las sesiones. + - Contraseña de la base de datos. + - Claves de XupAI / EmailJS si estuvieron expuestas. +2. **Configurar variables** (ver `.env.production.example`): + - `NODE_ENV=production` + - `JWT_SECRET`, `JWT_EXPIRES_IN=12h` + - `CLIENT_ORIGIN=https://tu-dominio` + - `SEED_DEMO_DATA=false` + - `ADMIN_USERNAME` / `ADMIN_PASSWORD` (solo el primer arranque) +3. **Verificar que las cuentas demo quedaron bloqueadas** + - Revisar logs `[SECURITY] ... bloqueadas`. + - Consulta de control: + ```sql + SELECT id, username, is_active FROM users + WHERE username IN ('admin','gerente','empleado','proveedor','domiciliario'); + ``` +4. **Confirmar cabeceras** con `curl -I https://tu-dominio/`: + - `content-security-policy`, `x-content-type-options`, `x-frame-options`, `referrer-policy`, `strict-transport-security`. +5. **Confirmar que `/health` no filtra información** y que responde 503 si la BD falla. +6. **Probar el flujo completo** con una cuenta real: login, catálogo, pedido, entrega, confirmación con código, facturación. +7. **Realtime:** verificar Socket.IO solo en el host persistente (no Vercel). + +--- + +## 7. Archivos modificados + +``` +src/app.ts cabeceras, CORS, límites, health +src/server.ts auth Socket.IO + CORS fail-closed +src/config/db.ts seed gate, bootstrap admin, neutralización demo +src/config/schemaSql.ts (sin cambios; el split se hace en db.ts) +src/lib/migrations.ts migraciones idempotentes + neutralización +src/lib/realtime.ts salas derivadas del JWT +src/lib/email.ts SMTP/Resend/EmailJS, reintentos, plantilla corporativa +src/lib/oc.ts validación de proveedor en productos OC +src/middleware/auth.ts identidad fresca desde BD, HS256, 12 h +src/middleware/error.ts errores genéricos + requestId +src/routes/auth.ts planes admin-only, logout, change-password +src/routes/products.ts ownership + whitelist + roles +src/routes/orders.ts sucursales, estados, códigos +src/routes/deliveries.ts redacción de códigos, rate limit, vehículos +src/routes/dashboard.ts aislamiento por inquilino, sin datos falsos +src/routes/reviews.ts validación + anti-spam +src/routes/restaurants.ts whitelist + ownership +src/routes/suppliers.ts whitelist + roles +src/routes/admin.ts paginación acotada + endpoints de correo +src/routes/xupai.ts rate limit + estado en servidor +scripts/email-test.ts prueba de correo enterprise +scripts/smoke.ts exige SMOKE_PASSWORD +EMAIL-ENTERPRISE.md SPF/DKIM/DMARC y entregabilidad +SECURITY-AUDIT.md este documento +MIGRACION-BACKEND.md despliegue y checklist de producción +vercel.json CSP + cabeceras + cache +Caddyfile CSP + cabeceras + health check +Dockerfile non-root, prod-deps, healthcheck +docker-compose.yml hardening, sin SQL demo, SEED_DEMO_DATA=false +.dockerignore contexto de build mínimo +render.yaml sin CORS *, bootstrap admin, 12 h +.env.example / .env.production.example plantillas sin secretos +.github/workflows/ci.yml typecheck + build + npm audit +.gitignore secretos, dist y artefactos ignorados +package.json helmet + nodemailer + script email:test +``` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a063551 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,103 @@ +services: + app: + build: . + init: true + restart: unless-stopped + env_file: + - .env.production + environment: + NODE_ENV: production + PORT: "4420" + DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB} + # Nunca sembrar usuarios/negocios de demostración en producción. + SEED_DEMO_DATA: "false" + depends_on: + db: + condition: service_healthy + expose: + - "4420" + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + healthcheck: + test: + [ + "CMD", + "node", + "-e", + "fetch('http://127.0.0.1:4420/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))", + ] + interval: 30s + timeout: 5s + retries: 3 + start_period: 30s + logging: + options: + max-size: "10m" + max-file: "3" + + db: + image: postgres:16-alpine + restart: unless-stopped + env_file: + - .env.production + environment: + POSTGRES_DB: ${POSTGRES_DB} + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + volumes: + - postgres_data:/var/lib/postgresql/data + # El esquema se crea desde la aplicación (initDatabase). No se monta el + # SQL de referencia porque incluye usuarios demo con contraseña conocida. + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}", + ] + interval: 5s + timeout: 5s + retries: 20 + security_opt: + - no-new-privileges:true + logging: + options: + max-size: "10m" + max-file: "3" + + caddy: + image: caddy:2-alpine + restart: unless-stopped + depends_on: + app: + condition: service_healthy + ports: + - "80:80" + - "443:443" + env_file: + - .env.production + environment: + DOMAIN: ${DOMAIN} + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro + - caddy_data:/data + - caddy_config:/config + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + cap_add: + - NET_BIND_SERVICE + logging: + options: + max-size: "10m" + max-file: "3" + +volumes: + postgres_data: + caddy_data: + caddy_config: diff --git a/package-lock.json b/package-lock.json index 8d9543c..ea64760 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,8 +11,10 @@ "bcryptjs": "^2.4.3", "cors": "^2.8.5", "dotenv": "^16.4.5", - "express": "^4.19.2", + "express": "^4.22.3", + "helmet": "^8.3.0", "jsonwebtoken": "^9.0.2", + "nodemailer": "^10.2.1", "pg": "^8.12.0", "socket.io": "^4.7.5" }, @@ -22,6 +24,7 @@ "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.6", "@types/node": "^20.14.0", + "@types/nodemailer": "^8.0.2", "@types/pg": "^8.11.6", "tsx": "^4.16.0", "typescript": "^5.5.0" @@ -579,6 +582,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/pg": { "version": "8.23.1", "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", @@ -639,9 +652,9 @@ } }, "node_modules/@types/ws": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", - "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", "license": "MIT", "dependencies": { "@types/node": "*" @@ -666,6 +679,15 @@ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", "license": "MIT" }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "license": "MIT", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, "node_modules/bcryptjs": { "version": "2.4.3", "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", @@ -673,9 +695,9 @@ "license": "MIT" }, "node_modules/body-parser": { - "version": "1.20.8", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz", - "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==", + "version": "1.20.9", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz", + "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==", "license": "MIT", "dependencies": { "bytes": "~3.1.2", @@ -872,9 +894,9 @@ } }, "node_modules/engine.io": { - "version": "6.6.11", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.11.tgz", - "integrity": "sha512-z34mGpLoY/82ZbkX1LqGMIaf3wjVMPL6gVC681QDqnmzJ26synI8qAE32P+a7UazmpJZ8UGrFIeAavgRfXzYrg==", + "version": "6.6.10", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.10.tgz", + "integrity": "sha512-9/lX2bdlizlCXMHRMOIm03VBQHQYC7VvydcxtTAUJRxNW1QzM/2PMFSmr6h/lCiMHcyCP6abK+t9Q+j4vekk8Q==", "license": "MIT", "dependencies": { "@types/cors": "^2.8.12", @@ -1189,6 +1211,18 @@ "node": ">= 0.4" } }, + "node_modules/helmet": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", + "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/EvanHahn" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -1411,6 +1445,15 @@ "node": ">= 0.6" } }, + "node_modules/nodemailer": { + "version": "10.2.1", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.1.tgz", + "integrity": "sha512-ZrDNsPFoDMwefNs7sJwrYiEJ/CG4ClJWDZv05iNJsEBWa8GRDry1QJHTJxsuTAY9eDDKjX4k+q3SxslXJOao7w==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -1605,9 +1648,9 @@ } }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.16.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", + "integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -1806,12 +1849,13 @@ } }, "node_modules/socket.io": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.4.tgz", - "integrity": "sha512-9ZV9zg8vN8hO3Y25DhR7nUkJ1VDnBhq5O/JrXhFT9s6+F0gqytSASTHVfCFc2mJXaTfARroErplXlzFWwETZqQ==", + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz", + "integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==", "license": "MIT", "dependencies": { "accepts": "~1.3.4", + "base64id": "~2.0.0", "cors": "~2.8.5", "debug": "~4.4.1", "engine.io": "~6.6.0", @@ -1942,9 +1986,9 @@ } }, "node_modules/tsx": { - "version": "4.23.15", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", - "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "version": "4.23.13", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.13.tgz", + "integrity": "sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 75df972..76be67a 100644 --- a/package.json +++ b/package.json @@ -8,14 +8,17 @@ "build": "tsc", "start": "node dist/server.js", "typecheck": "tsc --noEmit && tsc -p tsconfig.smoke.json", - "smoke": "tsx scripts/smoke.ts" + "smoke": "tsx scripts/smoke.ts", + "email:test": "tsx scripts/email-test.ts" }, "dependencies": { "bcryptjs": "^2.4.3", "cors": "^2.8.5", "dotenv": "^16.4.5", - "express": "^4.19.2", + "express": "^4.22.3", + "helmet": "^8.3.0", "jsonwebtoken": "^9.0.2", + "nodemailer": "^10.2.1", "pg": "^8.12.0", "socket.io": "^4.7.5" }, @@ -25,8 +28,9 @@ "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.6", "@types/node": "^20.14.0", + "@types/nodemailer": "^8.0.2", "@types/pg": "^8.11.6", "tsx": "^4.16.0", "typescript": "^5.5.0" } -} \ No newline at end of file +} diff --git a/render.yaml b/render.yaml new file mode 100644 index 0000000..4da100f --- /dev/null +++ b/render.yaml @@ -0,0 +1,51 @@ +services: + - type: web + name: xupply-backend + runtime: node + buildCommand: npm ci --no-audit --no-fund && npm run build + startCommand: node dist/server.js + healthCheckPath: /health + envVars: + - key: NODE_ENV + value: production + # Dominio(s) del frontend separados por coma. Sin lista, en producción no + # se acepta ningún origen cruzado (fail-closed). + - key: CLIENT_ORIGIN + sync: false + - key: JWT_SECRET + generateValue: true + - key: JWT_EXPIRES_IN + value: 12h + - key: SEED_DEMO_DATA + value: "false" + - key: ADMIN_USERNAME + sync: false + - key: ADMIN_PASSWORD + sync: false + # Correo transaccional (ver EMAIL-ENTERPRISE.md) + - key: MAIL_PROVIDER + sync: false + - key: MAIL_FROM + sync: false + - key: MAIL_REPLY_TO + sync: false + - key: SMTP_HOST + sync: false + - key: SMTP_PORT + sync: false + - key: SMTP_USER + sync: false + - key: SMTP_PASS + sync: false + - key: RESEND_API_KEY + sync: false + - key: DATABASE_URL + fromDatabase: + name: xupply-db + property: connectionString + +databases: + - name: xupply-db + databaseName: xupply + user: xupply + plan: free diff --git a/scripts/email-test.ts b/scripts/email-test.ts new file mode 100644 index 0000000..d166a90 --- /dev/null +++ b/scripts/email-test.ts @@ -0,0 +1,39 @@ +import dotenv from 'dotenv'; +import { getEmailStatus, sendTestEmail } from '../src/lib/email'; + +dotenv.config(); + +async function main() { + const to = (process.argv[2] || process.env.TEST_EMAIL_TO || '').trim(); + if (!to) { + console.error('Uso: npm run email:test -- correo@tu-dominio.com'); + process.exit(1); + } + + const status = getEmailStatus(); + console.log('Proveedor :', status.provider); + console.log('From :', status.from ?? '(sin configurar)'); + console.log('Reply-To :', status.reply_to ?? '(sin configurar)'); + console.log('BCC :', status.bcc ?? '(sin configurar)'); + if (status.warnings.length > 0) { + for (const warning of status.warnings) console.warn('ADVERTENCIA:', warning); + } + if (!status.configured) { + console.error('No hay proveedor de correo configurado. Revisa .env.example / EMAIL-ENTERPRISE.md'); + process.exit(1); + } + + console.log(`\nEnviando correo de prueba a ${to}...`); + const result = await sendTestEmail(to); + if (result.ok) { + console.log('OK: correo aceptado por el proveedor. Revisa la bandeja de entrada (y spam).'); + process.exit(0); + } + console.error('ERROR: el proveedor rechazó el envío. Revisa los logs anteriores.'); + process.exit(1); +} + +main().catch((err) => { + console.error('ERROR inesperado:', (err as Error)?.message || err); + process.exit(1); +}); diff --git a/scripts/smoke.ts b/scripts/smoke.ts index b79c76d..0197be6 100644 --- a/scripts/smoke.ts +++ b/scripts/smoke.ts @@ -33,7 +33,13 @@ async function run() { const baseUrl = `http://localhost:${port}`; const roles = ['admin', 'gerente', 'empleado', 'proveedor_admin', 'domiciliario']; - const pwd = process.env.SMOKE_PASSWORD || 'demo1234'; + // Sin contraseña por defecto: evita ejecutar el smoke test contra una base + // real usando las credenciales demo conocidas. + const pwd = process.env.SMOKE_PASSWORD; + if (!pwd) { + console.error('ERROR: define SMOKE_PASSWORD con la contraseña de los usuarios de prueba.'); + process.exit(1); + } const tokens: Record = {}; diff --git a/src/app.ts b/src/app.ts index 2519176..8109ab0 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,5 +1,6 @@ import express from 'express'; import cors from 'cors'; +import helmet from 'helmet'; import path from 'path'; import fs from 'fs'; import authRouter from './routes/auth'; @@ -27,37 +28,68 @@ import { notFound, errorHandler } from './middleware/error'; export function createApp() { const app = express(); + const isProduction = process.env.NODE_ENV === 'production' || process.env.VERCEL === '1'; const configuredOrigins = (process.env.CLIENT_ORIGIN ?? '') .split(',') .map((origin) => origin.trim()) - .filter(Boolean); + .filter((origin) => Boolean(origin) && origin !== '*'); + + // Detrás de Vercel / Render / Caddy siempre hay un proxy: sin esto `req.ip` + // devuelve la IP del proxy y el rate-limit (y la auditoría) quedan inútiles. + app.set('trust proxy', 1); + app.disable('x-powered-by'); + + // Cabeceras de seguridad. La CSP se define también aquí para despliegues + // que no pasan por un borde con cabeceras propias (Render, VPS, Docker sin + // Caddy). En Vercel/Caddy se refuerza en el borde. + app.use( + helmet({ + contentSecurityPolicy: { + useDefaults: false, + directives: { + defaultSrc: ["'self'"], + baseUri: ["'self'"], + objectSrc: ["'none'"], + frameAncestors: ["'none'"], + formAction: ["'self'"], + scriptSrc: ["'self'"], + styleSrc: ["'self'", "'unsafe-inline'"], + imgSrc: ["'self'", 'data:', 'blob:', 'https:'], + fontSrc: ["'self'", 'data:', 'https://fonts.gstatic.com'], + connectSrc: ["'self'", 'https:', 'wss:'], + manifestSrc: ["'self'"], + workerSrc: ["'self'", 'blob:'], + }, + }, + crossOriginEmbedderPolicy: false, + crossOriginResourcePolicy: { policy: 'cross-origin' }, + frameguard: { action: 'deny' }, + }) + ); app.use( cors({ origin: (origin: string | undefined, cb: (err: Error | null, allow?: boolean) => void) => { - // Permitir peticiones sin Origin (server-to-server, curl) y, en desarrollo, - // cuando no hay CLIENT_ORIGIN configurado. En producción se exige la lista blanca. - if (!origin || configuredOrigins.length === 0 || configuredOrigins.includes(origin)) { - return cb(null, true); - } - return cb(null, false); + // Peticiones sin Origin (server-to-server, curl, apps nativas) se permiten. + if (!origin) return cb(null, true); + if (configuredOrigins.includes(origin)) return cb(null, true); + // Fail-closed: sin lista blanca configurada, en producción NO se permite + // ningún origen cruzado (antes se permitían todos). + return cb(null, !isProduction); }, credentials: true, }) ); - app.use(express.json()); + // Límite explícito: evita peticiones gigantes que agoten memoria/CPU. + app.use(express.json({ limit: '1mb' })); // === 1. RUTAS DE DIAGNÓSTICO Y HEALTHCHECK (RESPUESTA INMEDIATA) === const healthHandler = async (_req: express.Request, res: express.Response) => { try { const resolved = resolveDatabaseUrl(); if (process.env.VERCEL === '1' && !resolved.isConfigured) { - return res.status(200).json({ - status: 'ok', - service: 'xupply-api', - db: 'missing_env', - message: 'DATABASE_URL (o POSTGRES_URL) no está configurada en Vercel Settings -> Environment Variables.', - }); + // Mensaje genérico: no revelar nombres de variables ni detalles de infra. + return res.status(503).json({ status: 'degraded', service: 'xupply-api' }); } const testRes = await query("SELECT to_regclass('public.users') as has_users"); return res.status(200).json({ @@ -67,11 +99,7 @@ export function createApp() { tables_ready: Boolean(testRes.rows[0]?.has_users), }); } catch { - return res.status(200).json({ - status: 'ok', - service: 'xupply-api', - db: 'error', - }); + return res.status(503).json({ status: 'degraded', service: 'xupply-api' }); } }; app.get('/health', healthHandler); diff --git a/src/config/db.ts b/src/config/db.ts index b510d3a..cca94c6 100644 --- a/src/config/db.ts +++ b/src/config/db.ts @@ -1,9 +1,36 @@ import { Pool } from 'pg'; +import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; import dotenv from 'dotenv'; import { SCHEMA_SQL } from './schemaSql'; dotenv.config(); +/** + * El esquema base incluye datos de referencia (roles, permisos) y, al final, + * datos de demostración (restaurantes, proveedores, productos y usuarios con + * contraseña conocida). En producción NO se siembran los datos demo salvo que + * se habilite explícitamente SEED_DEMO_DATA=true. + */ +function splitSchema(): { schema: string; demo: string } { + const demoStart = SCHEMA_SQL.indexOf('-- Restaurantes'); + const viewsStart = SCHEMA_SQL.indexOf('-- VISTAS'); + if (demoStart === -1 || viewsStart === -1 || viewsStart <= demoStart) { + return { schema: SCHEMA_SQL, demo: '' }; + } + return { + schema: SCHEMA_SQL.slice(0, demoStart) + SCHEMA_SQL.slice(viewsStart), + demo: SCHEMA_SQL.slice(demoStart, viewsStart), + }; +} + +export function shouldSeedDemoData(): boolean { + const flag = (process.env.SEED_DEMO_DATA ?? '').trim().toLowerCase(); + if (['true', '1', 'yes', 'si'].includes(flag)) return true; + if (['false', '0', 'no'].includes(flag)) return false; + return process.env.NODE_ENV !== 'production' && process.env.VERCEL !== '1'; +} + export function resolveDatabaseUrl(): { url: string; isConfigured: boolean; source: string } { if (process.env.DATABASE_URL && process.env.DATABASE_URL.trim()) { return { url: process.env.DATABASE_URL.trim(), isConfigured: true, source: 'DATABASE_URL' }; @@ -74,23 +101,137 @@ export async function initDatabase() { const res = await pool.query("SELECT to_regclass('public.users')"); if (!res.rows[0]?.to_regclass) { - console.log('[DB] Inicializando esquema de base de datos PostgreSQL desde SCHEMA_SQL...'); - await pool.query(SCHEMA_SQL); - console.log('[DB] Esquema y usuarios creados exitosamente.'); + console.log('[DB] Inicializando esquema de base de datos PostgreSQL...'); + const { schema, demo } = splitSchema(); + await pool.query(schema); + if (shouldSeedDemoData() && demo) { + await pool.query(demo); + console.log('[DB] Esquema y datos de demostración creados exitosamente.'); + console.warn('[DB] ATENCIÓN: los usuarios demo usan contraseñas conocidas. No uses este modo en producción.'); + } else { + console.log('[DB] Esquema creado sin datos de demostración (SEED_DEMO_DATA deshabilitado).'); + } } else { console.log('[DB] Tablas de base de datos verificadas.'); - // Make sure the admin user is a super admin - try { + } + + await ensureBootstrapAdmin(); + } catch (err) { + console.error('[DB] Error verificando/inicializando base de datos:', err); + throw err; + } +} + +/** + * Hash bcrypt compartido por todos los usuarios demo del esquema original + * (contraseña `demo1234`). No se usa para autenticar: solo para localizar + * cuentas heredadas que siguen siendo vulnerables. + */ +const KNOWN_DEMO_HASH = '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e'; + +/** + * Neutraliza cuentas heredadas que todavía usan la contraseña demo conocida. + * Se ejecuta solo cuando el sembrado demo está deshabilitado (producción). + * + * - Si el usuario coincide con `ADMIN_USERNAME` y hay `ADMIN_PASSWORD` válida, + * se rota su contraseña y se mantiene activo. + * - Cualquier otra cuenta con ese hash se desactiva y se le asigna un hash + * aleatorio inutilizable, invalidando además sus tokens (`token_version`). + */ +export async function neutralizeDemoCredentials(): Promise { + if (shouldSeedDemoData()) return; + try { + const rows = await pool.query( + 'SELECT id, username FROM users WHERE password_hash = $1', + [KNOWN_DEMO_HASH] + ); + if (!rows.rowCount) return; + + const adminUsername = (process.env.ADMIN_USERNAME ?? '').trim(); + const adminPassword = process.env.ADMIN_PASSWORD ?? ''; + let rotated = 0; + let blocked = 0; + + for (const row of rows.rows as Array<{ id: number; username: string }>) { + if (adminUsername && row.username === adminUsername && adminPassword.length >= 12) { + const hash = await bcrypt.hash(adminPassword, 12); await pool.query( - `UPDATE users SET restaurant_id = NULL, branch_id = NULL, name = 'Super Administrador' WHERE username = 'admin' AND role_id = 1` + `UPDATE users + SET password_hash = $1, + is_active = TRUE, + token_version = COALESCE(token_version, 1) + 1 + WHERE id = $2`, + [hash, row.id] ); - console.log('[DB] Admin user updated to Super Admin.'); - } catch (e) { - console.error('[DB] Error updating admin user:', e); + rotated += 1; + continue; } + const unusable = await bcrypt.hash(crypto.randomBytes(32).toString('hex'), 12); + await pool.query( + `UPDATE users + SET password_hash = $1, + is_active = FALSE, + token_version = COALESCE(token_version, 1) + 1 + WHERE id = $2`, + [unusable, row.id] + ); + blocked += 1; + } + + if (rotated > 0) { + console.warn( + `[SECURITY] ${rotated} cuenta(s) demo actualizadas con ADMIN_PASSWORD (usuario: ${adminUsername}).` + ); + } + if (blocked > 0) { + console.warn( + `[SECURITY] ${blocked} cuenta(s) bloqueadas por usar la contraseña demo conocida. ` + + 'Define ADMIN_USERNAME/ADMIN_PASSWORD o restablece sus contraseñas desde el panel.' + ); } } catch (err) { - console.error('[DB] Error verificando/inicializando base de datos:', err); - throw err; + console.error( + '[SECURITY] No se pudieron neutralizar las credenciales demo:', + (err as Error)?.message + ); } -} \ No newline at end of file +} + +/** + * En despliegues sin datos demo no existe ningún usuario. Si se definen + * ADMIN_USERNAME y ADMIN_PASSWORD, se crea el administrador inicial una sola + * vez (idempotente). Nunca se crean credenciales por defecto. + */ +async function ensureBootstrapAdmin(): Promise { + if (shouldSeedDemoData()) return; + const username = (process.env.ADMIN_USERNAME ?? '').trim(); + const password = process.env.ADMIN_PASSWORD ?? ''; + if (!username || !password) { + const anyUser = await pool.query('SELECT 1 FROM users LIMIT 1'); + if (!anyUser.rowCount) { + console.warn( + '[DB] No hay usuarios y ADMIN_USERNAME/ADMIN_PASSWORD no están definidos. ' + + 'Define ambas variables (contraseña de 12+ caracteres) para crear el administrador inicial.' + ); + } + return; + } + if (password.length < 12) { + console.warn('[DB] ADMIN_PASSWORD debe tener al menos 12 caracteres. No se creó el administrador inicial.'); + return; + } + const role = await pool.query("SELECT id FROM roles WHERE name = 'admin'"); + if (!role.rowCount) { + console.warn('[DB] El rol admin no existe todavía; no se creó el administrador inicial.'); + return; + } + const exists = await pool.query('SELECT id FROM users WHERE username = $1', [username]); + if (exists.rowCount) return; + const hash = await bcrypt.hash(password, 12); + await pool.query( + `INSERT INTO users (username, password_hash, name, role_id) + VALUES ($1, $2, 'Administrador', $3)`, + [username, hash, role.rows[0].id] + ); + console.log(`[DB] Administrador inicial creado: ${username}`); +} diff --git a/src/config/schemaSql.ts b/src/config/schemaSql.ts index 037bcc8..5f922c4 100644 --- a/src/config/schemaSql.ts +++ b/src/config/schemaSql.ts @@ -1,2 +1,2 @@ // Archivo autogenerado para asegurar que el esquema PostgreSQL se incluye en la build de Vercel -export const SCHEMA_SQL = "-- ============================================================\n-- XUPPLY IA - Esquema de Base de Datos PostgreSQL\n-- Plataforma B2B ERP / Ecosistema Logístico con IA\n-- Surtesoft - v2.0\n-- ============================================================\n\n-- ------------------------------------------------------------\n-- TIPOS ENUM personalizados\n-- ------------------------------------------------------------\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'order_status') THEN\n CREATE TYPE order_status AS ENUM ('nuevo', 'confirmado', 'preparando', 'despachado', 'en_camino', 'entregado', 'cancelado');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_mode') THEN\n CREATE TYPE invoice_mode AS ENUM ('electronica', 'pos', 'comandas');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_id_type') THEN\n CREATE TYPE invoice_id_type AS ENUM ('nit', 'cedula', 'email', 'Pasaporte');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'payment_method') THEN\n CREATE TYPE payment_method AS ENUM ('Efectivo', 'Tarjeta', 'Nequi', 'PSE', 'Daviplata', 'Credito');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_status') THEN\n CREATE TYPE invoice_status AS ENUM ('borrador', 'emitida', 'pagada', 'anulada');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_stock_status') THEN\n CREATE TYPE inventory_stock_status AS ENUM ('critical', 'low', 'normal');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'accounting_type') THEN\n CREATE TYPE accounting_type AS ENUM ('ingreso', 'egreso');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'vehicle_type') THEN\n CREATE TYPE vehicle_type AS ENUM ('moto', 'furgon', 'camion', 'camioneta');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'vehicle_status') THEN\n CREATE TYPE vehicle_status AS ENUM ('disponible', 'en_ruta', 'cargando', 'mantenimiento');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'delivery_status') THEN\n CREATE TYPE delivery_status AS ENUM ('asignado', 'en_camino', 'llegando', 'entregado', 'fallido');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_movement_type') THEN\n CREATE TYPE inventory_movement_type AS ENUM ('entrada', 'salida', 'ajuste', 'merma');\n END IF;\nEND $$;\n\n-- ------------------------------------------------------------\n-- TABLA: roles\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS roles (\n id SERIAL PRIMARY KEY,\n name VARCHAR(50) NOT NULL UNIQUE,\n display_name VARCHAR(100) NOT NULL,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: permissions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS permissions (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL UNIQUE,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: role_permissions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS role_permissions (\n role_id INT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n permission_id INT NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,\n PRIMARY KEY (role_id, permission_id)\n);\n\n-- ------------------------------------------------------------\n-- TABLA: restaurants\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS restaurants (\n id SERIAL PRIMARY KEY,\n name VARCHAR(200) NOT NULL,\n nit VARCHAR(20) UNIQUE,\n phone VARCHAR(20),\n email VARCHAR(200),\n address VARCHAR(500),\n city VARCHAR(100) DEFAULT 'Bucaramanga',\n department VARCHAR(100) DEFAULT 'Santander',\n logo_url VARCHAR(500),\n category VARCHAR(100),\n subscription_plan VARCHAR(50),\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: branches\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS branches (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n name VARCHAR(200) NOT NULL,\n address VARCHAR(500),\n phone VARCHAR(20),\n is_main BOOLEAN DEFAULT FALSE,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: users\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n username VARCHAR(50) NOT NULL UNIQUE,\n password_hash VARCHAR(255) NOT NULL,\n name VARCHAR(200) NOT NULL,\n email VARCHAR(200),\n phone VARCHAR(20),\n role_id INT NOT NULL REFERENCES roles(id),\n restaurant_id INT REFERENCES restaurants(id) ON DELETE SET NULL,\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n supplier_id INT,\n avatar_url VARCHAR(500),\n vehicle_type VARCHAR(50),\n vehicle_plate VARCHAR(50),\n is_active BOOLEAN DEFAULT TRUE,\n last_login TIMESTAMP NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: suppliers\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS suppliers (\n id SERIAL PRIMARY KEY,\n name VARCHAR(200) NOT NULL,\n nit VARCHAR(20) UNIQUE,\n category VARCHAR(100),\n phone VARCHAR(20),\n email VARCHAR(200),\n address VARCHAR(500),\n city VARCHAR(100) DEFAULT 'Bucaramanga',\n logo_url VARCHAR(500),\n rating DECIMAL(2,1) DEFAULT 0.0,\n review_count INT DEFAULT 0,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- FK de users hacia suppliers\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_users_supplier') THEN\n ALTER TABLE users ADD CONSTRAINT fk_users_supplier\n FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL;\n END IF;\nEND $$;\n\n-- ------------------------------------------------------------\n-- TABLA: product_categories\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS product_categories (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL UNIQUE,\n description TEXT,\n icon VARCHAR(50),\n sort_order INT DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: products\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS products (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n category_id INT REFERENCES product_categories(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n description TEXT,\n sku VARCHAR(50),\n unit VARCHAR(30) NOT NULL DEFAULT 'kg',\n price_per_unit DECIMAL(12,2) NOT NULL,\n min_order_qty DECIMAL(10,2) DEFAULT 1,\n stock_available DECIMAL(10,2) DEFAULT 0,\n image_url VARCHAR(500),\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: inventory\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS inventory (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n category VARCHAR(100),\n unit VARCHAR(30) NOT NULL DEFAULT 'kg',\n current_stock DECIMAL(10,2) DEFAULT 0,\n min_stock DECIMAL(10,2) DEFAULT 0,\n max_stock DECIMAL(10,2) DEFAULT 0,\n avg_daily_usage DECIMAL(10,2) DEFAULT 0,\n cost_per_unit DECIMAL(12,2) DEFAULT 0,\n batch_date DATE,\n expiry_date DATE,\n stock_status inventory_stock_status DEFAULT 'normal',\n supplier_id INT REFERENCES suppliers(id) ON DELETE SET NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_inventory_restaurant ON inventory(restaurant_id);\nCREATE INDEX idx_inventory_stock_status ON inventory(stock_status);\nCREATE INDEX idx_inventory_expiry ON inventory(expiry_date);\n\n-- ------------------------------------------------------------\n-- TABLA: menu_products\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS menu_products (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n name VARCHAR(200) NOT NULL,\n description TEXT,\n category VARCHAR(100),\n price DECIMAL(12,2) NOT NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: recipes\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS recipes (\n id SERIAL PRIMARY KEY,\n menu_product_id INT NOT NULL REFERENCES menu_products(id) ON DELETE CASCADE,\n inventory_id INT NOT NULL REFERENCES inventory(id) ON DELETE CASCADE,\n quantity DECIMAL(10,4) NOT NULL,\n unit VARCHAR(30) NOT NULL,\n cost_per_unit DECIMAL(12,2) DEFAULT 0,\n waste_pct DECIMAL(5,2) DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: orders\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS orders (\n id SERIAL PRIMARY KEY,\n order_code VARCHAR(20) NOT NULL UNIQUE,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n supplier_id INT NOT NULL REFERENCES suppliers(id),\n status order_status DEFAULT 'nuevo',\n total DECIMAL(12,2) DEFAULT 0,\n notes TEXT,\n delivery_address VARCHAR(500),\n requested_delivery_date TIMESTAMP,\n confirmed_at TIMESTAMP NULL,\n dispatched_at TIMESTAMP NULL,\n delivered_at TIMESTAMP NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_orders_status ON orders(status);\nCREATE INDEX idx_orders_restaurant ON orders(restaurant_id);\nCREATE INDEX idx_orders_supplier ON orders(supplier_id);\nCREATE INDEX idx_orders_created ON orders(created_at);\n\n-- ------------------------------------------------------------\n-- TABLA: order_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS order_items (\n id SERIAL PRIMARY KEY,\n order_id INT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,\n product_id INT REFERENCES products(id) ON DELETE SET NULL,\n inventory_id INT REFERENCES inventory(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit VARCHAR(30) NOT NULL,\n unit_price DECIMAL(12,2) DEFAULT 0,\n subtotal DECIMAL(12,2) DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: invoices\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS invoices (\n id SERIAL PRIMARY KEY,\n invoice_code VARCHAR(30) NOT NULL UNIQUE,\n cufe VARCHAR(100),\n mode invoice_mode DEFAULT 'electronica',\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n supplier_id INT REFERENCES suppliers(id) ON DELETE SET NULL,\n order_id INT REFERENCES orders(id) ON DELETE SET NULL,\n client_name VARCHAR(200),\n client_id_number VARCHAR(30),\n client_id_type invoice_id_type DEFAULT 'cedula',\n client_email VARCHAR(200),\n client_address VARCHAR(500),\n subtotal DECIMAL(12,2) DEFAULT 0,\n iva_rate DECIMAL(5,2) DEFAULT 19.00,\n iva_amount DECIMAL(12,2) DEFAULT 0,\n impoconsumo_rate DECIMAL(5,2) DEFAULT 8.00,\n impoconsumo_amount DECIMAL(12,2) DEFAULT 0,\n total DECIMAL(12,2) DEFAULT 0,\n payment_method payment_method DEFAULT 'Efectivo',\n status invoice_status DEFAULT 'borrador',\n motivo TEXT,\n mesa VARCHAR(10),\n mesero VARCHAR(100),\n issued_at TIMESTAMP NULL,\n paid_at TIMESTAMP NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_invoices_status ON invoices(status);\nCREATE INDEX idx_invoices_restaurant ON invoices(restaurant_id);\nCREATE INDEX idx_invoices_date ON invoices(issued_at);\n\n-- ------------------------------------------------------------\n-- TABLA: invoice_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS invoice_items (\n id SERIAL PRIMARY KEY,\n invoice_id INT NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,\n description VARCHAR(300) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit_price DECIMAL(12,2) NOT NULL,\n subtotal DECIMAL(12,2) NOT NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: supplier_reviews\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS Reseña (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n reviewer_name VARCHAR(200),\n rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),\n comment TEXT,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: accounting_transactions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS accounting_transactions (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n type accounting_type NOT NULL,\n amount DECIMAL(12,2) NOT NULL,\n description VARCHAR(500),\n category VARCHAR(100),\n reference_type VARCHAR(50),\n reference_id INT,\n payment_method VARCHAR(50),\n transaction_date DATE NOT NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_accounting_restaurant ON accounting_transactions(restaurant_id);\nCREATE INDEX idx_accounting_date ON accounting_transactions(transaction_date);\nCREATE INDEX idx_accounting_type ON accounting_transactions(type);\n\n-- ------------------------------------------------------------\n-- TABLA: vehicles\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS vehicles (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n name VARCHAR(100) NOT NULL,\n plate VARCHAR(20) NOT NULL,\n type vehicle_type DEFAULT 'moto',\n driver_name VARCHAR(200),\n driver_id INT REFERENCES users(id) ON DELETE SET NULL,\n status vehicle_status DEFAULT 'disponible',\n current_lat DECIMAL(10,8) NULL,\n current_lng DECIMAL(11,8) NULL,\n last_location_update TIMESTAMP NULL,\n imei VARCHAR(20) NULL,\n gps_validated BOOLEAN DEFAULT FALSE,\n gps_last_seen TIMESTAMP NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS imei VARCHAR(20) NULL;\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS gps_validated BOOLEAN DEFAULT FALSE;\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS gps_last_seen TIMESTAMP NULL;\n\n-- ------------------------------------------------------------\n-- TABLA: deliveries\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS deliveries (\n id SERIAL PRIMARY KEY,\n delivery_code VARCHAR(30) NOT NULL UNIQUE,\n order_id INT NOT NULL REFERENCES orders(id),\n vehicle_id INT REFERENCES vehicles(id) ON DELETE SET NULL,\n driver_id INT REFERENCES users(id) ON DELETE SET NULL,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n delivery_address VARCHAR(500),\n dest_lat DECIMAL(10,8) NULL,\n dest_lng DECIMAL(11,8) NULL,\n status delivery_status DEFAULT 'asignado',\n scheduled_time TIMESTAMP,\n actual_delivery_time TIMESTAMP NULL,\n notes TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_deliveries_status ON deliveries(status);\nCREATE INDEX idx_deliveries_order ON deliveries(order_id);\n\n-- ------------------------------------------------------------\n-- TABLA: delivery_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS delivery_items (\n id SERIAL PRIMARY KEY,\n delivery_id INT NOT NULL REFERENCES deliveries(id) ON DELETE CASCADE,\n product_name VARCHAR(200) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit VARCHAR(30),\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: route_history\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS route_history (\n id BIGSERIAL PRIMARY KEY,\n vehicle_id INT NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,\n delivery_id INT REFERENCES deliveries(id) ON DELETE SET NULL,\n lat DECIMAL(10,8) NOT NULL,\n lng DECIMAL(11,8) NOT NULL,\n speed DECIMAL(6,2),\n recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_route_vehicle ON route_history(vehicle_id, recorded_at);\n\n-- ------------------------------------------------------------\n-- TABLA: inventory_movements\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS inventory_movements (\n id BIGSERIAL PRIMARY KEY,\n inventory_id INT NOT NULL REFERENCES inventory(id) ON DELETE CASCADE,\n type inventory_movement_type NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n previous_stock DECIMAL(10,2),\n new_stock DECIMAL(10,2),\n reference_type VARCHAR(50),\n reference_id INT,\n notes TEXT,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_inv_movements_inventory ON inventory_movements(inventory_id);\nCREATE INDEX idx_inv_movements_date ON inventory_movements(created_at);\n\n-- ------------------------------------------------------------\n-- TABLA: audit_log\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS audit_log (\n id BIGSERIAL PRIMARY KEY,\n user_id INT REFERENCES users(id) ON DELETE SET NULL,\n action VARCHAR(50) NOT NULL,\n entity_type VARCHAR(50) NOT NULL,\n entity_id INT,\n old_values JSONB,\n new_values JSONB,\n ip_address VARCHAR(45),\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_audit_user ON audit_log(user_id);\nCREATE INDEX idx_audit_entity ON audit_log(entity_type, entity_id);\nCREATE INDEX idx_audit_date ON audit_log(created_at);\n\n-- ------------------------------------------------------------\n-- FUNCION: Auto-actualizar updated_at\n-- ------------------------------------------------------------\nCREATE OR REPLACE FUNCTION update_updated_at_column()\nRETURNS TRIGGER AS $$\nBEGIN\n NEW.updated_at = CURRENT_TIMESTAMP;\n RETURN NEW;\nEND;\n$$ language 'plpgsql';\n\n-- Aplicar trigger a todas las tablas con updated_at\nDROP TRIGGER IF EXISTS update_roles_updated_at ON roles;\nCREATE TRIGGER update_roles_updated_at BEFORE UPDATE ON roles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_restaurants_updated_at ON restaurants;\nCREATE TRIGGER update_restaurants_updated_at BEFORE UPDATE ON restaurants FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_branches_updated_at ON branches;\nCREATE TRIGGER update_branches_updated_at BEFORE UPDATE ON branches FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_users_updated_at ON users;\nCREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_suppliers_updated_at ON suppliers;\nCREATE TRIGGER update_suppliers_updated_at BEFORE UPDATE ON suppliers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_products_updated_at ON products;\nCREATE TRIGGER update_products_updated_at BEFORE UPDATE ON products FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_inventory_updated_at ON inventory;\nCREATE TRIGGER update_inventory_updated_at BEFORE UPDATE ON inventory FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_menu_products_updated_at ON menu_products;\nCREATE TRIGGER update_menu_products_updated_at BEFORE UPDATE ON menu_products FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_orders_updated_at ON orders;\nCREATE TRIGGER update_orders_updated_at BEFORE UPDATE ON orders FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_invoices_updated_at ON invoices;\nCREATE TRIGGER update_invoices_updated_at BEFORE UPDATE ON invoices FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_vehicles_updated_at ON vehicles;\nCREATE TRIGGER update_vehicles_updated_at BEFORE UPDATE ON vehicles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_deliveries_updated_at ON deliveries;\nCREATE TRIGGER update_deliveries_updated_at BEFORE UPDATE ON deliveries FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\n\n-- ============================================================\n-- DATOS INICIALES\n-- ============================================================\n\n-- Roles\nINSERT INTO roles (name, display_name, description) VALUES\n('admin', 'Administrador', 'Acceso total al sistema: configuracion, metricas, usuarios'),\n('gerente', 'Gerente', 'Gestion de pedidos, reportes y facturacion'),\n('empleado', 'Empleado', 'Acceso operativo a inventario y comandas'),\n('proveedor_admin', 'Proveedor Admin', 'Catalogo digital, recepcion de pedidos y despachos'),\n('domiciliario', 'Domiciliario', 'Rutas asignadas, entregas y GPS') ON CONFLICT (name) DO NOTHING;\n\n-- Permisos\nINSERT INTO permissions (name, description) VALUES\n('dashboard', 'Ver dashboard ejecutivo'),\n('analytics', 'Ver analitica y KPIs de la plataforma'),\n('pedidos', 'Ver pedidos'),\n('pedidos:write', 'Crear/editar pedidos'),\n('inventario', 'Ver inventario'),\n('inventario:write', 'Crear/editar inventario'),\n('contabilidad', 'Ver contabilidad'),\n('contabilidad:write', 'Crear/editar movimientos contables'),\n('proveedores', 'Ver proveedores'),\n('proveedores:write', 'Gestionar proveedores'),\n('costeo', 'Ver costeo de platos'),\n('costeo:write', 'Crear/editar costeo'),\n('facturacion', 'Ver facturacion'),\n('facturacion:write', 'Emitir facturas'),\n('config', 'Configuracion del sistema'),\n('prov:dashboard', 'Dashboard del proveedor'),\n('prov:logistica', 'Logistica del proveedor'),\n('prov:gps', 'GPS del proveedor'),\n('prov:inventario', 'Ver inventario del proveedor'),\n('prov:inventario:write', 'Gestionar inventario del proveedor'),\n('prov:precios', 'Gestionar precios del proveedor') ON CONFLICT (name) DO NOTHING;\n\n-- Relacion roles-permisos\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 1, id FROM permissions ON CONFLICT DO NOTHING;\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 2, id FROM permissions WHERE name IN (\n 'dashboard', 'pedidos', 'pedidos:write', 'inventario', 'contabilidad',\n 'proveedores', 'costeo', 'facturacion'\n);\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 3, id FROM permissions WHERE name IN ('inventario', 'costeo');\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 4, id FROM permissions WHERE name LIKE 'prov:%';\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 5, id FROM permissions WHERE name IN ('prov:logistica', 'prov:gps');\n\n-- Restaurantes\nINSERT INTO restaurants (name, nit, phone, email, address, city) VALUES\n('Rancho Grande BGA', '900123456-7', '(607) 634-5678', 'info@ranchogrande.com', 'Cra 27 #45-32, Cabecera', 'Bucaramanga'),\n('Fogon Santandereano', '900765432-1', '(607) 634-1234', 'contacto@fogonsantandereano.com', 'Calle 35 #22-10, San Pio', 'Bucaramanga'),\n('La Castellana Grill', '900987654-3', '(607) 634-5679', 'admin@lacastellana.com', 'Cra 15 #48-20, Centro', 'Bucaramanga'),\n('Fritangueria Bonita', '900345678-9', '(607) 634-9876', 'ventas@fritangueria.com', 'Calle 50 #12-45, Cordoba', 'Bucaramanga'),\n('El Corral BGA', '900567890-1', '(607) 634-4321', 'info@elcorralbga.com', 'Cra 30 #55-18, Cabecera', 'Bucaramanga');\n\n-- Sucursales\nINSERT INTO branches (restaurant_id, name, address, is_main) VALUES\n(1, 'Sede Principal', 'Cra 27 #45-32, Cabecera', TRUE),\n(2, 'Sede San Pio', 'Calle 35 #22-10, San Pio', TRUE),\n(3, 'Sede Centro', 'Cra 15 #48-20, Centro', TRUE),\n(4, 'Sede Cordoba', 'Calle 50 #12-45, Cordoba', TRUE),\n(5, 'Sede Cabecera', 'Cra 30 #55-18, Cabecera', TRUE);\n\n-- Proveedores\nINSERT INTO suppliers (name, nit, category, phone, email, address, city, rating, review_count) VALUES\n('Carnes El Paisa S.A.S', '900111222-3', 'Carnes', '(607) 634-1111', 'ventas@carneelpaisa.com', 'Via 40 #15-20, Zona Industrial', 'Bucaramanga', 4.7, 45),\n('Lacteos del Norte', '900333444-5', 'Lacteos', '(607) 634-2222', 'pedidos@lacteosnorte.com', 'Cra 8 #20-30, La Cordova', 'Bucaramanga', 4.5, 32),\n('Mariscos del Caribe', '900555666-7', 'Mariscos', '(607) 634-3333', 'ventas@mariscoscaribe.com', 'Calle 25 #10-15, San Francisco', 'Bucaramanga', 4.8, 28),\n('Verduras Frescas SAS', '900777888-9', 'Verduras', '(607) 634-4444', 'pedidos@verdurasfrescas.com', 'Via 40 #25-40, Zona Industrial', 'Bucaramanga', 4.3, 19),\n('Distribuidora de Bebidas', '900999000-1', 'Bebidas', '(607) 634-5555', 'ventas@distbebidass.com', 'Cra 12 #30-50, Centro', 'Bucaramanga', 4.6, 37);\n\n-- Categorias\nINSERT INTO product_categories (name, icon, sort_order) VALUES\n('Carnes', '🥩', 1),\n('Pollo', '🍗', 2),\n('Cerdo', '🐷', 3),\n('Mariscos', '🦐', 4),\n('Lacteos', '🧀', 5),\n('Verduras', '🥬', 6),\n('Frutas', '🍎', 7),\n('Bebidas', '🥤', 8),\n('Granos', '🫘', 9),\n('Condimentos', '🧂', 10) ON CONFLICT (name) DO NOTHING;\n\n-- Productos catalogo B2B\nINSERT INTO products (supplier_id, category_id, name, unit, price_per_unit, stock_available) VALUES\n(1, 1, 'Carne de res 90/10', 'kg', 29000, 500),\n(1, 1, 'Carne molida', 'kg', 22000, 300),\n(1, 1, 'Costilla de res', 'kg', 18000, 200),\n(1, 1, 'Lomo de res', 'kg', 37000, 100),\n(1, 2, 'Pechuga de pollo', 'kg', 11000, 400),\n(1, 2, 'Muslo de pollo', 'kg', 8500, 250),\n(1, 3, 'Chicharron', 'kg', 15000, 150),\n(1, 3, 'Costilla cerdo ahumada', 'kg', 18000, 100),\n(3, 4, 'Camaron tigre pelado', 'kg', 45000, 50),\n(2, 5, 'Queso costeño x kg', 'kg', 14000, 80),\n(2, 5, 'Mantequilla', 'kg', 12000, 120),\n(4, 6, 'Cebolla cabezona', 'kg', 4500, 200),\n(4, 6, 'Tomate', 'kg', 5000, 180),\n(4, 6, 'Pimenton', 'kg', 7000, 100),\n(5, 8, 'Agua 500ml', 'unidad', 1500, 1000),\n(5, 8, 'Gaseosa 350ml', 'unidad', 2500, 800),\n(5, 8, 'Jugo natural', 'litro', 4000, 200);\n\n-- Inventario demo\nINSERT INTO inventory (restaurant_id, branch_id, name, category, unit, current_stock, min_stock, max_stock, avg_daily_usage, cost_per_unit, batch_date, expiry_date, stock_status, supplier_id) VALUES\n(1, 1, 'Carne de res 90/10', 'Res', 'kg', 180, 50, 300, 25, 29000, '2026-08-10', '2026-08-25', 'normal', 1),\n(1, 1, 'Carne molida', 'Res', 'kg', 95, 30, 200, 15, 22000, '2026-08-12', '2026-08-27', 'normal', 1),\n(1, 1, 'Costilla de res', 'Res', 'kg', 60, 20, 150, 10, 18000, '2026-08-11', '2026-08-26', 'normal', 1),\n(1, 1, 'Lomo de res', 'Res', 'kg', 40, 15, 100, 6, 37000, '2026-08-10', '2026-08-24', 'low', 1),\n(1, 1, 'Pechuga de pollo', 'Pollo', 'kg', 120, 40, 250, 18, 11000, '2026-08-13', '2026-08-28', 'normal', 1),\n(1, 1, 'Muslo de pollo', 'Pollo', 'kg', 85, 30, 200, 12, 8500, '2026-08-12', '2026-08-27', 'normal', 1),\n(1, 1, 'Chicharron', 'Cerdo', 'kg', 50, 20, 100, 8, 15000, '2026-08-09', '2026-08-23', 'low', 1),\n(1, 1, 'Costilla cerdo ahumada', 'Cerdo', 'kg', 35, 15, 80, 5, 18000, '2026-08-11', '2026-08-25', 'low', 1),\n(1, 1, 'Camaron tigre pelado', 'Mariscos', 'kg', 20, 10, 50, 3, 45000, '2026-08-14', '2026-08-21', 'low', 3),\n(1, 1, 'Queso costeño x kg', 'Lacteos', 'kg', 45, 15, 100, 7, 14000, '2026-08-13', '2026-08-30', 'normal', 2);\n\n-- Menu demo\nINSERT INTO menu_products (restaurant_id, name, category, price) VALUES\n(1, 'Mute Santandereano', 'Fuertes', 22000),\n(1, 'Hamburguesa Especial', 'Fuertes', 18000),\n(1, 'Bandeja Paisa', 'Fuertes', 28000),\n(1, 'Arepa con Huevo', 'Entradas', 8000),\n(1, 'Caldo de Costilla', 'Entradas', 16000),\n(1, 'Sancocho de Gallina', 'Fuertes', 24000),\n(1, 'Agua 500ml', 'Bebidas', 3000),\n(1, 'Jugo Natural', 'Bebidas', 7000),\n(1, 'Gaseosa 350ml', 'Bebidas', 4000),\n(1, 'Cafe Americano', 'Bebidas', 5000);\n\n-- Usuarios demo\nINSERT INTO users (username, password_hash, name, email, role_id, restaurant_id, branch_id) VALUES\n('admin', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Super Administrador', 'admin@xupply.com', 1, NULL, NULL),\n('gerente', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Laura Vargas', 'gerente@ranchogrande.com', 2, 1, 1),\n('empleado', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Miguel Torres', 'empleado@ranchogrande.com', 3, 1, 1),\n('proveedor', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Pedro Mora', 'pedro@carneelpaisa.com', 4, NULL, NULL),\n('domiciliario', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Jhon Diaz', 'jhon@carneelpaisa.com', 5, NULL, NULL) ON CONFLICT (username) DO NOTHING;\n\n-- ============================================================\n-- VISTAS\n-- ============================================================\n\nCREATE OR REPLACE VIEW v_dashboard_summary AS\nSELECT\n r.id AS restaurant_id,\n r.name AS restaurant_name,\n (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id = r.id AND o.status != 'cancelado') AS total_orders,\n (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id = r.id AND DATE(o.created_at) = CURRENT_DATE) AS today_orders,\n (SELECT COALESCE(SUM(i.total), 0) FROM invoices i WHERE i.restaurant_id = r.id AND DATE(i.issued_at) = CURRENT_DATE) AS today_revenue,\n (SELECT COUNT(*) FROM inventory inv WHERE inv.restaurant_id = r.id AND inv.stock_status = 'critical') AS critical_stock_count,\n (SELECT COUNT(*) FROM suppliers s WHERE s.is_active = TRUE) AS active_suppliers\nFROM restaurants r;\n\nCREATE OR REPLACE VIEW v_inventory_predictions AS\nSELECT\n i.id,\n i.name AS item_name,\n i.restaurant_id,\n i.current_stock,\n i.min_stock,\n i.avg_daily_usage,\n i.unit,\n i.expiry_date,\n CASE\n WHEN i.current_stock <= i.min_stock THEN 'high'\n WHEN i.current_stock <= i.min_stock * 1.5 THEN 'medium'\n ELSE 'low'\n END AS urgency,\n ROUND(i.avg_daily_usage * 7, 2) AS recommended_order_qty,\n CASE\n WHEN i.avg_daily_usage > 20 THEN 'increasing'\n WHEN i.avg_daily_usage < 5 THEN 'decreasing'\n ELSE 'stable'\n END AS trend\nFROM inventory i\nWHERE i.is_active = TRUE;\n"; +export const SCHEMA_SQL = "-- ============================================================\n-- XUPPLY IA - Esquema de Base de Datos PostgreSQL\n-- Plataforma B2B ERP / Ecosistema Logístico con IA\n-- Surtesoft - v2.0\n-- ============================================================\n\n-- ------------------------------------------------------------\n-- TIPOS ENUM personalizados\n-- ------------------------------------------------------------\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'order_status') THEN\n CREATE TYPE order_status AS ENUM ('nuevo', 'confirmado', 'preparando', 'despachado', 'en_camino', 'entregado', 'cancelado');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_mode') THEN\n CREATE TYPE invoice_mode AS ENUM ('electronica', 'pos', 'comandas');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_id_type') THEN\n CREATE TYPE invoice_id_type AS ENUM ('nit', 'cedula', 'email', 'Pasaporte');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'payment_method') THEN\n CREATE TYPE payment_method AS ENUM ('Efectivo', 'Tarjeta', 'Nequi', 'PSE', 'Daviplata', 'Credito');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'invoice_status') THEN\n CREATE TYPE invoice_status AS ENUM ('borrador', 'emitida', 'pagada', 'anulada');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_stock_status') THEN\n CREATE TYPE inventory_stock_status AS ENUM ('critical', 'low', 'normal');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'accounting_type') THEN\n CREATE TYPE accounting_type AS ENUM ('ingreso', 'egreso');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'vehicle_type') THEN\n CREATE TYPE vehicle_type AS ENUM ('moto', 'furgon', 'camion', 'camioneta');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'vehicle_status') THEN\n CREATE TYPE vehicle_status AS ENUM ('disponible', 'en_ruta', 'cargando', 'mantenimiento');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'delivery_status') THEN\n CREATE TYPE delivery_status AS ENUM ('asignado', 'en_camino', 'llegando', 'entregado', 'fallido');\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'inventory_movement_type') THEN\n CREATE TYPE inventory_movement_type AS ENUM ('entrada', 'salida', 'ajuste', 'merma');\n END IF;\nEND $$;\n\n-- ------------------------------------------------------------\n-- TABLA: roles\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS roles (\n id SERIAL PRIMARY KEY,\n name VARCHAR(50) NOT NULL UNIQUE,\n display_name VARCHAR(100) NOT NULL,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: permissions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS permissions (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL UNIQUE,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: role_permissions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS role_permissions (\n role_id INT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n permission_id INT NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,\n PRIMARY KEY (role_id, permission_id)\n);\n\n-- ------------------------------------------------------------\n-- TABLA: restaurants\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS restaurants (\n id SERIAL PRIMARY KEY,\n name VARCHAR(200) NOT NULL,\n nit VARCHAR(20) UNIQUE,\n phone VARCHAR(20),\n email VARCHAR(200),\n address VARCHAR(500),\n city VARCHAR(100) DEFAULT 'Bucaramanga',\n department VARCHAR(100) DEFAULT 'Santander',\n logo_url VARCHAR(500),\n category VARCHAR(100),\n subscription_plan VARCHAR(50),\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: branches\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS branches (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n name VARCHAR(200) NOT NULL,\n address VARCHAR(500),\n phone VARCHAR(20),\n is_main BOOLEAN DEFAULT FALSE,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: users\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n username VARCHAR(50) NOT NULL UNIQUE,\n password_hash VARCHAR(255) NOT NULL,\n name VARCHAR(200) NOT NULL,\n email VARCHAR(200),\n phone VARCHAR(20),\n role_id INT NOT NULL REFERENCES roles(id),\n restaurant_id INT REFERENCES restaurants(id) ON DELETE SET NULL,\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n supplier_id INT,\n avatar_url VARCHAR(500),\n is_active BOOLEAN DEFAULT TRUE,\n last_login TIMESTAMP NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: suppliers\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS suppliers (\n id SERIAL PRIMARY KEY,\n name VARCHAR(200) NOT NULL,\n nit VARCHAR(20) UNIQUE,\n category VARCHAR(100),\n phone VARCHAR(20),\n email VARCHAR(200),\n address VARCHAR(500),\n city VARCHAR(100) DEFAULT 'Bucaramanga',\n logo_url VARCHAR(500),\n rating DECIMAL(2,1) DEFAULT 0.0,\n review_count INT DEFAULT 0,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- FK de users hacia suppliers\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_users_supplier') THEN\n ALTER TABLE users ADD CONSTRAINT fk_users_supplier\n FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL;\n END IF;\nEND $$;\n\n-- ------------------------------------------------------------\n-- TABLA: product_categories\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS product_categories (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL UNIQUE,\n description TEXT,\n icon VARCHAR(50),\n sort_order INT DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: products\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS products (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n category_id INT REFERENCES product_categories(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n description TEXT,\n sku VARCHAR(50),\n unit VARCHAR(30) NOT NULL DEFAULT 'kg',\n price_per_unit DECIMAL(12,2) NOT NULL,\n min_order_qty DECIMAL(10,2) DEFAULT 1,\n stock_available DECIMAL(10,2) DEFAULT 0,\n image_url VARCHAR(500),\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: inventory\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS inventory (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n category VARCHAR(100),\n unit VARCHAR(30) NOT NULL DEFAULT 'kg',\n current_stock DECIMAL(10,2) DEFAULT 0,\n min_stock DECIMAL(10,2) DEFAULT 0,\n max_stock DECIMAL(10,2) DEFAULT 0,\n avg_daily_usage DECIMAL(10,2) DEFAULT 0,\n cost_per_unit DECIMAL(12,2) DEFAULT 0,\n batch_date DATE,\n expiry_date DATE,\n stock_status inventory_stock_status DEFAULT 'normal',\n supplier_id INT REFERENCES suppliers(id) ON DELETE SET NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_inventory_restaurant ON inventory(restaurant_id);\nCREATE INDEX idx_inventory_stock_status ON inventory(stock_status);\nCREATE INDEX idx_inventory_expiry ON inventory(expiry_date);\n\n-- ------------------------------------------------------------\n-- TABLA: menu_products\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS menu_products (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id) ON DELETE CASCADE,\n name VARCHAR(200) NOT NULL,\n description TEXT,\n category VARCHAR(100),\n price DECIMAL(12,2) NOT NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: recipes\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS recipes (\n id SERIAL PRIMARY KEY,\n menu_product_id INT NOT NULL REFERENCES menu_products(id) ON DELETE CASCADE,\n inventory_id INT NOT NULL REFERENCES inventory(id) ON DELETE CASCADE,\n quantity DECIMAL(10,4) NOT NULL,\n unit VARCHAR(30) NOT NULL,\n cost_per_unit DECIMAL(12,2) DEFAULT 0,\n waste_pct DECIMAL(5,2) DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: orders\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS orders (\n id SERIAL PRIMARY KEY,\n order_code VARCHAR(20) NOT NULL UNIQUE,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n branch_id INT REFERENCES branches(id) ON DELETE SET NULL,\n supplier_id INT NOT NULL REFERENCES suppliers(id),\n status order_status DEFAULT 'nuevo',\n total DECIMAL(12,2) DEFAULT 0,\n notes TEXT,\n delivery_address VARCHAR(500),\n requested_delivery_date TIMESTAMP,\n confirmed_at TIMESTAMP NULL,\n dispatched_at TIMESTAMP NULL,\n delivered_at TIMESTAMP NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_orders_status ON orders(status);\nCREATE INDEX idx_orders_restaurant ON orders(restaurant_id);\nCREATE INDEX idx_orders_supplier ON orders(supplier_id);\nCREATE INDEX idx_orders_created ON orders(created_at);\n\n-- ------------------------------------------------------------\n-- TABLA: order_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS order_items (\n id SERIAL PRIMARY KEY,\n order_id INT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,\n product_id INT REFERENCES products(id) ON DELETE SET NULL,\n inventory_id INT REFERENCES inventory(id) ON DELETE SET NULL,\n name VARCHAR(200) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit VARCHAR(30) NOT NULL,\n unit_price DECIMAL(12,2) DEFAULT 0,\n subtotal DECIMAL(12,2) DEFAULT 0,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: invoices\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS invoices (\n id SERIAL PRIMARY KEY,\n invoice_code VARCHAR(30) NOT NULL UNIQUE,\n cufe VARCHAR(100),\n mode invoice_mode DEFAULT 'electronica',\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n supplier_id INT REFERENCES suppliers(id) ON DELETE SET NULL,\n order_id INT REFERENCES orders(id) ON DELETE SET NULL,\n client_name VARCHAR(200),\n client_id_number VARCHAR(30),\n client_id_type invoice_id_type DEFAULT 'cedula',\n client_email VARCHAR(200),\n client_address VARCHAR(500),\n subtotal DECIMAL(12,2) DEFAULT 0,\n iva_rate DECIMAL(5,2) DEFAULT 19.00,\n iva_amount DECIMAL(12,2) DEFAULT 0,\n impoconsumo_rate DECIMAL(5,2) DEFAULT 8.00,\n impoconsumo_amount DECIMAL(12,2) DEFAULT 0,\n total DECIMAL(12,2) DEFAULT 0,\n payment_method payment_method DEFAULT 'Efectivo',\n status invoice_status DEFAULT 'borrador',\n motivo TEXT,\n mesa VARCHAR(10),\n mesero VARCHAR(100),\n issued_at TIMESTAMP NULL,\n paid_at TIMESTAMP NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_invoices_status ON invoices(status);\nCREATE INDEX idx_invoices_restaurant ON invoices(restaurant_id);\nCREATE INDEX idx_invoices_date ON invoices(issued_at);\n\n-- ------------------------------------------------------------\n-- TABLA: invoice_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS invoice_items (\n id SERIAL PRIMARY KEY,\n invoice_id INT NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,\n description VARCHAR(300) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit_price DECIMAL(12,2) NOT NULL,\n subtotal DECIMAL(12,2) NOT NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: supplier_reviews\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS Reseña (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n reviewer_name VARCHAR(200),\n rating INT NOT NULL CHECK (rating BETWEEN 1 AND 5),\n comment TEXT,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: accounting_transactions\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS accounting_transactions (\n id SERIAL PRIMARY KEY,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n type accounting_type NOT NULL,\n amount DECIMAL(12,2) NOT NULL,\n description VARCHAR(500),\n category VARCHAR(100),\n reference_type VARCHAR(50),\n reference_id INT,\n payment_method VARCHAR(50),\n transaction_date DATE NOT NULL,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_accounting_restaurant ON accounting_transactions(restaurant_id);\nCREATE INDEX idx_accounting_date ON accounting_transactions(transaction_date);\nCREATE INDEX idx_accounting_type ON accounting_transactions(type);\n\n-- ------------------------------------------------------------\n-- TABLA: vehicles\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS vehicles (\n id SERIAL PRIMARY KEY,\n supplier_id INT NOT NULL REFERENCES suppliers(id) ON DELETE CASCADE,\n name VARCHAR(100) NOT NULL,\n plate VARCHAR(20) NOT NULL,\n type vehicle_type DEFAULT 'moto',\n driver_name VARCHAR(200),\n status vehicle_status DEFAULT 'disponible',\n current_lat DECIMAL(10,8) NULL,\n current_lng DECIMAL(11,8) NULL,\n last_location_update TIMESTAMP NULL,\n imei VARCHAR(20) NULL,\n gps_validated BOOLEAN DEFAULT FALSE,\n gps_last_seen TIMESTAMP NULL,\n is_active BOOLEAN DEFAULT TRUE,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS imei VARCHAR(20) NULL;\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS gps_validated BOOLEAN DEFAULT FALSE;\nALTER TABLE vehicles ADD COLUMN IF NOT EXISTS gps_last_seen TIMESTAMP NULL;\n\n-- ------------------------------------------------------------\n-- TABLA: deliveries\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS deliveries (\n id SERIAL PRIMARY KEY,\n delivery_code VARCHAR(30) NOT NULL UNIQUE,\n order_id INT NOT NULL REFERENCES orders(id),\n vehicle_id INT REFERENCES vehicles(id) ON DELETE SET NULL,\n driver_id INT REFERENCES users(id) ON DELETE SET NULL,\n restaurant_id INT NOT NULL REFERENCES restaurants(id),\n delivery_address VARCHAR(500),\n dest_lat DECIMAL(10,8) NULL,\n dest_lng DECIMAL(11,8) NULL,\n status delivery_status DEFAULT 'asignado',\n scheduled_time TIMESTAMP,\n actual_delivery_time TIMESTAMP NULL,\n notes TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_deliveries_status ON deliveries(status);\nCREATE INDEX idx_deliveries_order ON deliveries(order_id);\n\n-- ------------------------------------------------------------\n-- TABLA: delivery_items\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS delivery_items (\n id SERIAL PRIMARY KEY,\n delivery_id INT NOT NULL REFERENCES deliveries(id) ON DELETE CASCADE,\n product_name VARCHAR(200) NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n unit VARCHAR(30),\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\n-- ------------------------------------------------------------\n-- TABLA: route_history\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS route_history (\n id BIGSERIAL PRIMARY KEY,\n vehicle_id INT NOT NULL REFERENCES vehicles(id) ON DELETE CASCADE,\n delivery_id INT REFERENCES deliveries(id) ON DELETE SET NULL,\n lat DECIMAL(10,8) NOT NULL,\n lng DECIMAL(11,8) NOT NULL,\n speed DECIMAL(6,2),\n recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_route_vehicle ON route_history(vehicle_id, recorded_at);\n\n-- ------------------------------------------------------------\n-- TABLA: inventory_movements\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS inventory_movements (\n id BIGSERIAL PRIMARY KEY,\n inventory_id INT NOT NULL REFERENCES inventory(id) ON DELETE CASCADE,\n type inventory_movement_type NOT NULL,\n quantity DECIMAL(10,2) NOT NULL,\n previous_stock DECIMAL(10,2),\n new_stock DECIMAL(10,2),\n reference_type VARCHAR(50),\n reference_id INT,\n notes TEXT,\n created_by INT REFERENCES users(id) ON DELETE SET NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_inv_movements_inventory ON inventory_movements(inventory_id);\nCREATE INDEX idx_inv_movements_date ON inventory_movements(created_at);\n\n-- ------------------------------------------------------------\n-- TABLA: audit_log\n-- ------------------------------------------------------------\nCREATE TABLE IF NOT EXISTS audit_log (\n id BIGSERIAL PRIMARY KEY,\n user_id INT REFERENCES users(id) ON DELETE SET NULL,\n action VARCHAR(50) NOT NULL,\n entity_type VARCHAR(50) NOT NULL,\n entity_id INT,\n old_values JSONB,\n new_values JSONB,\n ip_address VARCHAR(45),\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX idx_audit_user ON audit_log(user_id);\nCREATE INDEX idx_audit_entity ON audit_log(entity_type, entity_id);\nCREATE INDEX idx_audit_date ON audit_log(created_at);\n\n-- ------------------------------------------------------------\n-- FUNCION: Auto-actualizar updated_at\n-- ------------------------------------------------------------\nCREATE OR REPLACE FUNCTION update_updated_at_column()\nRETURNS TRIGGER AS $$\nBEGIN\n NEW.updated_at = CURRENT_TIMESTAMP;\n RETURN NEW;\nEND;\n$$ language 'plpgsql';\n\n-- Aplicar trigger a todas las tablas con updated_at\nDROP TRIGGER IF EXISTS update_roles_updated_at ON roles;\nCREATE TRIGGER update_roles_updated_at BEFORE UPDATE ON roles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_restaurants_updated_at ON restaurants;\nCREATE TRIGGER update_restaurants_updated_at BEFORE UPDATE ON restaurants FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_branches_updated_at ON branches;\nCREATE TRIGGER update_branches_updated_at BEFORE UPDATE ON branches FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_users_updated_at ON users;\nCREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_suppliers_updated_at ON suppliers;\nCREATE TRIGGER update_suppliers_updated_at BEFORE UPDATE ON suppliers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_products_updated_at ON products;\nCREATE TRIGGER update_products_updated_at BEFORE UPDATE ON products FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_inventory_updated_at ON inventory;\nCREATE TRIGGER update_inventory_updated_at BEFORE UPDATE ON inventory FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_menu_products_updated_at ON menu_products;\nCREATE TRIGGER update_menu_products_updated_at BEFORE UPDATE ON menu_products FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_orders_updated_at ON orders;\nCREATE TRIGGER update_orders_updated_at BEFORE UPDATE ON orders FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_invoices_updated_at ON invoices;\nCREATE TRIGGER update_invoices_updated_at BEFORE UPDATE ON invoices FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_vehicles_updated_at ON vehicles;\nCREATE TRIGGER update_vehicles_updated_at BEFORE UPDATE ON vehicles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\nDROP TRIGGER IF EXISTS update_deliveries_updated_at ON deliveries;\nCREATE TRIGGER update_deliveries_updated_at BEFORE UPDATE ON deliveries FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();\n\n-- ============================================================\n-- DATOS INICIALES\n-- ============================================================\n\n-- Roles\nINSERT INTO roles (name, display_name, description) VALUES\n('admin', 'Administrador', 'Acceso total al sistema: configuracion, metricas, usuarios'),\n('gerente', 'Gerente', 'Gestion de pedidos, reportes y facturacion'),\n('empleado', 'Empleado', 'Acceso operativo a inventario y comandas'),\n('proveedor_admin', 'Proveedor Admin', 'Catalogo digital, recepcion de pedidos y despachos'),\n('domiciliario', 'Domiciliario', 'Rutas asignadas, entregas y GPS') ON CONFLICT (name) DO NOTHING;\n\n-- Permisos\nINSERT INTO permissions (name, description) VALUES\n('dashboard', 'Ver dashboard ejecutivo'),\n('analytics', 'Ver analitica y KPIs de la plataforma'),\n('pedidos', 'Ver pedidos'),\n('pedidos:write', 'Crear/editar pedidos'),\n('inventario', 'Ver inventario'),\n('inventario:write', 'Crear/editar inventario'),\n('contabilidad', 'Ver contabilidad'),\n('contabilidad:write', 'Crear/editar movimientos contables'),\n('proveedores', 'Ver proveedores'),\n('proveedores:write', 'Gestionar proveedores'),\n('costeo', 'Ver costeo de platos'),\n('costeo:write', 'Crear/editar costeo'),\n('facturacion', 'Ver facturacion'),\n('facturacion:write', 'Emitir facturas'),\n('config', 'Configuracion del sistema'),\n('prov:dashboard', 'Dashboard del proveedor'),\n('prov:logistica', 'Logistica del proveedor'),\n('prov:gps', 'GPS del proveedor'),\n('prov:inventario', 'Ver inventario del proveedor'),\n('prov:inventario:write', 'Gestionar inventario del proveedor'),\n('prov:precios', 'Gestionar precios del proveedor') ON CONFLICT (name) DO NOTHING;\n\n-- Relacion roles-permisos\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 1, id FROM permissions ON CONFLICT DO NOTHING;\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 2, id FROM permissions WHERE name IN (\n 'dashboard', 'pedidos', 'pedidos:write', 'inventario', 'contabilidad',\n 'proveedores', 'costeo', 'facturacion'\n);\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 3, id FROM permissions WHERE name IN ('inventario', 'costeo');\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 4, id FROM permissions WHERE name LIKE 'prov:%';\n\nINSERT INTO role_permissions (role_id, permission_id)\nSELECT 5, id FROM permissions WHERE name IN ('prov:logistica', 'prov:gps');\n\n-- Restaurantes\nINSERT INTO restaurants (name, nit, phone, email, address, city) VALUES\n('Rancho Grande BGA', '900123456-7', '(607) 634-5678', 'info@ranchogrande.com', 'Cra 27 #45-32, Cabecera', 'Bucaramanga'),\n('Fogon Santandereano', '900765432-1', '(607) 634-1234', 'contacto@fogonsantandereano.com', 'Calle 35 #22-10, San Pio', 'Bucaramanga'),\n('La Castellana Grill', '900987654-3', '(607) 634-5679', 'admin@lacastellana.com', 'Cra 15 #48-20, Centro', 'Bucaramanga'),\n('Fritangueria Bonita', '900345678-9', '(607) 634-9876', 'ventas@fritangueria.com', 'Calle 50 #12-45, Cordoba', 'Bucaramanga'),\n('El Corral BGA', '900567890-1', '(607) 634-4321', 'info@elcorralbga.com', 'Cra 30 #55-18, Cabecera', 'Bucaramanga');\n\n-- Sucursales\nINSERT INTO branches (restaurant_id, name, address, is_main) VALUES\n(1, 'Sede Principal', 'Cra 27 #45-32, Cabecera', TRUE),\n(2, 'Sede San Pio', 'Calle 35 #22-10, San Pio', TRUE),\n(3, 'Sede Centro', 'Cra 15 #48-20, Centro', TRUE),\n(4, 'Sede Cordoba', 'Calle 50 #12-45, Cordoba', TRUE),\n(5, 'Sede Cabecera', 'Cra 30 #55-18, Cabecera', TRUE);\n\n-- Proveedores\nINSERT INTO suppliers (name, nit, category, phone, email, address, city, rating, review_count) VALUES\n('Carnes El Paisa S.A.S', '900111222-3', 'Carnes', '(607) 634-1111', 'ventas@carneelpaisa.com', 'Via 40 #15-20, Zona Industrial', 'Bucaramanga', 4.7, 45),\n('Lacteos del Norte', '900333444-5', 'Lacteos', '(607) 634-2222', 'pedidos@lacteosnorte.com', 'Cra 8 #20-30, La Cordova', 'Bucaramanga', 4.5, 32),\n('Mariscos del Caribe', '900555666-7', 'Mariscos', '(607) 634-3333', 'ventas@mariscoscaribe.com', 'Calle 25 #10-15, San Francisco', 'Bucaramanga', 4.8, 28),\n('Verduras Frescas SAS', '900777888-9', 'Verduras', '(607) 634-4444', 'pedidos@verdurasfrescas.com', 'Via 40 #25-40, Zona Industrial', 'Bucaramanga', 4.3, 19),\n('Distribuidora de Bebidas', '900999000-1', 'Bebidas', '(607) 634-5555', 'ventas@distbebidass.com', 'Cra 12 #30-50, Centro', 'Bucaramanga', 4.6, 37);\n\n-- Categorias\nINSERT INTO product_categories (name, icon, sort_order) VALUES\n('Carnes', '🥩', 1),\n('Pollo', '🍗', 2),\n('Cerdo', '🐷', 3),\n('Mariscos', '🦐', 4),\n('Lacteos', '🧀', 5),\n('Verduras', '🥬', 6),\n('Frutas', '🍎', 7),\n('Bebidas', '🥤', 8),\n('Granos', '🫘', 9),\n('Condimentos', '🧂', 10) ON CONFLICT (name) DO NOTHING;\n\n-- Productos catalogo B2B\nINSERT INTO products (supplier_id, category_id, name, unit, price_per_unit, stock_available) VALUES\n(1, 1, 'Carne de res 90/10', 'kg', 29000, 500),\n(1, 1, 'Carne molida', 'kg', 22000, 300),\n(1, 1, 'Costilla de res', 'kg', 18000, 200),\n(1, 1, 'Lomo de res', 'kg', 37000, 100),\n(1, 2, 'Pechuga de pollo', 'kg', 11000, 400),\n(1, 2, 'Muslo de pollo', 'kg', 8500, 250),\n(1, 3, 'Chicharron', 'kg', 15000, 150),\n(1, 3, 'Costilla cerdo ahumada', 'kg', 18000, 100),\n(3, 4, 'Camaron tigre pelado', 'kg', 45000, 50),\n(2, 5, 'Queso costeño x kg', 'kg', 14000, 80),\n(2, 5, 'Mantequilla', 'kg', 12000, 120),\n(4, 6, 'Cebolla cabezona', 'kg', 4500, 200),\n(4, 6, 'Tomate', 'kg', 5000, 180),\n(4, 6, 'Pimenton', 'kg', 7000, 100),\n(5, 8, 'Agua 500ml', 'unidad', 1500, 1000),\n(5, 8, 'Gaseosa 350ml', 'unidad', 2500, 800),\n(5, 8, 'Jugo natural', 'litro', 4000, 200);\n\n-- Inventario demo\nINSERT INTO inventory (restaurant_id, branch_id, name, category, unit, current_stock, min_stock, max_stock, avg_daily_usage, cost_per_unit, batch_date, expiry_date, stock_status, supplier_id) VALUES\n(1, 1, 'Carne de res 90/10', 'Res', 'kg', 180, 50, 300, 25, 29000, '2026-08-10', '2026-08-25', 'normal', 1),\n(1, 1, 'Carne molida', 'Res', 'kg', 95, 30, 200, 15, 22000, '2026-08-12', '2026-08-27', 'normal', 1),\n(1, 1, 'Costilla de res', 'Res', 'kg', 60, 20, 150, 10, 18000, '2026-08-11', '2026-08-26', 'normal', 1),\n(1, 1, 'Lomo de res', 'Res', 'kg', 40, 15, 100, 6, 37000, '2026-08-10', '2026-08-24', 'low', 1),\n(1, 1, 'Pechuga de pollo', 'Pollo', 'kg', 120, 40, 250, 18, 11000, '2026-08-13', '2026-08-28', 'normal', 1),\n(1, 1, 'Muslo de pollo', 'Pollo', 'kg', 85, 30, 200, 12, 8500, '2026-08-12', '2026-08-27', 'normal', 1),\n(1, 1, 'Chicharron', 'Cerdo', 'kg', 50, 20, 100, 8, 15000, '2026-08-09', '2026-08-23', 'low', 1),\n(1, 1, 'Costilla cerdo ahumada', 'Cerdo', 'kg', 35, 15, 80, 5, 18000, '2026-08-11', '2026-08-25', 'low', 1),\n(1, 1, 'Camaron tigre pelado', 'Mariscos', 'kg', 20, 10, 50, 3, 45000, '2026-08-14', '2026-08-21', 'low', 3),\n(1, 1, 'Queso costeño x kg', 'Lacteos', 'kg', 45, 15, 100, 7, 14000, '2026-08-13', '2026-08-30', 'normal', 2);\n\n-- Menu demo\nINSERT INTO menu_products (restaurant_id, name, category, price) VALUES\n(1, 'Mute Santandereano', 'Fuertes', 22000),\n(1, 'Hamburguesa Especial', 'Fuertes', 18000),\n(1, 'Bandeja Paisa', 'Fuertes', 28000),\n(1, 'Arepa con Huevo', 'Entradas', 8000),\n(1, 'Caldo de Costilla', 'Entradas', 16000),\n(1, 'Sancocho de Gallina', 'Fuertes', 24000),\n(1, 'Agua 500ml', 'Bebidas', 3000),\n(1, 'Jugo Natural', 'Bebidas', 7000),\n(1, 'Gaseosa 350ml', 'Bebidas', 4000),\n(1, 'Cafe Americano', 'Bebidas', 5000);\n\n-- Usuarios demo\nINSERT INTO users (username, password_hash, name, email, role_id, restaurant_id, branch_id) VALUES\n('admin', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Super Administrador', 'admin@xupply.com', 1, NULL, NULL),\n('gerente', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Laura Vargas', 'gerente@ranchogrande.com', 2, 1, 1),\n('empleado', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Miguel Torres', 'empleado@ranchogrande.com', 3, 1, 1),\n('proveedor', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Pedro Mora', 'pedro@carneelpaisa.com', 4, NULL, NULL),\n('domiciliario', '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e', 'Jhon Diaz', 'jhon@carneelpaisa.com', 5, NULL, NULL) ON CONFLICT (username) DO NOTHING;\n\n-- ============================================================\n-- VISTAS\n-- ============================================================\n\nCREATE OR REPLACE VIEW v_dashboard_summary AS\nSELECT\n r.id AS restaurant_id,\n r.name AS restaurant_name,\n (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id = r.id AND o.status != 'cancelado') AS total_orders,\n (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id = r.id AND DATE(o.created_at) = CURRENT_DATE) AS today_orders,\n (SELECT COALESCE(SUM(i.total), 0) FROM invoices i WHERE i.restaurant_id = r.id AND DATE(i.issued_at) = CURRENT_DATE) AS today_revenue,\n (SELECT COUNT(*) FROM inventory inv WHERE inv.restaurant_id = r.id AND inv.stock_status = 'critical') AS critical_stock_count,\n (SELECT COUNT(*) FROM suppliers s WHERE s.is_active = TRUE) AS active_suppliers\nFROM restaurants r;\n\nCREATE OR REPLACE VIEW v_inventory_predictions AS\nSELECT\n i.id,\n i.name AS item_name,\n i.restaurant_id,\n i.current_stock,\n i.min_stock,\n i.avg_daily_usage,\n i.unit,\n i.expiry_date,\n CASE\n WHEN i.current_stock <= i.min_stock THEN 'high'\n WHEN i.current_stock <= i.min_stock * 1.5 THEN 'medium'\n ELSE 'low'\n END AS urgency,\n ROUND(i.avg_daily_usage * 7, 2) AS recommended_order_qty,\n CASE\n WHEN i.avg_daily_usage > 20 THEN 'increasing'\n WHEN i.avg_daily_usage < 5 THEN 'decreasing'\n ELSE 'stable'\n END AS trend\nFROM inventory i\nWHERE i.is_active = TRUE;\n"; diff --git a/src/lib/email.ts b/src/lib/email.ts index 2a20cc4..0537e32 100644 --- a/src/lib/email.ts +++ b/src/lib/email.ts @@ -1,39 +1,395 @@ import dotenv from 'dotenv'; +import nodemailer, { type Transporter } from 'nodemailer'; dotenv.config(); export interface EmailPayload { to_email: string; - to_name: string; + to_name?: string; subject: string; + /** Cuerpo en texto plano. Obligatorio: los filtros antispam penalizan el HTML sin alternativa. */ body: string; + /** HTML opcional. Si no se envía, se genera una plantilla corporativa. */ + html?: string; + reply_to?: string; + category?: 'transactional' | 'notification'; } -export async function sendEmail(payload: EmailPayload): Promise { - const serviceId = process.env.EMAILJS_SERVICE_ID; - const templateId = process.env.EMAILJS_TEMPLATE_ID; - const publicKey = process.env.EMAILJS_PUBLIC_KEY; - const privateKey = process.env.EMAILJS_PRIVATE_KEY; +type Provider = 'smtp' | 'resend' | 'emailjs' | 'none'; + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; +const FREE_MAIL_DOMAINS = [ + 'gmail.com', + 'googlemail.com', + 'hotmail.com', + 'outlook.com', + 'live.com', + 'yahoo.com', + 'icloud.com', + 'aol.com', + 'proton.me', + 'protonmail.com', +]; + +let providerLogged = false; +let smtpTransport: Transporter | null = null; + +function env(name: string): string { + return (process.env[name] ?? '').trim(); +} + +function smtpConfigured(): boolean { + return Boolean(env('SMTP_HOST') && env('SMTP_USER') && env('SMTP_PASS')); +} + +function resendConfigured(): boolean { + return Boolean(env('RESEND_API_KEY')); +} + +function emailjsConfigured(): boolean { + return Boolean(env('EMAILJS_SERVICE_ID') && env('EMAILJS_TEMPLATE_ID') && env('EMAILJS_PUBLIC_KEY')); +} + +export function getEmailProviderName(): Provider { + const explicit = env('MAIL_PROVIDER').toLowerCase(); + if (explicit === 'smtp') return smtpConfigured() ? 'smtp' : 'none'; + if (explicit === 'resend') return resendConfigured() ? 'resend' : 'none'; + if (explicit === 'emailjs') return emailjsConfigured() ? 'emailjs' : 'none'; + + // Autodetección: SMTP empresarial > Resend > EmailJS (legacy). + if (smtpConfigured()) return 'smtp'; + if (resendConfigured()) return 'resend'; + if (emailjsConfigured()) return 'emailjs'; + return 'none'; +} + +function fromHeader(): string { + const raw = cleanHeader(env('MAIL_FROM')); + if (!raw) return ''; + if (raw.includes('<')) return raw; + const name = cleanHeader(env('MAIL_FROM_NAME') || 'Xupply'); + return `"${name.replace(/"/g, '')}" <${raw}>`; +} + +function fromEmail(): string { + const raw = env('MAIL_FROM'); + const match = raw.match(/<([^>]+)>/); + return (match ? match[1] : raw).trim().toLowerCase(); +} + +function replyToHeader(payload: EmailPayload): string { + return cleanHeader(payload.reply_to?.trim() || env('MAIL_REPLY_TO') || env('MAIL_FROM')); +} + +/** Elimina CR/LF para impedir inyección de cabeceras. */ +function cleanHeader(value: string): string { + return value.replace(/[\r\n]+/g, ' ').trim(); +} + +function escapeHtml(value: string): string { return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function renderHtml(payload: EmailPayload): string { + const appUrl = env('APP_URL') || env('CLIENT_ORIGIN') || 'https://xupply.example.com'; + const company = env('MAIL_COMPANY_NAME') || 'Xupply'; + const address = env('MAIL_COMPANY_ADDRESS') || 'Bucaramanga, Santander, Colombia'; + const support = env('MAIL_REPLY_TO') || fromEmail(); + const safeBody = escapeHtml(payload.body).replace(/\r?\n/g, '
'); + const greeting = payload.to_name ? `Hola ${escapeHtml(payload.to_name)},` : 'Hola,'; + + return ` + + + + + ${escapeHtml(payload.subject)} + + +
${escapeHtml(payload.subject)}
+ + + + +
+ + + + + + + + + + + + + +
+
${escapeHtml(company)}
+
+

${greeting}

+

${safeBody}

+
+ Abrir ${escapeHtml(company)} +
+

${escapeHtml(company)} · ${escapeHtml(address)}

+

¿Necesitas ayuda? Escríbenos a ${escapeHtml(support)}

+

Este es un mensaje automático de ${escapeHtml(company)}.

+
+
+ +`; +} + +function renderText(payload: EmailPayload): string { + const company = env('MAIL_COMPANY_NAME') || 'Xupply'; + const address = env('MAIL_COMPANY_ADDRESS') || 'Bucaramanga, Santander, Colombia'; + const support = env('MAIL_REPLY_TO') || fromEmail(); + const greeting = payload.to_name ? `Hola ${payload.to_name},` : 'Hola,'; + return [ + greeting, + '', + payload.body, + '', + '--', + `${company} · ${address}`, + `Soporte: ${support}`, + `Este es un mensaje automático de ${company}.`, + ].join('\n'); +} + +function getSmtpTransport(): Transporter { + if (smtpTransport) return smtpTransport; + const port = Number(env('SMTP_PORT') || 587); + smtpTransport = nodemailer.createTransport({ + host: env('SMTP_HOST'), + port, + secure: env('SMTP_SECURE') === 'true' || port === 465, + auth: { + user: env('SMTP_USER'), + pass: env('SMTP_PASS'), + }, + pool: true, + maxConnections: 3, + maxMessages: 50, + connectionTimeout: 10_000, + greetingTimeout: 10_000, + socketTimeout: 20_000, + tls: { minVersion: 'TLSv1.2' }, + }); + return smtpTransport; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function sendViaSmtp(message: { + from: string; + to: string; + subject: string; + text: string; + html: string; + replyTo: string; +}): Promise { + const transport = getSmtpTransport(); + const info = await transport.sendMail({ + from: message.from, + to: message.to, + subject: message.subject, + text: message.text, + html: message.html, + replyTo: message.replyTo, + bcc: env('MAIL_BCC') || undefined, + headers: { + 'X-Mailer': 'Xupply', + 'X-Auto-Response-Suppress': 'OOF, AutoReply', + }, + }); + return Boolean(info?.messageId); +} - if (!serviceId || !templateId || !publicKey) { - console.log('[email] EmailJS no configurado, correo omitido:', payload.subject); +async function sendViaResend(message: { + from: string; + to: string; + subject: string; + text: string; + html: string; + replyTo: string; + category: string; +}): Promise { + const res = await fetch('https://api.resend.com/emails', { + method: 'POST', + headers: { + Authorization: `Bearer ${env('RESEND_API_KEY')}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + from: message.from, + to: [message.to], + subject: message.subject, + text: message.text, + html: message.html, + reply_to: message.replyTo || undefined, + bcc: env('MAIL_BCC') ? [env('MAIL_BCC')] : undefined, + headers: { + 'X-Entity-Ref-ID': `${message.category}-${Date.now()}`, + }, + }), + }); + if (!res.ok) { + const detail = await res.text().catch(() => ''); + console.error('[email] Resend rechazó el envío:', res.status, detail.slice(0, 300)); return false; } + return true; +} +async function sendViaEmailJs(payload: EmailPayload): Promise { const res = await fetch('https://api.emailjs.com/api/v1.0/email/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ - service_id: serviceId, - template_id: templateId, - user_id: publicKey, - accessToken: privateKey, - template_params: payload, + service_id: env('EMAILJS_SERVICE_ID'), + template_id: env('EMAILJS_TEMPLATE_ID'), + user_id: env('EMAILJS_PUBLIC_KEY'), + accessToken: env('EMAILJS_PRIVATE_KEY') || undefined, + template_params: { + to_email: payload.to_email, + to_name: payload.to_name ?? payload.to_email, + subject: payload.subject, + body: payload.body, + message: payload.body, + from_name: env('MAIL_FROM_NAME') || 'Xupply', + reply_to: replyToHeader(payload), + }, }), }); if (!res.ok) { - console.error('[email] Error EmailJS:', res.status, res.statusText); + const detail = await res.text().catch(() => ''); + console.error('[email] EmailJS rechazó el envío:', res.status, detail.slice(0, 300)); return false; } return true; -} \ No newline at end of file +} + +function validatePayload(payload: EmailPayload): string | null { + if (!payload?.to_email || !EMAIL_RE.test(payload.to_email.trim())) return 'destinatario inválido'; + if (!payload.subject || !payload.subject.trim()) return 'asunto vacío'; + if (!payload.body || !payload.body.trim()) return 'cuerpo vacío'; + return null; +} + +async function deliver(payload: EmailPayload, provider: Provider): Promise { + const html = payload.html?.trim() || renderHtml(payload); + const text = renderText(payload); + const message = { + from: fromHeader(), + to: payload.to_email.trim(), + subject: cleanHeader(payload.subject), + text, + html, + replyTo: replyToHeader(payload), + category: payload.category ?? 'transactional', + }; + + if (provider === 'smtp') return sendViaSmtp(message); + if (provider === 'resend') return sendViaResend(message); + if (provider === 'emailjs') return sendViaEmailJs(payload); + return false; +} + +/** + * Envía un correo transaccional. Nunca lanza excepciones: un fallo de correo + * no debe romper la creación de un pedido o una factura. + * + * Reintenta hasta 3 veces con backoff exponencial ante errores transitorios. + */ +export async function sendEmail(payload: EmailPayload): Promise { + const invalid = validatePayload(payload); + if (invalid) { + console.error('[email] Payload inválido:', invalid); + return false; + } + + const provider = getEmailProviderName(); + if (provider === 'none') { + console.warn('[email] Sin proveedor configurado; correo omitido:', payload.subject); + return false; + } + if (!providerLogged) { + providerLogged = true; + console.log(`[email] Proveedor configurado: ${provider}`); + } + if (provider !== 'emailjs' && !fromHeader()) { + console.error('[email] MAIL_FROM no está configurado; el correo no se puede enviar con un remitente válido.'); + return false; + } + + for (let attempt = 1; attempt <= 3; attempt += 1) { + try { + const ok = await deliver(payload, provider); + if (ok) return true; + } catch (err) { + console.error( + `[email] Intento ${attempt}/3 falló (${provider}):`, + (err as Error)?.message || err + ); + } + if (attempt < 3) await sleep(500 * 2 ** (attempt - 1)); + } + console.error('[email] No se pudo enviar el correo:', payload.subject, '→', payload.to_email); + return false; +} + +/** Estado no sensible para diagnóstico y health checks internos. */ +export function getEmailStatus() { + const provider = getEmailProviderName(); + const from = fromEmail(); + const warnings: string[] = []; + const isProduction = process.env.NODE_ENV === 'production' || process.env.VERCEL === '1'; + + if (provider === 'none') warnings.push('No hay proveedor de correo configurado.'); + if (provider !== 'none' && isProduction && from && FREE_MAIL_DOMAINS.includes(from.split('@')[1] ?? '')) { + warnings.push('MAIL_FROM usa un dominio gratuito; usa un dominio corporativo para evitar spam.'); + } + if (provider !== 'none' && isProduction && !env('MAIL_REPLY_TO')) { + warnings.push('MAIL_REPLY_TO no está configurado; las respuestas irán al remitente.'); + } + if (provider === 'smtp' && env('SMTP_USER') && from) { + const smtpDomain = (env('SMTP_USER').split('@')[1] ?? '').toLowerCase(); + const fromDomain = (from.split('@')[1] ?? '').toLowerCase(); + if (smtpDomain && fromDomain && smtpDomain !== fromDomain) { + warnings.push('El dominio de SMTP_USER no coincide con MAIL_FROM (SPF/DKIM podrían fallar).'); + } + } + + return { + provider, + from: from || null, + reply_to: env('MAIL_REPLY_TO') || null, + bcc: env('MAIL_BCC') || null, + configured: provider !== 'none', + warnings, + }; +} + +/** Envía un correo de prueba a un destinatario concreto. */ +export async function sendTestEmail(to: string): Promise<{ ok: boolean; status: ReturnType }> { + const status = getEmailStatus(); + const ok = await sendEmail({ + to_email: to, + to_name: 'Equipo Xupply', + subject: `Prueba de correo Xupply — ${new Date().toISOString()}`, + body: + 'Este es un correo de prueba enviado desde el backend de Xupply.\n\n' + + 'Si lo ves en la bandeja de entrada (no en spam), la configuración SPF/DKIM/DMARC y el remitente están correctos.', + category: 'transactional', + }); + return { ok, status }; +} diff --git a/src/lib/migrations.ts b/src/lib/migrations.ts index 62076e5..055a33e 100644 --- a/src/lib/migrations.ts +++ b/src/lib/migrations.ts @@ -1,12 +1,5 @@ import { query } from '../config/db'; -/** - * Hash bcrypt real para la contraseña demo `demo1234`. - * Reemplaza el placeholder inválido `$2b$10$DefaulthashForDemo...` que - * permitía entrar sin validar el hash (backdoor) en bases de datos antiguas. - */ -const DEMO_PASSWORD_HASH = '$2a$10$oeMFaVfquf/BWyFhkKmh.upF3lNucd/f8.jq4pajD5Sl10zCwwU.e'; - /** * Migraciones idempotentes (patrón del repo: ALTER/CREATE ... IF NOT EXISTS). * Se ejecutan una vez al arrancar el servidor. @@ -38,16 +31,6 @@ export async function ensureRadarAndGpsSchema(): Promise { ALTER TABLE deliveries ADD COLUMN IF NOT EXISTS confirmation_code VARCHAR(10); ALTER TABLE deliveries ADD COLUMN IF NOT EXISTS actual_delivery_time TIMESTAMP NULL; - -- Asignación de vehículo por usuario (antes: DDL en el top-level de routes/users.ts, - -- que se ejecutaba ANTES de crear el esquema y fallaba en silencio en bases nuevas) - ALTER TABLE users ADD COLUMN IF NOT EXISTS vehicle_type VARCHAR(50); - ALTER TABLE users ADD COLUMN IF NOT EXISTS vehicle_plate VARCHAR(50); - - -- Vehículo con conductor asignado y proveedor opcional (antes: DDL en el top-level - -- de routes/deliveries.ts, mismo problema de orden en bases nuevas) - ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS driver_id INT REFERENCES users(id) ON DELETE SET NULL; - ALTER TABLE vehicles ALTER COLUMN supplier_id DROP NOT NULL; - -- Última posición del domiciliario (clave por usuario, no por vehículo) CREATE TABLE IF NOT EXISTS driver_locations ( driver_id INT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, @@ -170,53 +153,13 @@ export async function ensureRadarAndGpsSchema(): Promise { WHERE r.name = 'admin' ON CONFLICT DO NOTHING; - -- Garantizar que usuarios proveedor tengan supplier_id asignado - UPDATE users SET supplier_id = 1 WHERE username IN ('proveedor', 'domiciliario') AND supplier_id IS NULL; - UPDATE users u - SET supplier_id = (SELECT s.id FROM suppliers s ORDER BY s.id ASC LIMIT 1) - WHERE u.role_id = 4 AND u.supplier_id IS NULL AND EXISTS (SELECT 1 FROM suppliers); + -- Vehículos: conductor asignado y flota compartida opcional + ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS driver_id INT REFERENCES users(id) ON DELETE SET NULL; + ALTER TABLE vehicles ALTER COLUMN supplier_id DROP NOT NULL; + CREATE INDEX IF NOT EXISTS idx_vehicles_supplier ON vehicles(supplier_id); + CREATE INDEX IF NOT EXISTS idx_deliveries_driver ON deliveries(driver_id); `); console.log('[DB] Esquema Radar de Stock + GPS verificado.'); - - // Semilla idempotente de direcciones/coordenadas de Bucaramanga. - // Antes vivía en el top-level de routes/deliveries.ts (mismo problema de orden). - try { - await query(` - UPDATE deliveries - SET dest_lat = 7.1168, dest_lng = -73.1095, - delivery_address = 'Carrera 35 #48-22, Cabecera del Llano, Bucaramanga' - WHERE id % 4 = 1; - - UPDATE deliveries - SET dest_lat = 7.0665, dest_lng = -73.1030, - delivery_address = 'Calle 30 #26-10, Parque Caracolí / Cañaveral, Floridablanca' - WHERE id % 4 = 2; - - UPDATE deliveries - SET dest_lat = 7.0845, dest_lng = -73.1175, - delivery_address = 'Calle 105 #24-32, Provenza, Bucaramanga' - WHERE id % 4 = 3; - - UPDATE deliveries - SET dest_lat = 7.0984, dest_lng = -73.1090, - delivery_address = 'Transversal 93 #34-99, El Tejar / C.C. Cacique, Bucaramanga' - WHERE id % 4 = 0; - - UPDATE vehicles - SET current_lat = 7.1320, current_lng = -73.1650 - WHERE id % 3 = 1; - - UPDATE vehicles - SET current_lat = 7.0850, current_lng = -73.1680 - WHERE id % 3 = 2; - - UPDATE vehicles - SET current_lat = 7.1235, current_lng = -73.1285 - WHERE id % 3 = 0; - `); - } catch (e) { - console.warn('[DB] Advertencia sembrando coordenadas de Bucaramanga:', e); - } // Indice unico parcial contabilidad try { @@ -228,25 +171,18 @@ export async function ensureRadarAndGpsSchema(): Promise { } catch (e) { console.warn('[DB] Advertencia creando índice uq_accounting_invoice_ingreso:', e); } - } catch (err) { - console.error('[DB] Error aplicando esquema Radar/GPS:', err); - } -} - -/** Repara hashes de cuentas semilla antiguas que usaban un placeholder inválido (backdoor). */ -export async function repairLegacySeedPasswords(): Promise { - try { - const res = await query( - `UPDATE users - SET password_hash = $1, token_version = token_version + 1, updated_at = CURRENT_TIMESTAMP - WHERE password_hash LIKE '$2b$10$DefaulthashForDemo%'`, - [DEMO_PASSWORD_HASH] - ); - if (res.rowCount) { - console.log(`[DB] Hashes semilla heredados reparados: ${res.rowCount}`); + // Índice único de reseñas: una por usuario y proveedor (idempotente). + try { + await query(` + CREATE UNIQUE INDEX IF NOT EXISTS uq_review_supplier_user + ON "Reseña" (supplier_id, created_by) + WHERE created_by IS NOT NULL; + `); + } catch (e) { + console.warn('[DB] No se pudo crear uq_review_supplier_user (¿reseñas duplicadas existentes?):', e); } } catch (err) { - console.error('[DB] Error reparando contraseñas semilla antiguas:', err); + console.error('[DB] Error aplicando esquema Radar/GPS:', err); } } @@ -285,10 +221,10 @@ export async function ensureServerInitialized(): Promise { if (!initPromise) { initPromise = (async () => { try { - const { initDatabase } = await import('../config/db'); + const { initDatabase, neutralizeDemoCredentials } = await import('../config/db'); await initDatabase(); await ensureRadarAndGpsSchema(); - await repairLegacySeedPasswords(); + await neutralizeDemoCredentials(); await dropLegacyPlatformViews(); await expireRadarItems(); } catch (err) { diff --git a/src/lib/oc.ts b/src/lib/oc.ts index 1f86df1..b36ebc2 100644 --- a/src/lib/oc.ts +++ b/src/lib/oc.ts @@ -35,8 +35,9 @@ export async function createPurchaseOrderDraft(opts: { if (prodIds.length > 0) { const inArr = prodIds.map((_, i) => `$${i + 1}`).join(','); const p = await client.query( - `SELECT id, name, unit, price_per_unit FROM products WHERE id IN (${inArr}) AND is_active=TRUE`, - prodIds + `SELECT id, name, unit, price_per_unit FROM products + WHERE id IN (${inArr}) AND is_active = TRUE AND supplier_id = $${prodIds.length + 1}`, + [...prodIds, Number(supplierId)] ); for (const r of p.rows) priceMap.set(r.id, r); } diff --git a/src/lib/realtime.ts b/src/lib/realtime.ts index 3bbc0e1..0d904f0 100644 --- a/src/lib/realtime.ts +++ b/src/lib/realtime.ts @@ -1,4 +1,6 @@ import type { Server as SocketIOServer, Socket } from 'socket.io'; +import type { AuthUser } from '../middleware/auth'; +import { query } from '../config/db'; let io: SocketIOServer | null = null; @@ -6,41 +8,82 @@ export function setIo(instance: SocketIOServer) { io = instance; } -export function registerSocket(socket: Socket) { - const { restaurantId, supplierId, orderId, deliveryId, userId, role } = socket.handshake.query; - if (typeof restaurantId === 'string') socket.join(`restaurant:${restaurantId}`); - if (typeof supplierId === 'string') socket.join(`supplier:${supplierId}`); - if (typeof orderId === 'string') socket.join(`order:${orderId}`); - if (typeof deliveryId === 'string') socket.join(`delivery:${deliveryId}`); - if (typeof userId === 'string') socket.join(`user:${userId}`); - if (typeof role === 'string') socket.join(`role:${role}`); - if (role === 'admin') socket.join('admins'); - - socket.on('client:identify', (data: any) => { - if (data?.role === 'admin') { - socket.join('admins'); - socket.join('role:admin'); +/** Comprueba que el usuario autenticado puede ver una entrega concreta. */ +async function canAccessDelivery(user: AuthUser, deliveryId: number): Promise { + if (user.role === 'admin') return true; + const res = await query( + `SELECT d.restaurant_id, d.driver_id, o.supplier_id + FROM deliveries d + JOIN orders o ON o.id = d.order_id + WHERE d.id = $1`, + [deliveryId] + ); + if (!res.rowCount) return false; + const row = res.rows[0]; + if (user.restaurant_id && Number(row.restaurant_id) === Number(user.restaurant_id)) return true; + if (user.supplier_id && Number(row.supplier_id) === Number(user.supplier_id)) return true; + if (user.role === 'domiciliario' && Number(row.driver_id) === Number(user.id)) return true; + return false; +} + +/** + * Registra un socket YA autenticado. + * + * La identidad llega desde el JWT (ver `server.ts`): NUNCA se aceptan + * `role`/`restaurantId`/`userId` enviados por el cliente, porque permitían + * unirse a la sala `admins` o a la de cualquier otro inquilino y recibir + * pedidos, posiciones GPS y eventos de auditoría ajenos. + */ +export function registerSocket(socket: Socket, user: AuthUser) { + socket.join(`user:${user.id}`); + if (user.restaurant_id) socket.join(`restaurant:${user.restaurant_id}`); + if (user.supplier_id) socket.join(`supplier:${user.supplier_id}`); + if (user.role) socket.join(`role:${user.role}`); + if (user.role === 'admin') socket.join('admins'); + + // El cliente solo puede pedir unirse a una entrega que le pertenezca. + socket.on('delivery:join', async (id: unknown) => { + const deliveryId = Number(id); + if (!Number.isInteger(deliveryId) || deliveryId <= 0) return; + try { + if (await canAccessDelivery(user, deliveryId)) socket.join(`delivery:${deliveryId}`); + } catch { + /* ignorar */ } - if (data?.userId) socket.join(`user:${data.userId}`); - if (data?.restaurantId) socket.join(`restaurant:${data.restaurantId}`); - if (data?.supplierId) socket.join(`supplier:${data.supplierId}`); }); - // Permite al cliente unirse/salir de la sala de seguimiento de una entrega - socket.on('delivery:join', (id: unknown) => { - if (Number.isInteger(Number(id))) socket.join(`delivery:${Number(id)}`); - }); socket.on('delivery:leave', (id: unknown) => { - socket.leave(`delivery:${Number(id)}`); + const deliveryId = Number(id); + if (Number.isInteger(deliveryId)) socket.leave(`delivery:${deliveryId}`); }); - // Permite al repartidor actualizar su posición en vivo - socket.on('delivery:update_position', (data: { deliveryId: number; lat: number; lng: number; speed: number | null }) => { - if (data && data.deliveryId) { - // Retransmitimos la posición a todos los que estén suscritos a esta entrega (Restaurantes, Admins, etc.) - socket.to(`delivery:${data.deliveryId}`).emit('delivery:position', data); + // Solo el domiciliario asignado (o un admin) puede publicar su posición. + socket.on( + 'delivery:update_position', + async (data: { deliveryId?: number; lat?: number; lng?: number; speed?: number | null }) => { + const deliveryId = Number(data?.deliveryId); + if (!Number.isInteger(deliveryId) || deliveryId <= 0) return; + try { + const res = await query( + `SELECT d.driver_id, d.restaurant_id, o.supplier_id + FROM deliveries d + JOIN orders o ON o.id = d.order_id + WHERE d.id = $1`, + [deliveryId] + ); + if (!res.rowCount) return; + const row = res.rows[0]; + const isAssignedDriver = Number(row.driver_id) === Number(user.id); + if (!isAssignedDriver && user.role !== 'admin') return; + const payload = { ...data, deliveryId }; + io?.to(`delivery:${deliveryId}`).emit('delivery:position', payload); + io?.to(`restaurant:${row.restaurant_id}`).emit('delivery:position', payload); + if (row.supplier_id) io?.to(`supplier:${row.supplier_id}`).emit('delivery:position', payload); + } catch { + /* ignorar */ + } } - }); + ); } export function emitAuditActivity(data: unknown) { @@ -121,7 +164,8 @@ export function emitOrder(event: string, data: unknown) { io.to(toSupplierId(data.supplier_id)).emit(event, data); io.to(`order:${data.id}`).emit(event, data); } else { - io.emit(event, data); + // Nunca broadcast global de datos de pedidos sin inquilino identificable. + io.to('admins').emit(event, data); } } @@ -138,4 +182,4 @@ export function emitToRole(role: string, event: string, data: unknown) { export function emitInventoryAlert(restaurantId: number, data: unknown) { if (!io) return; io.to(toRestaurantId(restaurantId)).emit('inventory:alert', data); -} \ No newline at end of file +} diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index b9c3069..62d3a31 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -1,5 +1,5 @@ import { Request, Response, NextFunction } from 'express'; -import jwt from 'jsonwebtoken'; +import jwt, { SignOptions } from 'jsonwebtoken'; import { query } from '../config/db'; export interface AuthUser { @@ -38,6 +38,9 @@ if (!RAW_JWT_SECRET || !RAW_JWT_SECRET.trim()) { const JWT_SECRET = (RAW_JWT_SECRET && RAW_JWT_SECRET.trim()) || 'dev-only-insecure-secret-change-me'; +// Sesiones cortas: antes 7 días. Configurable por entorno. +const JWT_EXPIRES_IN = (process.env.JWT_EXPIRES_IN || '12h') as SignOptions['expiresIn']; + const permissionCache = new Map>(); let cacheLoaded = false; @@ -63,7 +66,7 @@ export async function clearPermissionCache() { } export function signToken(user: AuthUser): string { - return jwt.sign(user, JWT_SECRET, { expiresIn: '7d' }); + return jwt.sign(user, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN, algorithm: 'HS256' }); } export async function authRequired(req: Request, res: Response, next: NextFunction) { @@ -72,23 +75,45 @@ export async function authRequired(req: Request, res: Response, next: NextFuncti return res.status(401).json({ error: 'Token requerido' }); } try { - const decoded = jwt.verify(header.slice(7), JWT_SECRET) as AuthUser; - - // Verificación en tiempo real contra DB para invalidar sesiones antiguas, - // revocar accesos de usuarios inactivos o cuando sus roles/permisos cambian drásticamente. - const userCheck = await query('SELECT token_version, is_active FROM users WHERE id = $1', [decoded.id]); - + const decoded = jwt.verify(header.slice(7), JWT_SECRET, { + algorithms: ['HS256'], + }) as AuthUser; + + // Verificación en tiempo real contra la BD: además de invalidar sesiones + // antiguas, el rol y el inquilino se toman SIEMPRE de la base de datos y no + // del token. Así un cambio de rol/restaurante/proveedor se aplica al + // instante (antes el JWT podía seguir diciendo lo contrario hasta caducar). + const userCheck = await query( + `SELECT u.id, u.username, u.name, u.token_version, u.is_active, + u.role_id, r.name AS role, u.restaurant_id, u.supplier_id, u.branch_id + FROM users u + JOIN roles r ON r.id = u.role_id + WHERE u.id = $1`, + [decoded.id] + ); + if (!userCheck.rowCount || !userCheck.rows[0].is_active) { return res.status(401).json({ error: 'Cuenta inactiva o eliminada' }); } - + // Comparar SIEMPRE la versión del token contra la de la BD. Los tokens sin versión // (emitidos antes de habilitar esta columna) se rechazan para forzar un nuevo inicio de sesión. if (Number(decoded.token_version ?? -1) !== Number(userCheck.rows[0].token_version)) { return res.status(401).json({ error: 'Sesión invalidada por cambios en la cuenta. Por favor inicie sesión nuevamente.' }); } - req.user = decoded; + const row = userCheck.rows[0]; + req.user = { + id: Number(row.id), + username: row.username, + name: row.name, + role: row.role, + role_id: Number(row.role_id), + restaurant_id: row.restaurant_id === null ? null : Number(row.restaurant_id), + supplier_id: row.supplier_id === null ? null : Number(row.supplier_id), + branch_id: row.branch_id === null ? null : Number(row.branch_id), + token_version: Number(row.token_version), + }; next(); } catch (err) { return res.status(401).json({ error: 'Token inválido o expirado' }); @@ -118,4 +143,4 @@ export function requirePermission(...permissionNames: string[]) { } next(); }; -} \ No newline at end of file +} diff --git a/src/middleware/error.ts b/src/middleware/error.ts index 6dce5ff..8242712 100644 --- a/src/middleware/error.ts +++ b/src/middleware/error.ts @@ -1,10 +1,24 @@ import { Request, Response, NextFunction } from 'express'; +import { randomUUID } from 'crypto'; export function notFound(req: Request, res: Response) { - res.status(404).json({ error: `Ruta no encontrada: ${req.method} ${req.originalUrl}` }); + // No reflejar la URL completa en producción (evita contenido reflejado). + const detail = + process.env.NODE_ENV === 'production' || process.env.VERCEL === '1' + ? 'Ruta no encontrada' + : `Ruta no encontrada: ${req.method} ${req.originalUrl}`; + res.status(404).json({ error: detail }); } -export function errorHandler(err: Error, _req: Request, res: Response, _next: NextFunction) { - console.error(err); - res.status(500).json({ error: 'Error interno del servidor', detail: err.message }); -} \ No newline at end of file +export function errorHandler(err: Error, req: Request, res: Response, _next: NextFunction) { + const requestId = randomUUID(); + // Log interno completo; al cliente solo un mensaje genérico + id de correlación. + // Antes se devolvía `err.message`, que filtraba SQL, nombres de tablas y + // detalles del pool de conexiones a cualquier usuario. + console.error(`[error] requestId=${requestId} ${req.method} ${req.originalUrl}`, err); + if (res.headersSent) return; + const rawStatus = Number((err as any)?.status); + const status = Number.isInteger(rawStatus) && rawStatus >= 400 && rawStatus < 600 ? rawStatus : 500; + const safeMessage = (err as any)?.expose === true && typeof err.message === 'string' ? err.message : 'Error interno del servidor'; + res.status(status).json({ error: safeMessage, requestId }); +} diff --git a/src/routes/admin.ts b/src/routes/admin.ts index 6385e3e..a999783 100644 --- a/src/routes/admin.ts +++ b/src/routes/admin.ts @@ -4,11 +4,21 @@ import { authRequired, clearPermissionCache, requirePermission } from '../middle import bcrypt from 'bcryptjs'; import { logAudit } from '../lib/audit'; import { emitToUser, emitToRole } from '../lib/realtime'; +import { getEmailStatus, sendTestEmail } from '../lib/email'; import { tenantScopeForRole, validateTenantScope } from '../lib/userTenant'; const router = Router(); router.use(authRequired); +/** Paginación acotada: evita `LIMIT NaN`, valores negativos y volcados masivos. */ +function pagination(page: unknown, limit: unknown, defaultLimit = 20, maxLimit = 100) { + const parsedPage = Number.parseInt(String(page ?? '1'), 10); + const parsedLimit = Number.parseInt(String(limit ?? defaultLimit), 10); + const p = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1; + const l = Number.isFinite(parsedLimit) && parsedLimit > 0 ? Math.min(parsedLimit, maxLimit) : defaultLimit; + return { page: p, limit: l, offset: (p - 1) * l }; +} + // ========================================== @@ -54,9 +64,8 @@ router.get('/users', requirePermission('config'), async (req: Request, res: Resp const total = parseInt(countResult.rows[0].count, 10); // Pagination - const p = Math.max(1, Number(page)); - const l = Math.max(1, Number(limit)); - sql += ` ORDER BY u.created_at DESC LIMIT ${l} OFFSET ${(p - 1) * l}`; + const { page: p, limit: l, offset } = pagination(page, limit); + sql += ` ORDER BY u.created_at DESC LIMIT ${l} OFFSET ${offset}`; const result = await query(sql, params); @@ -622,27 +631,16 @@ router.put('/roles/:id/permissions', requirePermission('config'), async (req: Re const oldPerms = await query('SELECT permission_id FROM role_permissions WHERE role_id = $1', [numericId]); - // Transacción real sobre una única conexión del pool. - // Antes BEGIN/DELETE/INSERT/COMMIT/ROLLBACK iban por query() => cada llamada podía - // caer en una conexión distinta, así que NO había transacción y se dejaban - // conexiones "idle in transaction". - const client = await require('../config/db').pool.connect(); - try { - await client.query('BEGIN'); - await client.query('DELETE FROM role_permissions WHERE role_id = $1', [numericId]); - - for (const pId of permissions) { - await client.query('INSERT INTO role_permissions (role_id, permission_id) VALUES ($1, $2)', [numericId, pId]); - } - - await client.query('COMMIT'); - } catch (txErr) { - await client.query('ROLLBACK'); - throw txErr; - } finally { - client.release(); + // Iniciar transacción explícita + await query('BEGIN'); + await query('DELETE FROM role_permissions WHERE role_id = $1', [numericId]); + + for (const pId of permissions) { + await query('INSERT INTO role_permissions (role_id, permission_id) VALUES ($1, $2)', [numericId, pId]); } + await query('COMMIT'); + // Invalidar tokens de los usuarios afectados para forzar actualizacion de RBAC local await query('UPDATE users SET token_version = token_version + 1 WHERE role_id = $1', [numericId]); @@ -655,6 +653,7 @@ router.put('/roles/:id/permissions', requirePermission('config'), async (req: Re res.json({ ok: true, count: permissions.length }); } catch (err) { + await query('ROLLBACK'); next(err); } }); @@ -722,9 +721,8 @@ router.get('/audit-log', requirePermission('config'), async (req: Request, res: const countResult = await query(`SELECT COUNT(*) FROM (${sql}) AS t`, params); const total = parseInt(countResult.rows[0].count, 10); - const p = Math.max(1, Number(page)); - const l = Math.max(1, Number(limit)); - sql += ` ORDER BY a.created_at DESC LIMIT ${l} OFFSET ${(p - 1) * l}`; + const { page: p, limit: l, offset } = pagination(page, limit, 50, 200); + sql += ` ORDER BY a.created_at DESC LIMIT ${l} OFFSET ${offset}`; const result = await query(sql, params); @@ -1177,4 +1175,50 @@ router.get('/stats', requirePermission('analytics'), async (req: Request, res: R } }); +// ========================================== +// CORREO TRANSACCIONAL (diagnóstico) +// ========================================== + +const emailTestCooldown = new Map(); + +router.get('/email/status', requirePermission('config'), async (_req: Request, res: Response) => { + const status = getEmailStatus(); + res.json({ + provider: status.provider, + from: status.from, + reply_to: status.reply_to, + configured: status.configured, + warnings: status.warnings, + }); +}); + +router.post('/email/test', requirePermission('config'), async (req: Request, res: Response, next: NextFunction) => { + try { + const user = req.user!; + const now = Date.now(); + const last = emailTestCooldown.get(user.id) ?? 0; + if (now - last < 60_000) { + return res.status(429).json({ error: 'Espera un minuto antes de enviar otra prueba.' }); + } + + const result = await query('SELECT email FROM users WHERE id = $1', [user.id]); + const to = String(result.rows[0]?.email ?? '').trim(); + if (!to) { + return res.status(400).json({ error: 'Tu usuario no tiene un correo configurado.' }); + } + + emailTestCooldown.set(user.id, now); + await logAudit(req, 'email_test', 'user', user.id, null, { provider: getEmailStatus().provider }); + const outcome = await sendTestEmail(to); + res.json({ + ok: outcome.ok, + sent_to: to, + provider: outcome.status.provider, + warnings: outcome.status.warnings, + }); + } catch (err) { + next(err); + } +}); + export default router; diff --git a/src/routes/auth.ts b/src/routes/auth.ts index 45efc4e..b4e4364 100644 --- a/src/routes/auth.ts +++ b/src/routes/auth.ts @@ -39,13 +39,23 @@ function buildPayload(row: { router.post('/register', registerLimiter, async (req, res, next) => { try { - const { username, password, name, email, phone, type, category } = req.body; + const { password, name, email, phone, type, category } = req.body; + const username = typeof req.body.username === 'string' ? req.body.username.trim().toLowerCase() : ''; if (!username || !password || !name) { return res.status(400).json({ error: 'username, password y name son requeridos' }); } + // Evita usuarios con espacios o caracteres de control (rompen el login y la auditoría). + if (!/^[a-z0-9._-]{3,40}$/.test(username)) { + return res.status(400).json({ + error: 'El usuario debe tener entre 3 y 40 caracteres: letras minúsculas, números, punto, guion o guion bajo', + }); + } if (String(password).length < 8) { return res.status(400).json({ error: 'La contraseña debe tener al menos 8 caracteres' }); } + if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(email))) { + return res.status(400).json({ error: 'El email no es válido' }); + } if (!['restaurante', 'proveedor'].includes(type)) { return res.status(400).json({ error: 'type debe ser restaurante o proveedor' }); } @@ -129,6 +139,7 @@ router.post('/login', loginLimiter, async (req, res, next) => { [username] ); } catch (queryErr: any) { + console.error('[Auth Login] Error de base de datos', queryErr?.code || queryErr?.message); if (queryErr?.message?.includes('users') || queryErr?.code === '42P01') { console.warn('[Auth Login] Tabla users no encontrada. Inicializando BD y reintentando...'); try { @@ -140,16 +151,12 @@ router.post('/login', loginLimiter, async (req, res, next) => { [username] ); } catch (initErr: any) { - return res.status(500).json({ - error: 'Error inicializando esquema de base de datos', - detail: initErr?.message || String(initErr), - }); + console.error('[Auth Login] Error inicializando esquema', initErr?.code || initErr?.message); + return res.status(500).json({ error: 'Error interno del servidor' }); } } else { - return res.status(500).json({ - error: 'Error de conexión a la base de datos', - detail: queryErr?.message || String(queryErr), - }); + // Nunca devolver el mensaje crudo del driver (filtra host, tablas, etc.). + return res.status(500).json({ error: 'Error interno del servidor' }); } } const row = result.rows[0]; @@ -229,19 +236,68 @@ router.get('/tenant-info', authRequired, async (req, res, next) => { } }); -router.post('/subscription-plan', authRequired, roleRequired('gerente', 'admin'), async (req, res, next) => { +router.post('/subscription-plan', authRequired, roleRequired('admin'), async (req, res, next) => { try { + // Un gerente NO puede cambiar su propio plan: eso permitía obtener el plan + // premium gratis. Solo un administrador de plataforma puede asignarlo. const user = req.user!; - const { plan } = req.body; + const { plan, restaurant_id } = req.body; if (!['basico', 'medio', 'premium'].includes(plan)) { return res.status(400).json({ error: 'Plan inválido. Opciones: basico, medio, premium' }); } - if (user.restaurant_id) { - await query('UPDATE restaurants SET subscription_plan = $1 WHERE id = $2', [plan, user.restaurant_id]); + const targetRestaurantId = restaurant_id ? Number(restaurant_id) : user.restaurant_id; + if (!targetRestaurantId) { + return res.status(400).json({ error: 'restaurant_id es requerido' }); + } + const updated = await query('UPDATE restaurants SET subscription_plan = $1 WHERE id = $2 RETURNING id', [ + plan, + targetRestaurantId, + ]); + if (!updated.rowCount) return res.status(404).json({ error: 'Restaurante no encontrado' }); + await logAudit(req, 'update_plan', 'restaurant', targetRestaurantId, null, { plan }); + res.json({ ok: true, plan, restaurant_id: targetRestaurantId }); + } catch (err) { + next(err); + } +}); + +/** Cierre de sesión real: invalida los tokens emitidos para este usuario. */ +router.post('/logout', authRequired, async (req, res, next) => { + try { + const user = req.user!; + await query('UPDATE users SET token_version = token_version + 1 WHERE id = $1', [user.id]); + await logAudit(req, 'logout', 'user', user.id, null, null); + res.json({ ok: true }); + } catch (err) { + next(err); + } +}); + +/** Cambio de contraseña por el propio usuario (antes solo el admin podía). */ +router.post('/change-password', authRequired, async (req, res, next) => { + try { + const user = req.user!; + const { current_password, new_password } = req.body || {}; + if (!current_password || !new_password) { + return res.status(400).json({ error: 'current_password y new_password son requeridos' }); + } + if (String(new_password).length < 10) { + return res.status(400).json({ error: 'La nueva contraseña debe tener al menos 10 caracteres' }); } - await query('UPDATE users SET subscription_plan = $1 WHERE id = $2', [plan, user.id]); - emitToUser('notification:created', user.id, { message: `Plan cambiado a: ${plan.toUpperCase()}` }); - res.json({ ok: true, plan }); + if (String(new_password) === String(current_password)) { + return res.status(400).json({ error: 'La nueva contraseña debe ser distinta a la actual' }); + } + const row = await query('SELECT password_hash FROM users WHERE id = $1', [user.id]); + if (!row.rowCount) return res.status(404).json({ error: 'Usuario no encontrado' }); + const ok = await bcrypt.compare(String(current_password), row.rows[0].password_hash).catch(() => false); + if (!ok) return res.status(401).json({ error: 'La contraseña actual no es correcta' }); + const hash = await bcrypt.hash(String(new_password), 10); + await query( + 'UPDATE users SET password_hash = $1, token_version = token_version + 1, updated_at = CURRENT_TIMESTAMP WHERE id = $2', + [hash, user.id] + ); + await logAudit(req, 'change_password', 'user', user.id, null, { self: true }); + res.json({ ok: true, message: 'Contraseña actualizada. Inicia sesión nuevamente.' }); } catch (err) { next(err); } diff --git a/src/routes/dashboard.ts b/src/routes/dashboard.ts index c87a1db..4c73c66 100644 --- a/src/routes/dashboard.ts +++ b/src/routes/dashboard.ts @@ -9,7 +9,7 @@ router.get('/summary', async (req, res, next) => { try { const user = req.user!; const isSupplier = user.role === 'proveedor_admin' && !!user.supplier_id; - const isRestaurant = !!user.restaurant_id || user.role === 'gerente' || user.role === 'admin'; + const isRestaurant = !!user.restaurant_id; const isDomiciliario = user.role === 'domiciliario'; // Clausula WHERE segura para órdenes @@ -31,7 +31,7 @@ router.get('/summary', async (req, res, next) => { COALESCE(SUM(o.total), 0)::float AS monto_total FROM orders o${orderWhere}`, orderParams - ).catch(() => ({ rows: [{ total: 4, nuevos: 1, activos: 2, monto_total: 1250000 }] })); + ); // Clausula WHERE segura para productos (los productos SOLO tienen supplier_id, NO tienen restaurant_id) let prodWhere = ''; @@ -43,7 +43,7 @@ router.get('/summary', async (req, res, next) => { const productsRes = await query( `SELECT COUNT(*)::int AS total FROM products p${prodWhere}`, prodParams - ).catch(() => ({ rows: [{ total: 18 }] })); + ); const recentRes = await query( `SELECT o.*, r.name AS restaurant_name, s.name AS supplier_name @@ -53,7 +53,7 @@ router.get('/summary', async (req, res, next) => { ${orderWhere} ORDER BY o.created_at DESC LIMIT 5`, orderParams - ).catch(() => ({ rows: [] })); + ); const orders = ordersRes.rows[0]; const productsCount = productsRes.rows[0]?.total ?? 0; @@ -89,17 +89,10 @@ router.get('/summary', async (req, res, next) => { const monthlyHistoryRes = await query( monthlyHistoryQuery, isSupplier ? [user.supplier_id] : user.restaurant_id ? [user.restaurant_id] : [] - ).catch(() => ({ rows: [] })); + ); - // Fallback amigable si la base de datos es nueva o no tiene histórico - let monthly_history = monthlyHistoryRes.rows; - if (monthly_history.length === 0) { - monthly_history = [ - { month_key: '2026-09', month_name: 'Septiembre', orders_count: Number(orders.total) || 4, total_amount: Number(orders.monto_total) || 1250000 }, - { month_key: '2026-08', month_name: 'Agosto', orders_count: 8, total_amount: 2840000 }, - { month_key: '2026-07', month_name: 'Julio', orders_count: 6, total_amount: 1980000 }, - ]; - } + // Sin datos históricos se devuelve una lista vacía (nunca cifras inventadas). + const monthly_history = monthlyHistoryRes.rows; // 2. Alertas de Stock (Para Gerente / Restaurante) let stock_alerts: any[] = []; @@ -114,18 +107,8 @@ router.get('/summary', async (req, res, next) => { ORDER BY (i.current_stock - i.min_stock) ASC LIMIT 6 `; - const invRes = await query(invQuery, user.restaurant_id ? [user.restaurant_id] : []).catch(() => ({ rows: [] })); + const invRes = await query(invQuery, user.restaurant_id ? [user.restaurant_id] : []); stock_alerts = invRes.rows; - - if (stock_alerts.length === 0) { - // Alertas de ejemplo realistas si el restaurante aún no cargó inventario - stock_alerts = [ - { id: 101, name: 'Queso Mozzarella Tajado', category: 'Lácteos', unit: 'kg', current_stock: 2.5, min_stock: 10, stock_status: 'critical', supplier_name: 'Lácteos del Valle' }, - { id: 102, name: 'Aceite Vegetal para Freidora', category: 'Abarrotes', unit: 'caneca 20L', current_stock: 1.0, min_stock: 4, stock_status: 'critical', supplier_name: 'Distribuidora Central' }, - { id: 103, name: 'Papas a la Francesa Corte Grueso', category: 'Congelados', unit: 'kg', current_stock: 6.0, min_stock: 15, stock_status: 'low', supplier_name: 'Congelados Andinos' }, - { id: 104, name: 'Salsa de Tomate Base Burger', category: 'Salsas', unit: 'galón', current_stock: 1.5, min_stock: 5, stock_status: 'low', supplier_name: 'Distribuidora Central' }, - ]; - } } // 3. Sugerencias del día (Productos recomendados para pedir hoy) @@ -137,18 +120,8 @@ router.get('/summary', async (req, res, next) => { WHERE p.is_active = TRUE AND p.stock_available > 0 ORDER BY p.id ASC LIMIT 6` - ).catch(() => ({ rows: [] })); - let daily_suggestions = sugRes.rows; - if (daily_suggestions.length === 0) { - daily_suggestions = [ - { id: 201, name: 'Queso Mozzarella Bloque 2.5kg', unit: 'bloque', price_per_unit: 48500, supplier_id: 1, supplier_name: 'Lácteos del Valle', reason: 'Insumo esencial para pizzas y hamburguesas' }, - { id: 202, name: 'Aceite Vegetal Palma Oro 20L', unit: 'caneca', price_per_unit: 115000, supplier_id: 1, supplier_name: 'Distribuidora Central', reason: 'Rotación alta en freidoras' }, - { id: 203, name: 'Carne Molida Especial Burger 80/20', unit: 'kg', price_per_unit: 24500, supplier_id: 1, supplier_name: 'Carnes El Paisa', reason: 'Base diaria de producción' }, - { id: 204, name: 'Papas Prefritas Corte Grueso 2.5kg', unit: 'bolsa', price_per_unit: 22000, supplier_id: 1, supplier_name: 'Congelados Andinos', reason: 'Acompañamiento estrella' }, - { id: 205, name: 'Salsa Tártara y BBQ Artesanal 4kg', unit: 'galón', price_per_unit: 32000, supplier_id: 1, supplier_name: 'Distribuidora Central', reason: 'Insumo de mesa y cocina' }, - { id: 206, name: 'Pan Brioche Hamburguesa x 30 uds', unit: 'paquete', price_per_unit: 28000, supplier_id: 1, supplier_name: 'Panadería Santa Clara', reason: 'Panadería fresca recomendada' }, - ]; - } + ); + const daily_suggestions = sugRes.rows; // 4. Descuentos del día (Promociones especiales de proveedores) const descRes = await query( @@ -161,16 +134,8 @@ router.get('/summary', async (req, res, next) => { WHERE p.is_active = TRUE AND p.stock_available > 0 ORDER BY p.price_per_unit DESC LIMIT 4` - ).catch(() => ({ rows: [] })); - let daily_discounts = descRes.rows; - if (daily_discounts.length === 0) { - daily_discounts = [ - { id: 301, name: 'Tocineta Ahumada Premium 1kg', unit: 'kg', price_per_unit: 28900, original_price: 36000, discount_pct: 20, supplier_id: 1, supplier_name: 'Carnes El Paisa', promo_tag: 'Oferta Flash 20% OFF' }, - { id: 302, name: 'Caja de Guantes de Nitrilo x 100', unit: 'caja', price_per_unit: 18500, original_price: 24000, discount_pct: 23, supplier_id: 1, supplier_name: 'Insumos & Desechables', promo_tag: 'Promo de Higiene' }, - { id: 303, name: 'Queso Cheddar Fundido en Barra 2kg', unit: 'barra', price_per_unit: 42000, original_price: 52000, discount_pct: 19, supplier_id: 1, supplier_name: 'Lácteos del Valle', promo_tag: 'Descuento Mayorista' }, - { id: 304, name: 'Pechuga de Pollo Fileteada x 5kg', unit: 'paquete', price_per_unit: 62000, original_price: 78000, discount_pct: 20, supplier_id: 1, supplier_name: 'Avícola Santander', promo_tag: 'Super Oferta de la Semana' }, - ]; - } + ); + const daily_discounts = descRes.rows; // 5. Proveedor: Info de sus productos y restaurantes clientes potenciales basados en lo que vende let my_products = null; @@ -203,33 +168,25 @@ router.get('/summary', async (req, res, next) => { ${myProdWhere} ORDER BY p.stock_available ASC LIMIT 8`, myProdParams - ).catch(() => ({ rows: [] })); + ); my_products = { total_skus: productsCount, low_stock_count: prodListRes.rows.filter((p: any) => p.stock_available < 15).length, - items: prodListRes.rows.length > 0 ? prodListRes.rows : [ - { id: 401, name: 'Carne Hamburguesa 150g x 10', unit: 'paquete', price_per_unit: 34000, stock_available: 8, sku: 'CRN-001', is_active: true }, - { id: 402, name: 'Costilla BBQ Ahumada', unit: 'kg', price_per_unit: 29500, stock_available: 4, sku: 'CRN-002', is_active: true }, - { id: 403, name: 'Lomo Fino de Res', unit: 'kg', price_per_unit: 42000, stock_available: 22, sku: 'CRN-003', is_active: true }, - ], + items: prodListRes.rows, }; + // Directorio de prospectos: solo datos públicos del comercio. No se + // exponen teléfono, correo ni dirección de otros inquilinos. const restRes = await query( - `SELECT r.id, r.name, r.city, r.address, r.phone, r.email, r.category, r.created_at + `SELECT r.id, r.name, r.city, r.category, r.created_at FROM restaurants r + WHERE r.is_active = TRUE ORDER BY r.created_at DESC LIMIT 10` - ).catch(() => ({ rows: [] })); + ); - emerging_restaurants = restRes.rows.length > 0 ? restRes.rows : [ - { id: 501, name: 'Rancho Grande BGA', category: 'BBQ & Parrilla', city: 'Bucaramanga', address: 'Cra 27 #45-32, Cabecera', phone: '(607) 634-5678', email: 'info@ranchogrande.com', created_at: new Date().toISOString() }, - { id: 502, name: 'Fogon Santandereano', category: 'Latino & Comida Típica', city: 'Bucaramanga', address: 'Calle 35 #22-10, San Pio', phone: '(607) 634-1234', email: 'contacto@fogonsantandereano.com', created_at: new Date().toISOString() }, - { id: 503, name: 'El Corral BGA', category: 'Hamburguesas & Fast Food', city: 'Bucaramanga', address: 'Cra 30 #55-18, Cabecera', phone: '(607) 634-4321', email: 'info@elcorralbga.com', created_at: new Date().toISOString() }, - { id: 504, name: 'Sweet Bakery & Café', category: 'Postres & Pastelería', city: 'Floridablanca', address: 'Cañaveral Plaza Local 12', phone: '3189988776', email: 'hola@sweetbakery.com', created_at: new Date().toISOString() }, - { id: 505, name: 'Brunch & Co. Búcaros', category: 'Brunch & Cafés', city: 'Bucaramanga', address: 'Calle 48 #34-20', phone: '3157766554', email: 'pedidos@brunchco.com', created_at: new Date().toISOString() }, - { id: 506, name: 'Sushi Sakura Gourmet', category: 'Asiático & Sushi', city: 'Bucaramanga', address: 'Carrera 36 #52-19', phone: '3174433221', email: 'contacto@sakurabga.com', created_at: new Date().toISOString() }, - ]; + emerging_restaurants = restRes.rows; // Calcular prospectos potenciales basados en lo que vende el proveedor prospective_restaurants = emerging_restaurants.map((rest: any) => { @@ -287,7 +244,7 @@ router.get('/summary', async (req, res, next) => { WHERE d.driver_id = $1 AND d.status NOT IN ('entregado', 'fallido') ORDER BY d.created_at DESC`, [user.id] - ).catch(() => ({ rows: [] })); + ); today_deliveries = delivRes.rows; } @@ -296,15 +253,9 @@ router.get('/summary', async (req, res, next) => { const rawSuppliers = await query( `SELECT s.id, s.name, s.category, s.rating, s.review_count, s.city, s.phone, s.logo_url FROM suppliers s WHERE s.is_active = TRUE` - ).catch(() => ({ rows: [] })); + ); - const supRows = rawSuppliers.rows.length > 0 ? rawSuppliers.rows : [ - { id: 1, name: 'Carnes El Paisa S.A.S', category: 'Carnes', rating: 4.8, review_count: 45, city: 'Bucaramanga' }, - { id: 2, name: 'Lacteos del Norte', category: 'Lacteos', rating: 4.6, review_count: 32, city: 'Bucaramanga' }, - { id: 3, name: 'Mariscos del Caribe', category: 'Mariscos', rating: 4.9, review_count: 28, city: 'Bucaramanga' }, - { id: 4, name: 'Verduras Frescas SAS', category: 'Verduras', rating: 4.5, review_count: 19, city: 'Bucaramanga' }, - { id: 5, name: 'Distribuidora de Bebidas', category: 'Bebidas', rating: 4.7, review_count: 37, city: 'Bucaramanga' }, - ]; + const supRows = rawSuppliers.rows; const categoryPhotos: Record = { 'Carnes': { diff --git a/src/routes/deliveries.ts b/src/routes/deliveries.ts index 55c22ee..b257dc8 100644 --- a/src/routes/deliveries.ts +++ b/src/routes/deliveries.ts @@ -1,5 +1,6 @@ import { Router } from 'express'; -import { query } from '../config/db'; +import { timingSafeEqual } from 'crypto'; +import { pool, query } from '../config/db'; import { authRequired, roleRequired } from '../middleware/auth'; import { emitOrder, emitToUser, emitDeliveryPosition, emitDeliveryStatus } from '../lib/realtime'; import { resolveBucaramangaCoords, BUCARAMANGA_DESTINATIONS, BUCARAMANGA_DISPATCH_HUBS } from '../lib/bucaramangaGeo'; @@ -45,6 +46,43 @@ function deliveryAccessWhere(user: { return { clause: '', params: [] as unknown[] }; } +type DeliveryUser = { + role: string; + id: number; + supplier_id: number | null; + restaurant_id: number | null; +}; + +type DeliveryRow = Record; + +/** + * El código de confirmación es una llave de doble control: lo lleva el + * domiciliario y lo valida el restaurante al recibir. Por eso NO debe + * devolverse a los usuarios del restaurante (podrían auto-confirmar sin que + * el conductor esté presente), ni a proveedores de otro inquilino. + */ +function canSeeConfirmationCode(user: DeliveryUser, row: DeliveryRow): boolean { + if (user.role === 'admin') return true; + if ( + user.role === 'proveedor_admin' && + user.supplier_id && + Number(row.order_supplier_id) === Number(user.supplier_id) + ) { + return true; + } + if (user.role === 'domiciliario' && Number(row.driver_id) === Number(user.id)) { + return true; + } + return false; +} + +/** Quita el código de confirmación de la respuesta para quien no debe verlo. */ +function redactDelivery(row: T, user: DeliveryUser): T { + if (!row || canSeeConfirmationCode(user, row)) return row; + const { confirmation_code, ...rest } = row; + return { ...rest, has_security_code: Boolean(confirmation_code) } as unknown as T; +} + router.get('/', async (req, res, next) => { try { const user = req.user!; @@ -66,7 +104,7 @@ router.get('/', async (req, res, next) => { } sql += ' ORDER BY d.created_at DESC LIMIT 100'; const result = await query(sql, params); - res.json(result.rows); + res.json(result.rows.map((row) => redactDelivery(row, user))); } catch (err) { next(err); } @@ -81,7 +119,7 @@ router.get('/my-deliveries', roleRequired('domiciliario'), async (req, res, next ORDER BY d.created_at DESC LIMIT 50`, [user.id] ); - res.json(result.rows); + res.json(result.rows.map((row) => redactDelivery(row, user))); } catch (err) { next(err); } @@ -131,7 +169,7 @@ router.get('/live', async (req, res, next) => { } } rows.push({ - ...r, + ...redactDelivery(r, user), position: lat !== null && lng !== null ? { lat, lng, recorded_at: updatedAt } : null, eta_min: lat !== null && lng !== null @@ -145,19 +183,31 @@ router.get('/live', async (req, res, next) => { } }); +// Las columnas de asignación de vehículos y las coordenadas reales se +// gestionan en lib/migrations.ts. No se mutan datos de demo en cada arranque. + router.get('/vehicles', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { try { const user = req.user!; + const safeColumns = `v.id, v.supplier_id, v.name, v.plate, v.type, v.status, v.driver_id, + v.current_lat, v.current_lng, v.last_location_update, + v.gps_validated, v.gps_last_seen, v.is_active, v.created_at, v.updated_at`; + const adminColumns = user.role === 'admin' || user.role === 'proveedor_admin' ? ', v.imei' : ''; let sql = ` - SELECT v.*, u.name AS driver_name, u.phone AS driver_phone, u.username AS driver_username + SELECT ${safeColumns}${adminColumns}, u.name AS driver_name, u.phone AS driver_phone, u.username AS driver_username FROM vehicles v LEFT JOIN users u ON u.id = v.driver_id WHERE v.is_active = TRUE `; const params: unknown[] = []; - if (user.role === 'proveedor_admin' && user.supplier_id) { + if (user.role === 'proveedor_admin') { + if (!user.supplier_id) return res.status(403).json({ error: 'El usuario proveedor no tiene un proveedor asociado' }); params.push(user.supplier_id); - sql += ` AND (v.supplier_id = $1 OR v.supplier_id IS NULL)`; + sql += ` AND v.supplier_id = $${params.length}`; + } else if (user.role === 'gerente') { + // El restaurante solo puede ver la flota de proveedores con los que opera. + params.push(user.restaurant_id); + sql += ` AND v.supplier_id IN (SELECT DISTINCT o.supplier_id FROM orders o WHERE o.restaurant_id = $${params.length})`; } sql += ' ORDER BY v.name'; const result = await query(sql, params); @@ -167,14 +217,26 @@ router.get('/vehicles', roleRequired('proveedor_admin', 'admin', 'gerente'), asy } }); -router.get('/drivers', roleRequired('proveedor_admin', 'admin', 'gerente'), async (_req, res, next) => { +router.get('/drivers', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { try { + const user = req.user!; + const params: unknown[] = []; + let supplierFilter = ''; + if (user.role === 'proveedor_admin') { + if (!user.supplier_id) { + return res.status(403).json({ error: 'El usuario proveedor no tiene un proveedor asociado' }); + } + params.push(user.supplier_id); + supplierFilter = ` AND u.supplier_id = $${params.length}`; + } const result = await query( `SELECT u.id, u.name, u.username, u.phone, u.email, r.name AS role_name, r.display_name AS role_label FROM users u JOIN roles r ON r.id = u.role_id WHERE u.is_active = TRUE - ORDER BY (r.name = 'domiciliario') DESC, u.name ASC` + AND r.name = 'domiciliario'${supplierFilter} + ORDER BY u.name ASC`, + params ); res.json(result.rows); } catch (err) { @@ -191,7 +253,7 @@ router.get('/:id', async (req, res, next) => { const delivery = result.rows[0]; const items = await query('SELECT * FROM delivery_items WHERE delivery_id = $1', [req.params.id]); const orderItems = await query('SELECT * FROM order_items WHERE order_id = $1', [delivery.order_id]); - res.json({ ...delivery, items: items.rows, order_items: orderItems.rows }); + res.json({ ...redactDelivery(delivery, user), items: items.rows, order_items: orderItems.rows }); } catch (err) { next(err); } @@ -213,6 +275,36 @@ router.post('/', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req const order = await query(orderSql, orderParams); if (!order.rowCount) return res.status(404).json({ error: 'Pedido no encontrado o no autorizado' }); + // Validar que conductor y vehículo pertenezcan al proveedor del pedido + // (evita asignaciones cruzadas entre inquilinos). + const orderSupplierId = order.rows[0].supplier_id; + if (driver_id) { + const driver = await query( + `SELECT u.id, u.supplier_id, r.name AS role_name + FROM users u JOIN roles r ON r.id = u.role_id + WHERE u.id = $1 AND u.is_active = TRUE`, + [Number(driver_id)] + ); + if (!driver.rowCount || driver.rows[0].role_name !== 'domiciliario') { + return res.status(400).json({ error: 'El domiciliario seleccionado no existe o está inactivo' }); + } + if (user.role !== 'admin' && Number(driver.rows[0].supplier_id) !== Number(orderSupplierId)) { + return res.status(403).json({ error: 'El domiciliario no pertenece al proveedor del pedido' }); + } + } + if (vehicle_id) { + const vehicle = await query( + 'SELECT id, supplier_id FROM vehicles WHERE id = $1 AND is_active = TRUE', + [Number(vehicle_id)] + ); + if (!vehicle.rowCount) { + return res.status(400).json({ error: 'El vehículo seleccionado no existe o está inactivo' }); + } + if (user.role !== 'admin' && Number(vehicle.rows[0].supplier_id) !== Number(orderSupplierId)) { + return res.status(403).json({ error: 'El vehículo no pertenece al proveedor del pedido' }); + } + } + // Verificar si ya existe una entrega para este pedido const existing = await query('SELECT * FROM deliveries WHERE order_id = $1', [order_id]); let deliveryRow; @@ -281,43 +373,83 @@ router.post('/', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req }); } - emitDeliveryStatus(deliveryRow, { delivery_id: deliveryRow.id, status: deliveryRow.status, delivery_code: deliveryRow.delivery_code, restaurant_id: deliveryRow.restaurant_id, supplier_id: deliveryRow.order_supplier_id }); - res.status(existing.rowCount ? 200 : 201).json(deliveryRow); + const fullDelivery = await query(`${deliverySelect()} WHERE d.id = $1`, [deliveryRow.id]); + const deliveryFull = fullDelivery.rows[0] ?? deliveryRow; + emitDeliveryStatus(deliveryFull, { delivery_id: deliveryFull.id, status: deliveryFull.status, delivery_code: deliveryFull.delivery_code, restaurant_id: deliveryFull.restaurant_id, supplier_id: deliveryFull.order_supplier_id }); + res.status(existing.rowCount ? 200 : 201).json(redactDelivery(deliveryFull, user)); } catch (err) { next(err); } }); router.patch('/:id/assign', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { + let client; try { const user = req.user!; - const { driver_id } = req.body; - if (!driver_id) return res.status(400).json({ error: 'driver_id es requerido' }); + const driverId = Number(req.body.driver_id); + const vehicleId = Number(req.body.vehicle_id); + if (!Number.isInteger(driverId) || driverId <= 0) { + return res.status(400).json({ error: 'Selecciona un domiciliario válido' }); + } + if (!Number.isInteger(vehicleId) || vehicleId <= 0) { + return res.status(400).json({ error: 'Selecciona un vehículo válido' }); + } + + client = await pool.connect(); + await client.query('BEGIN'); const access = deliveryAccessWhere(user, 2); - const delivery = await query(`${deliverySelect()} WHERE d.id = $1${access.clause}`, [req.params.id, ...access.params]); - if (!delivery.rowCount) return res.status(404).json({ error: 'Entrega no encontrada o no autorizada' }); + const delivery = await client.query( + `${deliverySelect()} WHERE d.id = $1${access.clause} FOR UPDATE OF d`, + [req.params.id, ...access.params] + ); + if (!delivery.rowCount) { + await client.query('ROLLBACK'); + return res.status(404).json({ error: 'Entrega no encontrada o no autorizada' }); + } const del = delivery.rows[0]; - const driver = await query( + const driver = await client.query( `SELECT u.*, r.name AS role_name FROM users u JOIN roles r ON r.id = u.role_id WHERE u.id = $1 AND u.is_active = TRUE`, - [driver_id] + [driverId] ); if (!driver.rowCount) { + await client.query('ROLLBACK'); return res.status(400).json({ error: 'El usuario seleccionado no existe o está inactivo' }); } - const driverRow = driver.rows[0]; - if (driverRow.role_name !== 'domiciliario' && user.role !== 'admin') { - return res.status(400).json({ error: 'El usuario seleccionado no tiene rol de domiciliario' }); + if (driver.rows[0].role_name !== 'domiciliario') { + await client.query('ROLLBACK'); + return res.status(400).json({ error: 'El usuario seleccionado no tiene el rol de domiciliario' }); + } + if (user.role !== 'admin' && Number(driver.rows[0].supplier_id) !== Number(del.order_supplier_id)) { + await client.query('ROLLBACK'); + return res.status(403).json({ error: 'El domiciliario no pertenece al proveedor del pedido' }); } - if (user.supplier_id && driverRow.supplier_id && driverRow.supplier_id !== user.supplier_id) { - return res.status(403).json({ error: 'El domiciliario no pertenece a tu proveedor' }); + + const vehicle = await client.query( + `SELECT id FROM vehicles + WHERE id = $1 AND is_active = TRUE + AND ($2::boolean = TRUE OR supplier_id = $3) + FOR UPDATE`, + [vehicleId, user.role === 'admin', del.order_supplier_id] + ); + if (!vehicle.rowCount) { + await client.query('ROLLBACK'); + return res.status(400).json({ error: 'El vehículo no está activo o no pertenece al proveedor del pedido' }); } + const confirmationCode = del.confirmation_code || String(Math.floor(1000 + Math.random() * 9000)); - const result = await query( - `UPDATE deliveries SET driver_id = $1, confirmation_code = $2, updated_at = CURRENT_TIMESTAMP - WHERE id = $3 RETURNING *`, - [driver_id, confirmationCode, req.params.id] + await client.query( + `UPDATE vehicles SET driver_id = $1, driver_name = $2, updated_at = CURRENT_TIMESTAMP + WHERE id = $3`, + [driverId, driver.rows[0].name, vehicleId] + ); + const result = await client.query( + `UPDATE deliveries + SET driver_id = $1, vehicle_id = $2, confirmation_code = $3, updated_at = CURRENT_TIMESTAMP + WHERE id = $4 RETURNING *`, + [driverId, vehicleId, confirmationCode, req.params.id] ); + await client.query('COMMIT'); // Sincronizar estado del pedido a despachado si aún no lo estaba const currentOrder = await query('SELECT id, status, order_code FROM orders WHERE id = $1', [del.order_id]); @@ -332,15 +464,26 @@ router.patch('/:id/assign', roleRequired('proveedor_admin', 'admin', 'gerente'), emitOrder('order:updated', updatedOrder.rows[0]); } - emitToUser('notification:created', driver_id, { + emitToUser('notification:created', driverId, { message: `Se te asignó la entrega ${del.delivery_code}`, delivery_id: del.id, confirmation_code: confirmationCode, }); - emitDeliveryStatus(del, { delivery_id: del.id, status: result.rows[0].status, delivery_code: del.delivery_code, restaurant_id: del.restaurant_id, supplier_id: del.order_supplier_id }); - res.json(result.rows[0]); + const assignedFull = await query(`${deliverySelect()} WHERE d.id = $1`, [del.id]); + const assignedRow = assignedFull.rows[0] ?? { ...del, status: result.rows[0].status }; + emitDeliveryStatus(assignedRow, { delivery_id: del.id, status: result.rows[0].status, delivery_code: del.delivery_code, restaurant_id: del.restaurant_id, supplier_id: del.order_supplier_id }); + res.json(redactDelivery(assignedRow, user)); } catch (err) { + if (client) { + try { + await client.query('ROLLBACK'); + } catch (rollbackError) { + console.error('Error revirtiendo la asignación de entrega:', rollbackError); + } + } next(err); + } finally { + client?.release(); } }); @@ -354,15 +497,20 @@ router.patch('/:id/status', async (req, res, next) => { const delivery = await query(`${deliverySelect()} WHERE d.id = $1${access.clause}`, [req.params.id, ...access.params]); if (!delivery.rowCount) return res.status(404).json({ error: 'Entrega no encontrada' }); const del = delivery.rows[0]; - if (user.role === 'domiciliario' && !['en_camino', 'llegando', 'entregado'].includes(status)) { - return res.status(403).json({ error: 'El domiciliario solo puede cambiar a en_camino, llegando o entregado' }); + if (user.role === 'domiciliario' && !['en_camino', 'llegando'].includes(status)) { + return res.status(403).json({ error: 'El domiciliario solo puede cambiar a en_camino o llegando' }); } - if (status === 'entregado' && user.role === 'domiciliario') { - return res.status(400).json({ error: 'Usa POST /:id/confirm con el código de confirmación para entregar' }); + if ((user.role === 'gerente' || user.role === 'empleado') && status !== 'fallido') { + return res.status(403).json({ error: 'El restaurante solo puede reportar la entrega como fallida' }); + } + if (status === 'entregado' && user.role !== 'admin') { + return res.status(403).json({ + error: 'La entrega solo se completa con el código de confirmación. Usa POST /:id/confirm.', + }); } const deliveredSql = status === 'entregado' ? ', actual_delivery_time = CURRENT_TIMESTAMP' : ''; - const result = await query( - `UPDATE deliveries SET status = $1, updated_at = CURRENT_TIMESTAMP${deliveredSql} WHERE id = $2 RETURNING *`, + await query( + `UPDATE deliveries SET status = $1, updated_at = CURRENT_TIMESTAMP${deliveredSql} WHERE id = $2`, [status, req.params.id] ); if (status === 'en_camino') { @@ -386,13 +534,55 @@ router.patch('/:id/status', async (req, res, next) => { emitOrder('order:updated', updated.rows[0]); } emitDeliveryStatus(del, { delivery_id: del.id, status, delivery_code: del.delivery_code, restaurant_id: del.restaurant_id, supplier_id: del.order_supplier_id }); - res.json(result.rows[0]); + const statusFull = await query(`${deliverySelect()} WHERE d.id = $1`, [del.id]); + res.json(redactDelivery(statusFull.rows[0] ?? { ...del, status }, user)); } catch (err) { next(err); } }); -router.post('/:id/confirm', roleRequired('domiciliario', 'gerente', 'admin'), async (req, res, next) => { +// Límite de intentos de la llave de entrega (anti fuerza bruta de 4 dígitos). +// Se cuenta por usuario + entrega para no bloquear a otros usuarios legítimos. +const confirmAttempts = new Map(); +const CONFIRM_MAX_ATTEMPTS = 5; +const CONFIRM_WINDOW_MS = 10 * 60 * 1000; + +function confirmKey(userId: number, deliveryId: number): string { + return `${userId}:${deliveryId}`; +} + +function checkConfirmRateLimit(userId: number, deliveryId: number): boolean { + const now = Date.now(); + const key = confirmKey(userId, deliveryId); + const entry = confirmAttempts.get(key); + if (!entry || entry.resetAt <= now) { + confirmAttempts.set(key, { count: 0, resetAt: now + CONFIRM_WINDOW_MS }); + return true; + } + return entry.count < CONFIRM_MAX_ATTEMPTS; +} + +function registerConfirmFailure(userId: number, deliveryId: number): void { + const key = confirmKey(userId, deliveryId); + const entry = confirmAttempts.get(key); + if (entry) entry.count += 1; + else confirmAttempts.set(key, { count: 1, resetAt: Date.now() + CONFIRM_WINDOW_MS }); + if (confirmAttempts.size > 5000) { + const now = Date.now(); + for (const [mapKey, value] of confirmAttempts) { + if (value.resetAt <= now) confirmAttempts.delete(mapKey); + } + } +} + +function codesMatch(expected: string, received: string): boolean { + const a = Buffer.from(String(expected).trim()); + const b = Buffer.from(String(received).trim()); + if (a.length !== b.length || a.length === 0) return false; + return timingSafeEqual(a, b); +} + +router.post('/:id/confirm', roleRequired('gerente', 'empleado', 'admin'), async (req, res, next) => { try { const user = req.user!; const { confirmation_code } = req.body; @@ -406,16 +596,21 @@ router.post('/:id/confirm', roleRequired('domiciliario', 'gerente', 'admin'), as if (del.status === 'entregado') { return res.status(400).json({ error: 'Esta entrega ya fue confirmada previamente' }); } + if (!checkConfirmRateLimit(user.id, del.id)) { + return res.status(429).json({ error: 'Demasiados intentos fallidos. Espera unos minutos o solicita un nuevo código.' }); + } // Validación estricta del código / llave de entrega - if (String(del.confirmation_code).trim() !== String(confirmation_code).trim()) { + if (!codesMatch(del.confirmation_code, confirmation_code)) { + registerConfirmFailure(user.id, del.id); return res.status(401).json({ error: 'Llave de entrega incorrecta. Verifica el código con el domiciliario.' }); } + confirmAttempts.delete(confirmKey(user.id, del.id)); - const result = await query( + await query( `UPDATE deliveries SET status = 'entregado', actual_delivery_time = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP - WHERE id = $1 RETURNING *`, + WHERE id = $1`, [req.params.id] ); @@ -443,7 +638,7 @@ router.post('/:id/confirm', roleRequired('domiciliario', 'gerente', 'admin'), as }); } - res.json({ message: 'Envío completado exitosamente con la llave de entrega', delivery: result.rows[0] }); + res.json({ message: 'Envío completado exitosamente con la llave de entrega', delivery: redactDelivery({ ...del, status: 'entregado' }, user) }); } catch (err) { next(err); } @@ -646,19 +841,41 @@ router.get('/:id/track', async (req, res, next) => { } }); -router.post('/vehicles', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { +router.post('/vehicles', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { const user = req.user!; const { name, plate, type, driver_id, imei } = req.body; + if (!name || !plate) return res.status(400).json({ error: 'name y plate son obligatorios' }); + if (imei && String(imei).length > 20) return res.status(400).json({ error: 'imei inválido' }); + + const supplierId = user.role === 'admin' ? Number(req.body.supplier_id) : user.supplier_id; + if (!supplierId || !Number.isInteger(supplierId)) { + return res.status(400).json({ error: 'supplier_id es obligatorio para crear un vehículo' }); + } + if (user.role === 'proveedor_admin' && Number(supplierId) !== Number(user.supplier_id)) { + return res.status(403).json({ error: 'No autorizado para crear vehículos de otro proveedor' }); + } + let driverName = req.body.driver_name || null; if (driver_id) { - const u = await query('SELECT name FROM users WHERE id = $1', [driver_id]).catch(() => ({ rows: [] })); - if (u.rows[0]) driverName = u.rows[0].name; + const u = await query( + `SELECT u.id, u.name, u.supplier_id, r.name AS role_name + FROM users u JOIN roles r ON r.id = u.role_id WHERE u.id = $1 AND u.is_active = TRUE`, + [Number(driver_id)] + ); + if (!u.rowCount || u.rows[0].role_name !== 'domiciliario') { + return res.status(400).json({ error: 'El conductor debe ser un domiciliario activo' }); + } + if (Number(u.rows[0].supplier_id) !== Number(supplierId)) { + return res.status(403).json({ error: 'El conductor no pertenece al proveedor' }); + } + driverName = u.rows[0].name; } + const result = await query( `INSERT INTO vehicles (supplier_id, name, plate, type, driver_id, driver_name, imei, gps_validated) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`, - [user.supplier_id || null, name, plate, type ?? 'moto', driver_id ? Number(driver_id) : null, driverName, imei || null, Boolean(imei)] + [supplierId, name, plate, type ?? 'moto', driver_id ? Number(driver_id) : null, driverName, imei || null, Boolean(imei)] ); res.status(201).json(result.rows[0]); } catch (err) { @@ -666,14 +883,35 @@ router.post('/vehicles', roleRequired('proveedor_admin', 'admin', 'gerente'), as } }); -router.put('/vehicles/:id', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { +router.put('/vehicles/:id', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { + const user = req.user!; const { name, plate, type, driver_id, imei } = req.body; + if (imei && String(imei).length > 20) return res.status(400).json({ error: 'imei inválido' }); + + const vehicle = await query( + `SELECT id, supplier_id FROM vehicles + WHERE id = $1 AND ($2::boolean = TRUE OR supplier_id = $3)`, + [req.params.id, user.role === 'admin', user.supplier_id] + ); + if (!vehicle.rowCount) return res.status(404).json({ error: 'Vehículo no encontrado' }); + let driverName = req.body.driver_name || null; if (driver_id) { - const u = await query('SELECT name FROM users WHERE id = $1', [driver_id]).catch(() => ({ rows: [] })); - if (u.rows[0]) driverName = u.rows[0].name; + const u = await query( + `SELECT u.id, u.name, u.supplier_id, r.name AS role_name + FROM users u JOIN roles r ON r.id = u.role_id WHERE u.id = $1 AND u.is_active = TRUE`, + [Number(driver_id)] + ); + if (!u.rowCount || u.rows[0].role_name !== 'domiciliario') { + return res.status(400).json({ error: 'El conductor debe ser un domiciliario activo' }); + } + if (Number(u.rows[0].supplier_id) !== Number(vehicle.rows[0].supplier_id)) { + return res.status(403).json({ error: 'El conductor no pertenece al proveedor del vehículo' }); + } + driverName = u.rows[0].name; } + const result = await query( `UPDATE vehicles SET name = COALESCE($1, name), @@ -693,13 +931,15 @@ router.put('/vehicles/:id', roleRequired('proveedor_admin', 'admin', 'gerente'), } }); -router.patch('/vehicles/:id/gps', roleRequired('proveedor_admin', 'admin', 'gerente'), async (req, res, next) => { +router.patch('/vehicles/:id/gps', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { + const user = req.user!; const { imei, gps_validated } = req.body; + if (imei && String(imei).length > 20) return res.status(400).json({ error: 'imei inválido' }); const result = await query( `UPDATE vehicles SET imei = $1, gps_validated = $2, updated_at = CURRENT_TIMESTAMP - WHERE id = $3 RETURNING *`, - [imei || null, Boolean(gps_validated), req.params.id] + WHERE id = $3 AND ($4::boolean = TRUE OR supplier_id = $5) RETURNING *`, + [imei || null, Boolean(gps_validated), req.params.id, user.role === 'admin', user.supplier_id] ); if (!result.rowCount) return res.status(404).json({ error: 'Vehículo no encontrado' }); res.json(result.rows[0]); diff --git a/src/routes/invoices.ts b/src/routes/invoices.ts index 27ce8e7..153e892 100644 --- a/src/routes/invoices.ts +++ b/src/routes/invoices.ts @@ -96,11 +96,12 @@ router.post('/', roleRequired('gerente', 'admin'), async (req, res, next) => { await logAudit(req, 'create', 'invoice', invoiceId, null, { code, total }); const invoice = await query('SELECT * FROM invoices WHERE id = $1', [invoiceId]); if (client_email) { - sendEmail({ + void sendEmail({ to_email: client_email, to_name: client_name ?? client_email, subject: `Factura ${code}`, body: `Tu factura ${code} por $${total} está disponible en Xupply.`, + category: 'transactional', }); } res.status(201).json(invoice.rows[0]); diff --git a/src/routes/orders.ts b/src/routes/orders.ts index f1bab0a..132539e 100644 --- a/src/routes/orders.ts +++ b/src/routes/orders.ts @@ -30,6 +30,7 @@ function orderSelect() { function orderAccessWhere(user: { role: string; + id: number; supplier_id: number | null; restaurant_id: number | null; }, startIndex = 1) { @@ -37,7 +38,10 @@ function orderAccessWhere(user: { return { clause: ` AND o.supplier_id = $${startIndex}`, params: [user.supplier_id] as unknown[] }; } if (user.role === 'domiciliario') { - return { clause: '', params: [] as unknown[] }; + return { + clause: ` AND EXISTS (SELECT 1 FROM deliveries d WHERE d.order_id = o.id AND d.driver_id = $${startIndex})`, + params: [user.id] as unknown[], + }; } if (user.restaurant_id) { return { clause: ` AND o.restaurant_id = $${startIndex}`, params: [user.restaurant_id] as unknown[] }; @@ -99,11 +103,24 @@ router.post('/', roleRequired('gerente', 'empleado', 'admin'), async (req, res, await client.query('ROLLBACK'); return res.status(400).json({ error: `El supplier_id ${supplier_id} no existe` }); } + // La sucursal debe pertenecer al restaurante del usuario (evita pedidos + // asociados a sucursales de otro inquilino). + const branchId = branch_id ? Number(branch_id) : user.branch_id; + if (branchId) { + const branch = await client.query('SELECT 1 FROM branches WHERE id = $1 AND restaurant_id = $2', [ + branchId, + user.restaurant_id, + ]); + if (!branch.rowCount) { + await client.query('ROLLBACK'); + return res.status(400).json({ error: 'La sucursal indicada no pertenece a tu restaurante' }); + } + } const code = `ORDER-${Date.now().toString(36).toUpperCase()}`; const inserted = await client.query( `INSERT INTO orders (order_code, restaurant_id, branch_id, supplier_id, status, notes, delivery_address, requested_delivery_date, created_by) VALUES ($1, $2, $3, $4, 'nuevo', $5, $6, $7, $8) RETURNING id`, - [code, user.restaurant_id, branch_id ?? user.branch_id, supplier_id, notes, delivery_address, requested_delivery_date, user.id] + [code, user.restaurant_id, branchId ?? null, supplier_id, notes, delivery_address, requested_delivery_date, user.id] ); const orderId = inserted.rows[0].id; let total = 0; @@ -142,11 +159,12 @@ router.post('/', roleRequired('gerente', 'empleado', 'admin'), async (req, res, const order = { ...full.rows[0], items: (await query('SELECT * FROM order_items WHERE order_id = $1', [orderId])).rows }; emitOrder('order:created', order); if (order.supplier_email) { - sendEmail({ + void sendEmail({ to_email: order.supplier_email, to_name: order.supplier_name, subject: `Nuevo pedido ${order.order_code}`, body: `Recibiste el pedido ${order.order_code} por $${total}.`, + category: 'transactional', }); } res.status(201).json(order); @@ -187,14 +205,15 @@ router.get('/:id', async (req, res, next) => { ); let deliveriesList = deliveries.rows; - // Para el gerente, el domiciliario lleva el código; el gerente no lo ve en la pantalla antes de la entrega - if (user.role === 'gerente' || (user.restaurant_id && user.role !== 'admin')) { + // El código de confirmación lo lleva el domiciliario y lo valida el + // restaurante: los usuarios del restaurante NO deben verlo por API + // (podrían auto-confirmar sin la presencia del conductor). + const isRestaurantUser = + user.role === 'gerente' || user.role === 'empleado' || (user.restaurant_id !== null && user.role !== 'admin'); + if (isRestaurantUser) { deliveriesList = deliveriesList.map((d: any) => { - if (d.status !== 'entregado') { - const { confirmation_code, ...rest } = d; - return { ...rest, has_security_code: true }; - } - return d; + const { confirmation_code, ...rest } = d; + return { ...rest, has_security_code: Boolean(confirmation_code) }; }); } @@ -223,6 +242,15 @@ router.patch('/:id/status', roleRequired('admin', 'gerente', 'empleado', 'provee if (user.restaurant_id && order.restaurant_id !== user.restaurant_id) { return res.status(403).json({ error: 'No autorizado' }); } + if (user.role !== 'admin') { + const hasTenant = user.role === 'proveedor_admin' ? Boolean(user.supplier_id) : Boolean(user.restaurant_id); + if (!hasTenant) return res.status(403).json({ error: 'Usuario sin inquilino asignado' }); + } + if (status === 'entregado' && user.role !== 'admin') { + return res.status(403).json({ + error: 'El pedido solo se marca como entregado con la llave de entrega (POST /api/deliveries/:id/confirm).', + }); + } const allowed = STATUS_TRANSITIONS[order.status] ?? []; if (!allowed.includes(status)) { return res.status(400).json({ error: `No se puede pasar de "${order.status}" a "${status}"` }); diff --git a/src/routes/products.ts b/src/routes/products.ts index a6857b0..8d40490 100644 --- a/src/routes/products.ts +++ b/src/routes/products.ts @@ -62,50 +62,28 @@ router.post('/', roleRequired('proveedor_admin', 'admin'), async (req, res, next return res.status(400).json({ error: 'name y price_per_unit son requeridos' }); } - let supplierId = user.supplier_id || (req.body.supplier_id ? Number(req.body.supplier_id) : null); + // El proveedor SIEMPRE sale del usuario autenticado. Un admin puede indicarlo + // explícitamente, pero se valida que exista. Antes, si faltaba supplier_id, + // el código "adivinaba" un proveedor por email/nombre (o el primero de la + // tabla) y podía asignar el producto —y al usuario— a otro inquilino. + let supplierId: number | null = user.supplier_id ? Number(user.supplier_id) : null; - // Si el usuario no tiene supplier_id en el token - if (!supplierId) { - // 1. Verificar en base de datos por si su usuario ya tiene supplier_id - const userDb = await query('SELECT supplier_id, email, name FROM users WHERE id = $1', [user.id]); - if (userDb.rowCount && userDb.rows[0].supplier_id) { - supplierId = userDb.rows[0].supplier_id; - } - } - - if (!supplierId && user.role === 'proveedor_admin') { - // 2. Si es proveedor_admin, buscar proveedor por email o nombre - const userEmail = (user as any).email || ''; - const userName = user.name || ''; - const supMatch = await query( - 'SELECT id FROM suppliers WHERE email = $1 OR name ILIKE $2 LIMIT 1', - [userEmail, `%${userName}%`] - ); - if (supMatch.rowCount) { - supplierId = supMatch.rows[0].id; - } else { - // Asignar al primer proveedor disponible - const anySup = await query('SELECT id FROM suppliers WHERE is_active = TRUE ORDER BY id ASC LIMIT 1'); - if (anySup.rowCount) { - supplierId = anySup.rows[0].id; - } + if (user.role === 'admin') { + const requested = req.body.supplier_id ? Number(req.body.supplier_id) : null; + if (!requested) { + return res.status(400).json({ error: 'supplier_id es requerido para un administrador' }); } - // Actualizar users table para persistirlo - if (supplierId) { - await query('UPDATE users SET supplier_id = $1 WHERE id = $2', [supplierId, user.id]); - } - } else if (!supplierId && user.role === 'admin') { - // 3. Si es admin, usar el supplier_id enviado o el primero disponible - if (req.body.supplier_id) { - supplierId = Number(req.body.supplier_id); - } else { - const anySup = await query('SELECT id FROM suppliers WHERE is_active = TRUE ORDER BY id ASC LIMIT 1'); - supplierId = anySup.rows[0]?.id || 1; + const supCheck = await query('SELECT 1 FROM suppliers WHERE id = $1', [requested]); + if (!supCheck.rowCount) { + return res.status(400).json({ error: `El supplier_id ${requested} no existe` }); } + supplierId = requested; } if (!supplierId) { - return res.status(400).json({ error: 'No se encontró un proveedor para asociar el producto. Crea o asigna un proveedor primero.' }); + return res.status(403).json({ + error: 'Tu usuario no tiene un proveedor asociado. Contacta al administrador.', + }); } const result = await query( @@ -120,14 +98,22 @@ router.post('/', roleRequired('proveedor_admin', 'admin'), async (req, res, next } }); -router.put('/:id', async (req, res, next) => { +router.put('/:id', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { const user = req.user!; const current = await query('SELECT * FROM products WHERE id = $1', [req.params.id]); if (!current.rowCount) return res.status(404).json({ error: 'Producto no encontrado' }); - if (user.role !== 'admin' && user.supplier_id && current.rows[0].supplier_id !== user.supplier_id) { - return res.status(403).json({ error: 'No autorizado' }); - } + + // Default-deny: solo el proveedor dueño del producto (o un admin) puede + // modificarlo. Antes, si `user.supplier_id` era null (cualquier gerente, + // empleado o domiciliario), la comprobación se saltaba y se podía cambiar + // el precio/stock de productos de CUALQUIER proveedor. + const isOwner = + user.role === 'admin' || + (user.role === 'proveedor_admin' && + Boolean(user.supplier_id) && + Number(current.rows[0].supplier_id) === Number(user.supplier_id)); + if (!isOwner) return res.status(403).json({ error: 'No autorizado' }); const { name, category_id, description, sku, unit, price_per_unit, min_order_qty, stock_available, image_url, is_active } = req.body; const result = await query( @@ -149,14 +135,17 @@ router.put('/:id', async (req, res, next) => { } }); -router.delete('/:id', async (req, res, next) => { +router.delete('/:id', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { const user = req.user!; const current = await query('SELECT * FROM products WHERE id = $1', [req.params.id]); if (!current.rowCount) return res.status(404).json({ error: 'Producto no encontrado' }); - if (user.role !== 'admin' && user.supplier_id && current.rows[0].supplier_id !== user.supplier_id) { - return res.status(403).json({ error: 'No autorizado' }); - } + const isOwner = + user.role === 'admin' || + (user.role === 'proveedor_admin' && + Boolean(user.supplier_id) && + Number(current.rows[0].supplier_id) === Number(user.supplier_id)); + if (!isOwner) return res.status(403).json({ error: 'No autorizado' }); await query('UPDATE products SET is_active = FALSE, updated_at = CURRENT_TIMESTAMP WHERE id = $1', [ req.params.id, ]); diff --git a/src/routes/restaurants.ts b/src/routes/restaurants.ts index 046e8d8..4cbb780 100644 --- a/src/routes/restaurants.ts +++ b/src/routes/restaurants.ts @@ -5,6 +5,10 @@ import { authRequired, roleRequired } from '../middleware/auth'; const router = Router(); router.use(authRequired); +const RESTAURANT_COLUMNS = `id, name, nit, phone, email, address, city, department, logo_url, + description, cover_url, category, subscription_plan, is_active, created_at, updated_at`; +const BRANCH_COLUMNS = 'id, restaurant_id, name, address, phone, is_main, is_active, created_at, updated_at'; + router.get('/', async (req, res, next) => { try { const { category, search } = req.query; @@ -29,8 +33,9 @@ router.get('/', async (req, res, next) => { router.get('/me', async (req, res, next) => { try { const user = req.user!; + if (!user.restaurant_id) return res.status(403).json({ error: 'El usuario no tiene un restaurante asociado' }); const result = await query( - `SELECT r.* FROM restaurants r WHERE r.id = $1`, + `SELECT ${RESTAURANT_COLUMNS} FROM restaurants r WHERE r.id = $1`, [user.restaurant_id] ); if (!result.rowCount) return res.status(404).json({ error: 'Restaurante no encontrado' }); @@ -43,7 +48,7 @@ router.get('/me', async (req, res, next) => { router.get('/:id', async (req, res, next) => { try { if (req.params.id === 'me' || req.params.id === 'branches') return next(); // Let other handlers catch it - const result = await query('SELECT * FROM restaurants WHERE id = $1', [req.params.id]); + const result = await query(`SELECT ${RESTAURANT_COLUMNS} FROM restaurants WHERE id = $1 AND is_active = TRUE`, [req.params.id]); if (!result.rowCount) return res.status(404).json({ error: 'Restaurante no encontrado' }); res.json(result.rows[0]); } catch (err) { @@ -54,6 +59,7 @@ router.get('/:id', async (req, res, next) => { router.put('/me', roleRequired('gerente', 'admin'), async (req, res, next) => { try { const user = req.user!; + if (!user.restaurant_id) return res.status(403).json({ error: 'El usuario no tiene un restaurante asociado' }); const { name, nit, phone, email, address, city, department, logo_url } = req.body; const result = await query( `UPDATE restaurants @@ -62,7 +68,7 @@ router.put('/me', roleRequired('gerente', 'admin'), async (req, res, next) => { city = COALESCE($7, city), department = COALESCE($8, department), logo_url = COALESCE($9, logo_url), updated_at = CURRENT_TIMESTAMP WHERE id = $1 - RETURNING *`, + RETURNING ${RESTAURANT_COLUMNS}`, [user.restaurant_id, name, nit, phone, email, address, city, department, logo_url] ); if (!result.rowCount) return res.status(404).json({ error: 'Restaurante no encontrado' }); @@ -74,9 +80,10 @@ router.put('/me', roleRequired('gerente', 'admin'), async (req, res, next) => { router.get('/:id/branches', async (req, res, next) => { try { - const result = await query('SELECT * FROM branches WHERE restaurant_id = $1 ORDER BY is_main DESC, name', [ - req.params.id, - ]); + const result = await query( + `SELECT ${BRANCH_COLUMNS} FROM branches WHERE restaurant_id = $1 ORDER BY is_main DESC, name`, + [req.params.id] + ); res.json(result.rows); } catch (err) { next(err); @@ -86,10 +93,12 @@ router.get('/:id/branches', async (req, res, next) => { router.post('/branches', roleRequired('gerente', 'admin'), async (req, res, next) => { try { const user = req.user!; + if (!user.restaurant_id) return res.status(403).json({ error: 'El usuario no tiene un restaurante asociado' }); const { name, address, phone, is_main } = req.body; + if (!name) return res.status(400).json({ error: 'name es obligatorio' }); const result = await query( `INSERT INTO branches (restaurant_id, name, address, phone, is_main) - VALUES ($1, $2, $3, $4, $5) RETURNING *`, + VALUES ($1, $2, $3, $4, $5) RETURNING ${BRANCH_COLUMNS}`, [user.restaurant_id, name, address, phone, is_main ?? false] ); res.status(201).json(result.rows[0]); diff --git a/src/routes/reviews.ts b/src/routes/reviews.ts index 0043f93..757ccde 100644 --- a/src/routes/reviews.ts +++ b/src/routes/reviews.ts @@ -10,8 +10,9 @@ router.get('/', async (req, res, next) => { try { const { supplier_id } = req.query; const params: unknown[] = []; - let sql = `SELECT rv.*, s.name AS supplier_name - FROM reseña rv + let sql = `SELECT rv.id, rv.supplier_id, rv.reviewer_name, rv.rating, rv.comment, rv.created_at, + s.name AS supplier_name + FROM "Reseña" rv JOIN suppliers s ON s.id = rv.supplier_id`; if (supplier_id) { params.push(supplier_id); @@ -29,34 +30,51 @@ router.post('/', roleRequired('gerente', 'empleado', 'admin'), async (req, res, try { const user = req.user!; const { supplier_id, rating, comment } = req.body; - if (!supplier_id || !rating || rating < 1 || rating > 5) { - return res.status(400).json({ error: 'supplier_id y rating (1-5) son requeridos' }); + const supplierId = Number(supplier_id); + const ratingNum = Number(rating); + if (!Number.isInteger(supplierId) || supplierId <= 0) { + return res.status(400).json({ error: 'supplier_id es requerido' }); + } + if (!Number.isInteger(ratingNum) || ratingNum < 1 || ratingNum > 5) { + return res.status(400).json({ error: 'rating debe ser un entero entre 1 y 5' }); + } + if (comment !== undefined && comment !== null && String(comment).length > 1000) { + return res.status(400).json({ error: 'El comentario no puede superar 1000 caracteres' }); } if (user.role === 'proveedor_admin') { return res.status(403).json({ error: 'Los proveedores no se califican a sí mismos' }); } + const supplier = await query('SELECT id, name FROM suppliers WHERE id = $1 AND is_active = TRUE', [supplierId]); + if (!supplier.rowCount) return res.status(404).json({ error: 'Proveedor no encontrado' }); + + // Una sola reseña por usuario y proveedor (evita manipular el rating). + const existing = await query( + 'SELECT id FROM "Reseña" WHERE supplier_id = $1 AND created_by = $2 LIMIT 1', + [supplierId, user.id] + ); + if (existing.rowCount) { + return res.status(409).json({ error: 'Ya calificaste a este proveedor. Puedes actualizar tu reseña existente.' }); + } + const userRow = await query('SELECT name FROM users WHERE id = $1', [user.id]); const result = await query( - `INSERT INTO reseña (supplier_id, reviewer_name, rating, comment, created_by) - VALUES ($1, $2, $3, $4, $5) RETURNING *`, - [supplier_id, userRow.rows[0]?.name ?? user.username, rating, comment, user.id] + `INSERT INTO "Reseña" (supplier_id, reviewer_name, rating, comment, created_by) + VALUES ($1, $2, $3, $4, $5) RETURNING id, supplier_id, reviewer_name, rating, comment, created_at`, + [supplierId, userRow.rows[0]?.name ?? user.username, ratingNum, comment ?? null, user.id] ); const agg = await query( `SELECT ROUND(AVG(rating)::numeric, 1) AS rating, COUNT(*)::int AS review_count - FROM reseña WHERE supplier_id = $1`, - [supplier_id] + FROM "Reseña" WHERE supplier_id = $1`, + [supplierId] ); await query('UPDATE suppliers SET rating = $1, review_count = $2 WHERE id = $3', [ agg.rows[0].rating, agg.rows[0].review_count, - supplier_id, + supplierId, ]); - const supplier = await query('SELECT id, name FROM suppliers WHERE id = $1', [supplier_id]); - if (supplier.rowCount) { - const admins = await query('SELECT id FROM users WHERE supplier_id = $1', [supplier_id]); - for (const a of admins.rows) { - emitToUser('notification:created', a.id, { message: `Nueva reseña para ${supplier.rows[0].name}` }); - } + const admins = await query('SELECT id FROM users WHERE supplier_id = $1', [supplierId]); + for (const a of admins.rows) { + emitToUser('notification:created', a.id, { message: `Nueva reseña para ${supplier.rows[0].name}` }); } res.status(201).json(result.rows[0]); } catch (err) { diff --git a/src/routes/suppliers.ts b/src/routes/suppliers.ts index 9329949..d44d541 100644 --- a/src/routes/suppliers.ts +++ b/src/routes/suppliers.ts @@ -1,16 +1,19 @@ import { Router } from 'express'; import { query } from '../config/db'; -import { authRequired } from '../middleware/auth'; +import { authRequired, roleRequired } from '../middleware/auth'; import { emitToUser } from '../lib/realtime'; const router = Router(); router.use(authRequired); +const SUPPLIER_COLUMNS = `id, name, nit, category, phone, email, address, city, logo_url, + description, cover_url, rating, review_count, is_active, created_at, updated_at`; + router.get('/', async (req, res, next) => { try { const { category, search } = req.query; const params: unknown[] = []; - let sql = 'SELECT * FROM suppliers WHERE is_active = TRUE'; + let sql = `SELECT ${SUPPLIER_COLUMNS} FROM suppliers WHERE is_active = TRUE`; if (category) { params.push(category); sql += ` AND category ILIKE $${params.length}`; @@ -30,7 +33,7 @@ router.get('/', async (req, res, next) => { router.get('/me', async (req, res, next) => { try { const user = req.user!; - const result = await query('SELECT * FROM suppliers WHERE id = $1', [user.supplier_id]); + const result = await query(`SELECT ${SUPPLIER_COLUMNS} FROM suppliers WHERE id = $1`, [user.supplier_id]); if (!result.rowCount) return res.status(404).json({ error: 'Proveedor no encontrado' }); res.json(result.rows[0]); } catch (err) { @@ -38,16 +41,19 @@ router.get('/me', async (req, res, next) => { } }); -router.put('/me', async (req, res, next) => { +router.put('/me', roleRequired('proveedor_admin', 'admin'), async (req, res, next) => { try { const user = req.user!; + if (!user.supplier_id) { + return res.status(403).json({ error: 'El usuario no tiene un proveedor asociado' }); + } const { name, nit, category, phone, email, address, city, logo_url } = req.body; const result = await query( `UPDATE suppliers SET name = COALESCE($2, name), nit = COALESCE($3, nit), category = COALESCE($4, category), phone = COALESCE($5, phone), email = COALESCE($6, email), address = COALESCE($7, address), city = COALESCE($8, city), logo_url = COALESCE($9, logo_url), updated_at = CURRENT_TIMESTAMP - WHERE id = $1 RETURNING *`, + WHERE id = $1 RETURNING ${SUPPLIER_COLUMNS}`, [user.supplier_id, name, nit, category, phone, email, address, city, logo_url] ); if (!result.rowCount) return res.status(404).json({ error: 'Proveedor no encontrado' }); @@ -60,7 +66,7 @@ router.put('/me', async (req, res, next) => { router.get('/:id', async (req, res, next) => { try { - const result = await query('SELECT * FROM suppliers WHERE id = $1', [req.params.id]); + const result = await query(`SELECT ${SUPPLIER_COLUMNS} FROM suppliers WHERE id = $1 AND is_active = TRUE`, [req.params.id]); if (!result.rowCount) return res.status(404).json({ error: 'Proveedor no encontrado' }); res.json(result.rows[0]); } catch (err) { diff --git a/src/routes/users.ts b/src/routes/users.ts index 0e06be8..6186054 100644 --- a/src/routes/users.ts +++ b/src/routes/users.ts @@ -7,6 +7,12 @@ import bcrypt from 'bcryptjs'; const router = Router(); router.use(authRequired); +// Asegurar columnas de asignación de vehículo en usuarios +query(` + ALTER TABLE users ADD COLUMN IF NOT EXISTS vehicle_type VARCHAR(50); + ALTER TABLE users ADD COLUMN IF NOT EXISTS vehicle_plate VARCHAR(50); +`).catch(() => undefined); + router.get('/', roleRequired('admin', 'gerente', 'proveedor_admin'), async (req, res, next) => { try { const user = req.user!; diff --git a/src/routes/xupai.ts b/src/routes/xupai.ts index e7f1c15..fcbdf51 100644 --- a/src/routes/xupai.ts +++ b/src/routes/xupai.ts @@ -274,8 +274,10 @@ async function runTool(name: string, rawArgs: any, ctx: { restaurantId: number; // --------------------------------------------------------------------------- // Gate de confirmación (defensa en profundidad del lado del servidor): -// crear_borrador_oc SOLO se ejecuta si el último turno del usuario es una -// confirmación explícita y si antes hubo una propuesta de OC del asistente. +// crear_borrador_oc SOLO se ejecuta si el usuario confirmó explícitamente +// DESPUÉS de que el servidor emitiera una propuesta de OC. El estado vive en +// el servidor: no se confía en el historial enviado por el cliente, que podría +// inyectar un turno falso del asistente para saltarse la confirmación. // --------------------------------------------------------------------------- const CONFIRM_WORDS = new Set([ 'si', 'sip', 'yes', 'yep', 'ok', 'oka', 'oke', 'dale', 'listo', 'claro', @@ -283,38 +285,65 @@ const CONFIRM_WORDS = new Set([ 'genial', 'perfecto', 'bueno', 'va', 'simon', 'obvio', 'ejecuta', ]); +const PROPOSAL_TTL_MS = 10 * 60 * 1000; +const pendingProposals = new Map(); + function normalize(text: string) { return text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, ''); } -function getUserConfirmation(messages: ChatMsg[]): { ok: boolean; reason: string } { +function markProposal(userId: number) { + pendingProposals.set(userId, Date.now()); + if (pendingProposals.size > 5000) { + const now = Date.now(); + for (const [key, ts] of pendingProposals) { + if (now - ts > PROPOSAL_TTL_MS) pendingProposals.delete(key); + } + } +} + +function getUserConfirmation(messages: ChatMsg[], userId: number): { ok: boolean; reason: string } { + const proposedAt = pendingProposals.get(userId); + if (!proposedAt || Date.now() - proposedAt > PROPOSAL_TTL_MS) { + return { + ok: false, + reason: 'No hay una propuesta de Orden de Compra vigente. Primero presenta la sugerencia y termina preguntando "¿Quieres que genere la orden de compra con esto?"', + }; + } + let lastUserIdx = -1; for (let i = messages.length - 1; i >= 0; i--) { if (messages[i].role === 'user') { lastUserIdx = i; break; } } if (lastUserIdx < 0) { - return { ok: false, reason: 'No hay confirmación explícita del usuario. Primero pregunta "¿Quieres que genere la orden de compra con esto?" y espera su respuesta afirmativa.' }; + return { ok: false, reason: 'No hay confirmación explícita del usuario.' }; } const lastUser = normalize(messages[lastUserIdx].content || ''); const firstToken = lastUser.replace(/[.,!?¿¡]+/g, ' ').trim().split(/\s+/)[0]; - const confirmed = CONFIRM_WORDS.has(firstToken); - - if (/\bno\b/.test(lastUser)) { - return { ok: false, reason: 'El usuario respondió de forma negativa o con dudas. No se debe crear la orden de compra.' }; - } - if (!confirmed) { - return { ok: false, reason: 'Falta la confirmación explícita del usuario. Pregunta "¿Quieres que genere la orden de compra con esto?" y espera un sí/ok/dale. NO crees la OC sin esa confirmación.' }; + if (/\bno\b/.test(lastUser) || !CONFIRM_WORDS.has(firstToken)) { + return { ok: false, reason: 'Falta la confirmación explícita del usuario. Espera un sí/ok/dale antes de crear la OC.' }; } + return { ok: true, reason: 'ok' }; +} - let prevAssistant = ''; - for (let i = lastUserIdx - 1; i >= 0; i--) { - if (messages[i].role === 'assistant') { prevAssistant = normalize(messages[i].content || ''); break; } +// Límite de uso del agente para evitar abuso de costos del proveedor LLM. +const agentRate = new Map(); +const AGENT_MAX_REQUESTS = 30; +const AGENT_WINDOW_MS = 10 * 60 * 1000; + +function checkAgentRateLimit(userId: number): { ok: boolean; retryAfter: number } { + const now = Date.now(); + const entry = agentRate.get(userId); + if (!entry || entry.resetAt <= now) { + agentRate.set(userId, { count: 1, resetAt: now + AGENT_WINDOW_MS }); + return { ok: true, retryAfter: 0 }; } - if (!/orden de compra|borrador|generar?e? la|quieres que genere/.test(prevAssistant)) { - return { ok: false, reason: 'No hay una sugerencia de Orden de Compra previa que confirmar. Primero presenta la sugerencia con cifras y termina preguntando si genera la OC.' }; + entry.count += 1; + if (entry.count > AGENT_MAX_REQUESTS) { + return { ok: false, retryAfter: Math.ceil((entry.resetAt - now) / 1000) }; } - return { ok: true, reason: 'ok' }; + return { ok: true, retryAfter: 0 }; } // --------------------------------------------------------------------------- @@ -337,7 +366,16 @@ async function chatCompletions(messages: any[], tools: any[]): Promise { }); if (!res.ok) { const text = await res.text(); - throw new Error(`Proveedor LLM (${XUPAI_MODEL}) respondió ${res.status}: ${text.slice(0, 400)}`); + // El detalle del proveedor se registra solo en el servidor; nunca se + // devuelve al cliente (podría filtrar configuración interna). + console.error(`[XupAI] Proveedor LLM (${XUPAI_MODEL}) respondió ${res.status}: ${text.slice(0, 400)}`); + const error = new Error('No se pudo contactar al proveedor de IA. Intenta nuevamente.') as Error & { + status?: number; + expose?: boolean; + }; + error.status = 502; + error.expose = true; + throw error; } return res.json(); } @@ -359,15 +397,25 @@ router.post('/agent', roleRequired('gerente', 'admin'), async (req, res, next) = return res.status(403).json({ error: 'Esta función es solo para restaurantes.' }); } + const rate = checkAgentRateLimit(req.user!.id); + if (!rate.ok) { + res.setHeader('Retry-After', String(rate.retryAfter)); + return res.status(429).json({ error: 'Has hecho demasiadas consultas a XupAI. Intenta más tarde.' }); + } + const { message, history } = req.body || {}; if (!message || !String(message).trim()) { return res.status(400).json({ error: 'message es requerido' }); } + if (String(message).length > 2000) { + return res.status(400).json({ error: 'message no puede superar 2000 caracteres' }); + } const historyMessages: ChatMsg[] = Array.isArray(history) ? history .filter((m: any) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()) .slice(-24) + .map((m: any) => ({ role: m.role, content: String(m.content).slice(0, 2000) })) : []; const messages: ChatMsg[] = [ @@ -393,22 +441,29 @@ router.post('/agent', roleRequired('gerente', 'admin'), async (req, res, next) = const fnName: string = tc.function?.name || ''; let toolResult: string; if (fnName === 'crear_borrador_oc') { - const gate = getUserConfirmation(messages); + const gate = getUserConfirmation(messages, ctx.userId ?? 0); if (!gate.ok) { toolResult = JSON.stringify({ error: gate.reason }); } else { try { toolResult = await runTool('crear_borrador_oc', tc.function?.arguments, ctx); - try { draft_created = Boolean(JSON.parse(toolResult).ok); } catch {} + try { + if (JSON.parse(toolResult).ok) { + draft_created = true; + pendingProposals.delete(ctx.userId ?? 0); + } + } catch {} } catch (err: any) { - toolResult = JSON.stringify({ error: err.message || 'Error creando la orden' }); + console.error('[XupAI] Error creando borrador de OC:', err); + toolResult = JSON.stringify({ error: 'No se pudo crear la orden de compra. Intenta nuevamente.' }); } } } else { try { toolResult = await runTool(fnName, tc.function?.arguments, ctx); } catch (err: any) { - toolResult = JSON.stringify({ error: err.message || 'Error ejecutando la herramienta' }); + console.error(`[XupAI] Error ejecutando herramienta ${fnName}:`, err); + toolResult = JSON.stringify({ error: 'No se pudo consultar la información solicitada.' }); } } messages.push({ role: 'tool', tool_call_id: tc.id, content: toolResult }); @@ -416,7 +471,13 @@ router.post('/agent', roleRequired('gerente', 'admin'), async (req, res, next) = continue; } - return res.json({ reply: msg.content || '', model: XUPAI_MODEL, mode: 'xupai', draft_created }); + const reply = msg.content || ''; + // Si el asistente propone generar la OC, habilitamos la confirmación + // del lado del servidor durante los próximos 10 minutos. + if (/quieres que genere/i.test(normalize(reply))) { + markProposal(ctx.userId ?? 0); + } + return res.json({ reply, model: XUPAI_MODEL, mode: 'xupai', draft_created }); } return res.status(529).json({ error: 'El agente alcanzó el límite de pasos. Intenta nuevamente.' }); diff --git a/src/server.ts b/src/server.ts index b463e05..0e9ce42 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,9 +1,12 @@ import http from 'http'; import { Server } from 'socket.io'; import dotenv from 'dotenv'; +import jwt from 'jsonwebtoken'; import app from './app'; import { setIo, registerSocket, emitToUser } from './lib/realtime'; import { ensureServerInitialized, expireRadarItems } from './lib/migrations'; +import { query } from './config/db'; +import type { AuthUser } from './middleware/auth'; dotenv.config(); @@ -12,24 +15,88 @@ const server = http.createServer(app); const socketOrigins = (process.env.CLIENT_ORIGIN ?? '') .split(',') .map((origin) => origin.trim()) - .filter(Boolean); + .filter((origin) => Boolean(origin) && origin !== '*'); +const isProduction = process.env.NODE_ENV === 'production' || process.env.VERCEL === '1'; const io = new Server(server, { - // En producción, restringir a la lista blanca de CLIENT_ORIGIN. - cors: { origin: socketOrigins.length === 0 ? true : socketOrigins, credentials: true }, + // En producción, lista blanca estricta (fail-closed). Las apps nativas no + // envían Origin y se permiten; los navegadores deben estar en CLIENT_ORIGIN. + cors: { + origin: ( + origin: string | undefined, + cb: (err: Error | null, allow?: boolean) => void + ) => { + if (!origin) return cb(null, true); + if (socketOrigins.includes(origin)) return cb(null, true); + return cb(null, !isProduction); + }, + credentials: true, + }, }); -io.on('connection', (socket) => { - registerSocket(socket); - const userId = Number(socket.handshake.query.userId); - const role = String(socket.handshake.query.role || ''); - if (Number.isInteger(userId) && userId > 0) { - socket.join(`user:${userId}`); - emitToUser('notification:created', userId, { message: 'Conexión en tiempo real establecida' }); +/** + * Autenticación del handshake de Socket.IO. + * + * Antes cualquier cliente podía conectarse y unirse a las salas que quisiera + * (incluida `admins`) enviando `role=admin` en la query, y por tanto recibir + * pedidos, GPS y auditoría de toda la plataforma. Ahora la identidad SIEMPRE + * sale del JWT y las salas se derivan de esa identidad, nunca del cliente. + */ +io.use(async (socket, next) => { + try { + const rawAuth = (socket.handshake.auth ?? {}) as { token?: unknown }; + const token = + typeof rawAuth.token === 'string' && rawAuth.token + ? rawAuth.token + : String(socket.handshake.query.token ?? ''); + if (!token) return next(new Error('unauthorized')); + const decoded = jwt.verify(token, String(process.env.JWT_SECRET ?? ''), { + algorithms: ['HS256'], + }) as AuthUser; + if (!decoded?.id) return next(new Error('unauthorized')); + + // Igual que authRequired: rol, inquilino y versión del token se leen de la + // base de datos para que una sesión revocada no pueda seguir conectada. + const check = await query( + `SELECT u.username, u.name, u.is_active, u.token_version, + u.role_id, r.name AS role, u.restaurant_id, u.supplier_id, u.branch_id + FROM users u + JOIN roles r ON r.id = u.role_id + WHERE u.id = $1`, + [decoded.id] + ); + const row = check.rows[0]; + if (!check.rowCount || !row.is_active) return next(new Error('unauthorized')); + if (Number(decoded.token_version ?? -1) !== Number(row.token_version)) { + return next(new Error('unauthorized')); + } + + (socket.data as { user?: AuthUser }).user = { + id: Number(decoded.id), + username: row.username, + name: row.name, + role: row.role, + role_id: Number(row.role_id), + restaurant_id: row.restaurant_id === null ? null : Number(row.restaurant_id), + supplier_id: row.supplier_id === null ? null : Number(row.supplier_id), + branch_id: row.branch_id === null ? null : Number(row.branch_id), + token_version: Number(row.token_version), + }; + return next(); + } catch { + return next(new Error('unauthorized')); } - if (role === 'admin') { - socket.join('admins'); - socket.join('role:admin'); +}); + +io.on('connection', (socket) => { + const user = (socket.data as { user?: AuthUser }).user; + if (!user) { + socket.disconnect(true); + return; } + + registerSocket(socket, user); + + emitToUser('notification:created', user.id, { message: 'Conexión en tiempo real establecida' }); }); setIo(io); @@ -44,4 +111,4 @@ if (!process.env.VERCEL) { } export default app; -export { app, server, io }; \ No newline at end of file +export { app, server, io }; diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..fbe2227 --- /dev/null +++ b/vercel.json @@ -0,0 +1,33 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": "express", + "installCommand": "npm ci --no-audit --no-fund", + "buildCommand": "npm run build", + "headers": [ + { + "source": "/(.*)", + "headers": [ + { + "key": "Content-Security-Policy", + "value": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https: wss:; manifest-src 'self'; worker-src 'self' blob:; upgrade-insecure-requests" + }, + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "X-Frame-Options", "value": "DENY" }, + { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }, + { + "key": "Permissions-Policy", + "value": "camera=(), microphone=(), payment=(), usb=(), geolocation=(self)" + }, + { "key": "Cross-Origin-Opener-Policy", "value": "same-origin" }, + { + "key": "Strict-Transport-Security", + "value": "max-age=63072000; includeSubDomains; preload" + } + ] + }, + { + "source": "/api/(.*)", + "headers": [{ "key": "Cache-Control", "value": "no-store" }] + } + ] +}