From 6d2143e1c479b6dc708e128aaf25a2b921af1946 Mon Sep 17 00:00:00 2001 From: urieljareth Date: Wed, 21 Oct 2026 12:01:56 -0600 Subject: [PATCH] Cobros recurrentes: panel de cliente, comprobantes verificados y notificaciones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Panel de cliente con acceso propio (role=cliente): resumen, cotizaciones con descarga PDF y guia de pagos recurrentes con subida de comprobante (imagen->WebP o PDF). - Módulo admin /cobros: programas de pago (semanal/quincenal/mensual), generación idempotente manual y automatica cada hora (scheduler en instrumentation, zona America/Mexico_City), revisión de comprobantes con aprobar/rechazar (el rechazo borra el archivo del servidor y permite re-subir). - Cuentas de cliente creadas/rotadas/revocadas desde la página de clientes. - Notificaciones: servicio SMTP configurable por env (se omite con aviso si no hay credenciales) y Web Push con VAPID + service worker. - Separación de roles en middleware (cliente solo ve /cliente, staff no entra al panel de cliente; PDF y comprobantes son rutas compartidas con validación de pertenencia). - Producción: volumen uploads_data en ambos compose, env vars documentadas en .env.example, migración 20261020000000. --- .env.example | 34 +- .gitignore | 3 + docker-compose.coolify.yml | 18 + docker-compose.yaml | 18 + next.config.ts | 4 +- package-lock.json | 1026 ++++++++++++++--- package.json | 5 + .../migration.sql | 109 ++ prisma/schema.prisma | 98 ++ public/sw.js | 37 + src/app/(app)/clientes/ClientesList.tsx | 174 ++- src/app/(app)/clientes/page.tsx | 2 + src/app/(app)/cobros/CobrosClient.tsx | 277 +++++ src/app/(app)/cobros/EstadoPagoBadge.tsx | 39 + src/app/(app)/cobros/PagosTabla.tsx | 109 ++ src/app/(app)/cobros/ProgramasTabla.tsx | 377 ++++++ src/app/(app)/cobros/page.tsx | 117 ++ src/app/(app)/cobros/types.ts | 45 + src/app/api/auth/login/route.ts | 10 +- .../api/cliente/cotizaciones/[id]/route.ts | 71 ++ src/app/api/cliente/cotizaciones/route.ts | 73 ++ .../cliente/pagos/[id]/comprobante/route.ts | 112 ++ src/app/api/cliente/pagos/route.ts | 36 + src/app/api/cliente/push/config/route.ts | 24 + src/app/api/cliente/push/suscribir/route.ts | 77 ++ src/app/api/cliente/resumen/route.ts | 33 + src/app/api/clientes/[id]/acceso/route.ts | 124 ++ src/app/api/cobros/generar/route.ts | 48 + .../api/cobros/pagos/[id]/aprobar/route.ts | 48 + .../api/cobros/pagos/[id]/rechazar/route.ts | 57 + src/app/api/cobros/pagos/route.ts | 51 + src/app/api/cobros/programas/[id]/route.ts | 77 ++ src/app/api/cobros/programas/route.ts | 85 ++ src/app/api/comprobantes/[pagoId]/route.ts | 75 ++ src/app/api/export/pdf/[id]/route.ts | 13 + src/app/cliente/ClienteShell.tsx | 227 ++++ src/app/cliente/cotizaciones/[id]/page.tsx | 336 ++++++ src/app/cliente/cotizaciones/page.tsx | 154 +++ src/app/cliente/layout.tsx | 34 + src/app/cliente/page.tsx | 197 ++++ src/app/cliente/pagos/SubirComprobante.tsx | 65 ++ src/app/cliente/pagos/page.tsx | 184 +++ src/app/cliente/resumen-data.ts | 118 ++ src/app/login/page.tsx | 5 +- src/components/layout/Sidebar.tsx | 2 + src/instrumentation.ts | 17 + src/lib/auth.ts | 20 + src/lib/cobros-fechas.ts | 137 +++ src/lib/cobros.ts | 57 + src/lib/email.ts | 77 ++ src/lib/notificaciones.ts | 207 ++++ src/lib/push.ts | 85 ++ src/lib/scheduler.ts | 53 + src/lib/schemas.ts | 77 ++ src/lib/uploads.ts | 138 +++ src/middleware.ts | 48 +- 56 files changed, 5587 insertions(+), 157 deletions(-) create mode 100644 prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql create mode 100644 public/sw.js create mode 100644 src/app/(app)/cobros/CobrosClient.tsx create mode 100644 src/app/(app)/cobros/EstadoPagoBadge.tsx create mode 100644 src/app/(app)/cobros/PagosTabla.tsx create mode 100644 src/app/(app)/cobros/ProgramasTabla.tsx create mode 100644 src/app/(app)/cobros/page.tsx create mode 100644 src/app/(app)/cobros/types.ts create mode 100644 src/app/api/cliente/cotizaciones/[id]/route.ts create mode 100644 src/app/api/cliente/cotizaciones/route.ts create mode 100644 src/app/api/cliente/pagos/[id]/comprobante/route.ts create mode 100644 src/app/api/cliente/pagos/route.ts create mode 100644 src/app/api/cliente/push/config/route.ts create mode 100644 src/app/api/cliente/push/suscribir/route.ts create mode 100644 src/app/api/cliente/resumen/route.ts create mode 100644 src/app/api/clientes/[id]/acceso/route.ts create mode 100644 src/app/api/cobros/generar/route.ts create mode 100644 src/app/api/cobros/pagos/[id]/aprobar/route.ts create mode 100644 src/app/api/cobros/pagos/[id]/rechazar/route.ts create mode 100644 src/app/api/cobros/pagos/route.ts create mode 100644 src/app/api/cobros/programas/[id]/route.ts create mode 100644 src/app/api/cobros/programas/route.ts create mode 100644 src/app/api/comprobantes/[pagoId]/route.ts create mode 100644 src/app/cliente/ClienteShell.tsx create mode 100644 src/app/cliente/cotizaciones/[id]/page.tsx create mode 100644 src/app/cliente/cotizaciones/page.tsx create mode 100644 src/app/cliente/layout.tsx create mode 100644 src/app/cliente/page.tsx create mode 100644 src/app/cliente/pagos/SubirComprobante.tsx create mode 100644 src/app/cliente/pagos/page.tsx create mode 100644 src/app/cliente/resumen-data.ts create mode 100644 src/instrumentation.ts create mode 100644 src/lib/cobros-fechas.ts create mode 100644 src/lib/cobros.ts create mode 100644 src/lib/email.ts create mode 100644 src/lib/notificaciones.ts create mode 100644 src/lib/push.ts create mode 100644 src/lib/scheduler.ts create mode 100644 src/lib/uploads.ts diff --git a/.env.example b/.env.example index ba086b5..d584a61 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,7 @@ -# Cotizador E3 — variables de entorno -# Copia este archivo a .env (local) o configúralas en Coolify (producción). +# Cotizador E3 — variables de entorno +# Copia este archivo a .env (local) o configúralas en Coolify (producción). -# ── Base de datos (compartida por Next.js y el API Python) ── +# ── Base de datos (compartida por Next.js y el API Python) ── DB_HOST=localhost DB_PORT=5432 DB_USER=postgres @@ -9,17 +9,17 @@ DB_PASSWORD=postgres DB_NAME=cotizador_e3 # Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines, -# se construye automáticamente desde las DB_* (ver prisma.config.ts). +# se construye automáticamente desde las DB_* (ver prisma.config.ts). DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3" -# ── Auth ── +# ── Auth ── # OBLIGATORIA. Genera una con: openssl rand -base64 32 JWT_SECRET= -# ── API Python (api/) — clave para agentes de IA / n8n ── +# ── API Python (api/) — clave para agentes de IA / n8n ── API_KEY= -# ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ── +# ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ── RUN_SEED=false SEED_ADMIN_EMAIL=admin@e3.local SEED_ADMIN_PASSWORD= @@ -36,3 +36,23 @@ SEED_ASESOR_NAME= MINIMAX_API_KEY= MINIMAX_BASE_URL=https://api.minimax.io/anthropic MINIMAX_MODEL=MiniMax-M3 + +# --- Notificaciones (panel de cliente) --- +# Web Push. Genera el par con: node -e "require('web-push').generateVAPIDKeys()|console.log" +# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log). +VAPID_PUBLIC_KEY= +VAPID_PRIVATE_KEY= +# URL publica (links de correo y notificaciones). En Coolify: el dominio del servicio web. +NEXT_PUBLIC_APP_URL=http://localhost:3000 + +# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log) +SMTP_HOST= +SMTP_PORT=587 +SMTP_USER= +SMTP_PASS= +SMTP_FROM= +SMTP_FROM_NAME=Cotizador E3 + +# Directorio de comprobantes. Local: vacio = /uploads. +# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml). +UPLOAD_DIR= \ No newline at end of file diff --git a/.gitignore b/.gitignore index 4c72762..64c9ad9 100644 --- a/.gitignore +++ b/.gitignore @@ -60,3 +60,6 @@ next-env.d.ts # claude local settings .claude/settings.local.json + +# Comprobantes de pago subidos por los clientes (nunca se commitean) +uploads/ diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.yml index d5adc4a..e62ee22 100644 --- a/docker-compose.coolify.yml +++ b/docker-compose.coolify.yml @@ -55,6 +55,23 @@ services: - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME} + # URL publica: la usan los links de correo y de las notificaciones push. + - NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL} + # Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())" + # La app funciona sin ellas: las notificaciones se omiten con aviso en log. + - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY} + - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY} + # SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log. + - SMTP_HOST=${SMTP_HOST} + - SMTP_PORT=${SMTP_PORT:-587} + - SMTP_USER=${SMTP_USER} + - SMTP_PASS=${SMTP_PASS} + - SMTP_FROM=${SMTP_FROM} + - SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3} + # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. + - UPLOAD_DIR=/app/uploads + volumes: + - uploads_data:/app/uploads depends_on: postgres: condition: service_healthy @@ -94,3 +111,4 @@ services: volumes: postgres_data: + uploads_data: diff --git a/docker-compose.yaml b/docker-compose.yaml index d5adc4a..e62ee22 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -55,6 +55,23 @@ services: - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME} + # URL publica: la usan los links de correo y de las notificaciones push. + - NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL} + # Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())" + # La app funciona sin ellas: las notificaciones se omiten con aviso en log. + - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY} + - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY} + # SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log. + - SMTP_HOST=${SMTP_HOST} + - SMTP_PORT=${SMTP_PORT:-587} + - SMTP_USER=${SMTP_USER} + - SMTP_PASS=${SMTP_PASS} + - SMTP_FROM=${SMTP_FROM} + - SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3} + # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. + - UPLOAD_DIR=/app/uploads + volumes: + - uploads_data:/app/uploads depends_on: postgres: condition: service_healthy @@ -94,3 +111,4 @@ services: volumes: postgres_data: + uploads_data: diff --git a/next.config.ts b/next.config.ts index c366877..bda8d0e 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,7 +1,9 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { - serverExternalPackages: ["pdfkit"], + // sharp/nodemailer/web-push traen binarios o crypto nativo: empaquetarlos + // rompe el build de produccion. + serverExternalPackages: ["pdfkit", "sharp", "nodemailer", "web-push"], poweredByHeader: false, }; diff --git a/package-lock.json b/package-lock.json index 86c1d12..4b410bf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,11 +18,14 @@ "jose": "^6.2.3", "lucide-react": "^1.11.0", "next": "16.2.4", + "nodemailer": "^10.1.7", "pdfkit": "^0.18.0", "pg": "^8.20.0", "prisma": "^7.8.0", "react": "19.2.4", "react-dom": "19.2.4", + "sharp": "^0.35.5", + "web-push": "^3.6.7", "zod": "^4.3.6", "zustand": "^5.0.12" }, @@ -30,9 +33,11 @@ "@tailwindcss/postcss": "^4", "@types/bcryptjs": "^2.4.6", "@types/node": "^20", + "@types/nodemailer": "^8.0.2", "@types/pdfkit": "^0.17.6", "@types/react": "^19", "@types/react-dom": "^19", + "@types/web-push": "^3.6.4", "eslint": "^9", "eslint-config-next": "16.2.4", "tailwindcss": "^4", @@ -363,9 +368,9 @@ } }, "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "license": "MIT", "optional": true, "dependencies": { @@ -1093,15 +1098,14 @@ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", "license": "MIT", - "optional": true, "engines": { "node": ">=18" } }, "node_modules/@img/sharp-darwin-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", - "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], @@ -1111,19 +1115,19 @@ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.2.4" + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, "node_modules/@img/sharp-darwin-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", - "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], @@ -1133,19 +1137,38 @@ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.2.4" + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", - "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], @@ -1159,9 +1182,9 @@ } }, "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", - "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], @@ -1175,9 +1198,9 @@ } }, "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", - "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], @@ -1194,9 +1217,9 @@ } }, "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", - "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], @@ -1213,9 +1236,9 @@ } }, "node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", - "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", "cpu": [ "ppc64" ], @@ -1232,9 +1255,9 @@ } }, "node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", - "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ "riscv64" ], @@ -1251,9 +1274,9 @@ } }, "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", - "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], @@ -1270,9 +1293,9 @@ } }, "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", - "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], @@ -1289,9 +1312,9 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", - "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], @@ -1308,9 +1331,9 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", - "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], @@ -1327,9 +1350,9 @@ } }, "node_modules/@img/sharp-linux-arm": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", - "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], @@ -1342,19 +1365,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.2.4" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, "node_modules/@img/sharp-linux-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", - "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], @@ -1367,19 +1390,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.2.4" + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, "node_modules/@img/sharp-linux-ppc64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", - "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", "cpu": [ "ppc64" ], @@ -1392,19 +1415,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-ppc64": "1.2.4" + "@img/sharp-libvips-linux-ppc64": "1.3.4" } }, "node_modules/@img/sharp-linux-riscv64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", - "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", "cpu": [ "riscv64" ], @@ -1417,19 +1440,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.2.4" + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, "node_modules/@img/sharp-linux-s390x": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", - "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], @@ -1442,19 +1465,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.2.4" + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, "node_modules/@img/sharp-linux-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", - "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], @@ -1467,19 +1490,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.2.4" + "@img/sharp-libvips-linux-x64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", - "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], @@ -1492,19 +1515,19 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", - "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], @@ -1517,38 +1540,54 @@ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, "node_modules/@img/sharp-wasm32": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", - "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", - "cpu": [ - "wasm32" - ], + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.7.0" + "@emnapi/runtime": "^1.11.3" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-win32-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", - "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", "cpu": [ "arm64" ], @@ -1558,16 +1597,16 @@ "win32" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-win32-ia32": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", - "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ "ia32" ], @@ -1577,16 +1616,16 @@ "win32" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": "^20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" } }, "node_modules/@img/sharp-win32-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", - "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "cpu": [ "x64" ], @@ -1596,7 +1635,7 @@ "win32" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" @@ -2617,6 +2656,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/pdfkit": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.6.tgz", @@ -2657,6 +2706,16 @@ "@types/react": "^19.2.0" } }, + "node_modules/@types/web-push": { + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz", + "integrity": "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.59.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.0.tgz", @@ -3268,6 +3327,15 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/ajv": { "version": "6.15.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", @@ -3553,6 +3621,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, "node_modules/ast-types-flow": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", @@ -3713,6 +3793,12 @@ "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", "license": "MIT" }, + "node_modules/bn.js": { + "version": "4.12.5", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz", + "integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "1.1.14", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", @@ -3821,6 +3907,12 @@ "node": "*" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/buffer-indexof-polyfill": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", @@ -4202,7 +4294,6 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -4293,7 +4384,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "devOptional": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -4390,6 +4480,15 @@ "safe-buffer": "~5.1.0" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/effect": { "version": "3.20.0", "resolved": "https://registry.npmjs.org/effect/-/effect-3.20.0.tgz", @@ -5775,12 +5874,34 @@ "node": ">=16.9.0" } }, + "node_modules/http_ece": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", + "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/http-status-codes": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/http-status-codes/-/http-status-codes-2.3.0.tgz", "integrity": "sha512-RJ8XvFvpPM/Dmc5SV+dC4y5PCeOhT3x1Hq0NU3rjGeg5a/CqlhZ7uudknPwZFz4aeAXDcbAyaeP7GAo9lvngtA==", "license": "MIT" }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/iconv-lite": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", @@ -6512,6 +6633,27 @@ "safe-buffer": "~5.1.0" } }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", @@ -7110,6 +7252,12 @@ "node": ">=8.6" } }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -7147,7 +7295,6 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, "license": "MIT" }, "node_modules/mysql2": { @@ -7276,6 +7423,510 @@ } } }, + "node_modules/next/node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/next/node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/next/node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/next/node_modules/postcss": { "version": "8.4.31", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", @@ -7304,6 +7955,64 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/next/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/next/node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, "node_modules/node-exports-info": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz", @@ -7330,6 +8039,15 @@ "dev": true, "license": "MIT" }, + "node_modules/nodemailer": { + "version": "10.1.7", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.7.tgz", + "integrity": "sha512-OQa6FDln5fLttmqSbjDiRYvFDOFNrBqfiOwHPlEbURil3b+vPB1v8xpi+Sp46drzNDlsTnNsS502vthmz56r4w==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -8411,56 +9129,59 @@ "license": "MIT" }, "node_modules/sharp": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", - "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", - "hasInstallScript": true, + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", "license": "Apache-2.0", - "optional": true, "dependencies": { - "@img/colour": "^1.0.0", + "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", - "semver": "^7.7.3" + "semver": "^7.8.5" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.34.5", - "@img/sharp-darwin-x64": "0.34.5", - "@img/sharp-libvips-darwin-arm64": "1.2.4", - "@img/sharp-libvips-darwin-x64": "1.2.4", - "@img/sharp-libvips-linux-arm": "1.2.4", - "@img/sharp-libvips-linux-arm64": "1.2.4", - "@img/sharp-libvips-linux-ppc64": "1.2.4", - "@img/sharp-libvips-linux-riscv64": "1.2.4", - "@img/sharp-libvips-linux-s390x": "1.2.4", - "@img/sharp-libvips-linux-x64": "1.2.4", - "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", - "@img/sharp-libvips-linuxmusl-x64": "1.2.4", - "@img/sharp-linux-arm": "0.34.5", - "@img/sharp-linux-arm64": "0.34.5", - "@img/sharp-linux-ppc64": "0.34.5", - "@img/sharp-linux-riscv64": "0.34.5", - "@img/sharp-linux-s390x": "0.34.5", - "@img/sharp-linux-x64": "0.34.5", - "@img/sharp-linuxmusl-arm64": "0.34.5", - "@img/sharp-linuxmusl-x64": "0.34.5", - "@img/sharp-wasm32": "0.34.5", - "@img/sharp-win32-arm64": "0.34.5", - "@img/sharp-win32-ia32": "0.34.5", - "@img/sharp-win32-x64": "0.34.5" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, "node_modules/sharp/node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", "license": "ISC", - "optional": true, "bin": { "semver": "bin/semver.js" }, @@ -9367,6 +10088,25 @@ } } }, + "node_modules/web-push": { + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", + "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "license": "MPL-2.0", + "dependencies": { + "asn1.js": "^5.3.0", + "http_ece": "1.2.0", + "https-proxy-agent": "^7.0.0", + "jws": "^4.0.0", + "minimist": "^1.2.5" + }, + "bin": { + "web-push": "src/cli.js" + }, + "engines": { + "node": ">= 16" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index 64f5830..94b5002 100644 --- a/package.json +++ b/package.json @@ -26,11 +26,14 @@ "jose": "^6.2.3", "lucide-react": "^1.11.0", "next": "16.2.4", + "nodemailer": "^10.1.7", "pdfkit": "^0.18.0", "pg": "^8.20.0", "prisma": "^7.8.0", "react": "19.2.4", "react-dom": "19.2.4", + "sharp": "^0.35.5", + "web-push": "^3.6.7", "zod": "^4.3.6", "zustand": "^5.0.12" }, @@ -38,9 +41,11 @@ "@tailwindcss/postcss": "^4", "@types/bcryptjs": "^2.4.6", "@types/node": "^20", + "@types/nodemailer": "^8.0.2", "@types/pdfkit": "^0.17.6", "@types/react": "^19", "@types/react-dom": "^19", + "@types/web-push": "^3.6.4", "eslint": "^9", "eslint-config-next": "16.2.4", "tailwindcss": "^4", diff --git a/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql b/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql new file mode 100644 index 0000000..c545a47 --- /dev/null +++ b/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql @@ -0,0 +1,109 @@ +-- AlterTable +ALTER TABLE "User" ADD COLUMN "clienteId" TEXT; + +-- CreateTable +CREATE TABLE "ProgramaPago" ( + "id" TEXT NOT NULL, + "clienteId" TEXT NOT NULL, + "cotizacionId" TEXT, + "concepto" TEXT NOT NULL, + "monto" DOUBLE PRECISION NOT NULL, + "moneda" TEXT NOT NULL DEFAULT 'MXN', + "frecuencia" TEXT NOT NULL DEFAULT 'semanal', + "diaSemana" INTEGER, + "diaMes" INTEGER, + "fechaInicio" TIMESTAMP(3) NOT NULL, + "fechaFin" TIMESTAMP(3), + "activo" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "PagoRecurrente" ( + "id" TEXT NOT NULL, + "programaId" TEXT NOT NULL, + "fecha" TIMESTAMP(3) NOT NULL, + "monto" DOUBLE PRECISION NOT NULL, + "estado" TEXT NOT NULL DEFAULT 'pendiente', + "verificadoAt" TIMESTAMP(3), + "rechazadoAt" TIMESTAMP(3), + "rechazoMotivo" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "ComprobantePago" ( + "id" TEXT NOT NULL, + "pagoId" TEXT NOT NULL, + "archivoRuta" TEXT NOT NULL, + "archivoNombre" TEXT NOT NULL, + "mime" TEXT NOT NULL, + "tamano" INTEGER NOT NULL, + "subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SuscripcionPush" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "endpoint" TEXT NOT NULL, + "p256dh" TEXT NOT NULL, + "auth" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId"); + +-- CreateIndex +CREATE INDEX "ProgramaPago_activo_idx" ON "ProgramaPago"("activo"); + +-- CreateIndex +CREATE INDEX "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado"); + +-- CreateIndex +CREATE INDEX "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha"); + +-- CreateIndex +CREATE UNIQUE INDEX "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha"); + +-- CreateIndex +CREATE UNIQUE INDEX "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId"); + +-- CreateIndex +CREATE UNIQUE INDEX "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint"); + +-- CreateIndex +CREATE INDEX "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "User_clienteId_key" ON "User"("clienteId"); + +-- AddForeignKey +ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index e71e46b..8b8ca48 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -12,11 +12,16 @@ model User { email String @unique password String name String + // "admin" | "asesor" | "cliente". Un usuario con role="cliente" DEBE tener + // clienteId: su sesion da acceso unicamente al panel /cliente de ese Cliente. role String @default("asesor") + clienteId String? @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt cotizaciones Cotizacion[] @relation("AsesorCotizaciones") + cliente Cliente? @relation("ClienteUsuario", fields: [clienteId], references: [id]) + suscripcionesPush SuscripcionPush[] } model Cliente { @@ -30,6 +35,9 @@ model Cliente { updatedAt DateTime @updatedAt cotizaciones Cotizacion[] + // Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente. + usuario User? @relation("ClienteUsuario") + programasPago ProgramaPago[] @@index([nombre, empresa]) } @@ -67,6 +75,7 @@ model Cotizacion { planBucefalo PlanBucefaloCotizacion? registrosHoras RegistroHoras[] propuestasIA PropuestaIA[] + programasPago ProgramaPago[] @@index([clienteId]) @@index([asesorId]) @@ -271,3 +280,92 @@ model FinanciamientoPlan { montoMinimo Float iva Float @default(0.16) } + +// Programa de cobros recurrentes configurado por el administrador. +// Ejemplo real: Instituto Santiago Tapia — cada sabado se genera un cobro de $750 +// por la administracion web. La generacion es idempotente: un PagoRecurrente por +// (programaId, fecha), calculado desde fechaInicio con la cadencia. +model ProgramaPago { + id String @id @default(cuid()) + clienteId String + // Vinculo opcional con la cotizacion que origina el servicio recurrente. + cotizacionId String? + concepto String + monto Float + moneda String @default("MXN") + // "semanal" | "quincenal" | "mensual" + frecuencia String @default("semanal") + // Dia de la semana 0=domingo..6=sabado (requerido si frecuencia=semanal). + diaSemana Int? + // Dia del mes 1..31 (requerido si frecuencia=mensual; quincenal usa dia 1 y 15). + diaMes Int? + fechaInicio DateTime + fechaFin DateTime? + activo Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + cliente Cliente @relation(fields: [clienteId], references: [id], onDelete: Cascade) + cotizacion Cotizacion? @relation(fields: [cotizacionId], references: [id], onDelete: SetNull) + pagos PagoRecurrente[] + + @@index([clienteId]) + @@index([activo]) +} + +// Un cobro generado para un periodo concreto (ej. sabado 2026-07-04). +// estados: pendiente (sin comprobante) | en_revision (comprobante subido, +// esperando admin) | verificado (admin aprobo) | rechazado (admin rechazo y +// borro el archivo; el cliente puede volver a subir). +model PagoRecurrente { + id String @id @default(cuid()) + programaId String + // Fecha del periodo (medianoche America/Mexico_City al momento de generar). + fecha DateTime + monto Float + estado String @default("pendiente") + // Fecha en que el admin valido el comprobante (estado=verificado). + verificadoAt DateTime? + rechazadoAt DateTime? + rechazoMotivo String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + programa ProgramaPago @relation(fields: [programaId], references: [id], onDelete: Cascade) + comprobante ComprobantePago? + + @@unique([programaId, fecha]) + @@index([estado]) + @@index([fecha]) +} + +// Comprobante de pago subido por el cliente (imagen o PDF). El archivo vive en +// UPLOAD_DIR/comprobantes/ y se sirve solo por un route handler autenticado +// (nunca desde /public). Al rechazar, el admin borra el archivo del servidor +// y se elimina este registro; el cliente vuelve a "pendiente". +model ComprobantePago { + id String @id @default(cuid()) + pagoId String @unique + archivoRuta String // relativa a UPLOAD_DIR, ej. "comprobantes//.webp" + archivoNombre String // nombre original que vio el cliente + mime String // image/webp | application/pdf + tamano Int // bytes finales en disco + subidoAt DateTime @default(now()) + + pago PagoRecurrente @relation(fields: [pagoId], references: [id], onDelete: Cascade) +} + +// Suscripcion Web Push del navegador del cliente (endpoint VAPID + claves p256dh/auth). +model SuscripcionPush { + id String @id @default(cuid()) + userId String + endpoint String @unique + p256dh String + auth String + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + usuario User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([userId]) +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..e585f3a --- /dev/null +++ b/public/sw.js @@ -0,0 +1,37 @@ +// Service worker del panel de cliente: solo notificaciones push. +// Sin estrategias de cache — el panel siempre va a red. + +self.addEventListener("push", (event) => { + let data = {}; + try { + data = event.data ? event.data.json() : {}; + } catch { + data = {}; + } + const titulo = (data && data.titulo) || "Cotizador E3"; + const cuerpo = (data && data.cuerpo) || ""; + const url = (data && data.url) || "/cliente/pagos"; + event.waitUntil( + self.registration.showNotification(titulo, { + body: cuerpo, + icon: "/favicon.ico", + data: { url }, + }) + ); +}); + +self.addEventListener("notificationclick", (event) => { + const data = event.notification.data || {}; + const url = data.url || "/cliente/pagos"; + event.notification.close(); + event.waitUntil( + self.clients + .matchAll({ type: "window", includeUncontrolled: true }) + .then((cs) => { + const existing = cs.find((c) => "focus" in c); + return existing + ? existing.navigate(url).then(() => existing.focus()) + : self.clients.openWindow(url); + }) + ); +}); diff --git a/src/app/(app)/clientes/ClientesList.tsx b/src/app/(app)/clientes/ClientesList.tsx index aab868a..585f852 100644 --- a/src/app/(app)/clientes/ClientesList.tsx +++ b/src/app/(app)/clientes/ClientesList.tsx @@ -1,7 +1,9 @@ "use client"; import { useMemo, useState } from "react"; -import { Search } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { KeyRound, Search, Trash2 } from "lucide-react"; +import { useConfirm, useToast } from "@/components/ui/DialogProvider"; import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton"; interface Cliente { @@ -11,10 +13,23 @@ interface Cliente { email: string | null; telefono: string | null; _count: { cotizaciones: number }; + usuario: { id: string; email: string } | null; } +type DialogoAcceso = { + cliente: Cliente; + modo: "crear" | "rotar"; + email: string; + password: string; +} | null; + export function ClientesList({ clientes }: { clientes: Cliente[] }) { const [search, setSearch] = useState(""); + const [dialogo, setDialogo] = useState(null); + const [guardando, setGuardando] = useState(false); + const router = useRouter(); + const showConfirm = useConfirm(); + const toast = useToast(); const filtered = useMemo(() => { if (!search) return clientes; @@ -27,6 +42,73 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) { ); }, [clientes, search]); + const abrirDialogo = (cliente: Cliente, modo: "crear" | "rotar") => { + setDialogo({ + cliente, + modo, + email: modo === "rotar" ? cliente.usuario?.email || "" : "", + password: "", + }); + }; + + const guardarAcceso = async () => { + if (!dialogo) return; + const email = dialogo.email.trim(); + const password = dialogo.password; + if (!email) { + toast("El email es requerido", "error"); + return; + } + if (password.length < 6) { + toast("La contrasena debe tener al menos 6 caracteres", "error"); + return; + } + setGuardando(true); + try { + const res = await fetch(`/api/clientes/${dialogo.cliente.id}/acceso`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password }), + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al guardar acceso", "error"); + return; + } + toast(dialogo.modo === "crear" ? "Acceso creado" : "Acceso actualizado", "success"); + setDialogo(null); + router.refresh(); + } catch { + toast("Error de conexion", "error"); + } finally { + setGuardando(false); + } + }; + + const revocarAcceso = async (cliente: Cliente) => { + const ok = await showConfirm({ + title: "Revocar acceso", + message: `Eliminar la cuenta de panel de ${cliente.nombre}? El cliente dejara de poder iniciar sesion.`, + confirmText: "Revocar", + danger: true, + }); + if (!ok) return; + try { + const res = await fetch(`/api/clientes/${cliente.id}/acceso`, { + method: "DELETE", + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al revocar acceso", "error"); + return; + } + toast("Acceso revocado", "success"); + router.refresh(); + } catch { + toast("Error de conexion", "error"); + } + }; + return ( <>
@@ -66,6 +148,9 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) { Cotizaciones + + Acceso panel + @@ -84,6 +169,34 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) { {c._count.cotizaciones} + + {c.usuario ? ( +
+ {c.usuario.email} + + +
+ ) : ( + + )} +
)} + + {dialogo && ( +
setDialogo(null)} + > +
e.stopPropagation()} + > +
+ {dialogo.modo === "crear" + ? `Crear acceso para ${dialogo.cliente.nombre}` + : `Rotar acceso de ${dialogo.cliente.nombre}`} +
+
+
+ + + setDialogo((d) => (d ? { ...d, email: e.target.value } : d)) + } + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + placeholder="cliente@empresa.com" + /> +
+
+ + + setDialogo((d) => (d ? { ...d, password: e.target.value } : d)) + } + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + placeholder="Minimo 6 caracteres" + /> +
+
+
+ + +
+
+
+ )} ); } diff --git a/src/app/(app)/clientes/page.tsx b/src/app/(app)/clientes/page.tsx index 8a00b0f..85f4d42 100644 --- a/src/app/(app)/clientes/page.tsx +++ b/src/app/(app)/clientes/page.tsx @@ -12,6 +12,7 @@ export default async function ClientesPage() { email: true, telefono: true, _count: { select: { cotizaciones: true } }, + usuario: { select: { id: true, email: true } }, }, }); @@ -52,6 +53,7 @@ function ClientesListWrapper({ email: string | null; telefono: string | null; _count: { cotizaciones: number }; + usuario: { id: string; email: string } | null; }[]; }) { return ; diff --git a/src/app/(app)/cobros/CobrosClient.tsx b/src/app/(app)/cobros/CobrosClient.tsx new file mode 100644 index 0000000..6ac9159 --- /dev/null +++ b/src/app/(app)/cobros/CobrosClient.tsx @@ -0,0 +1,277 @@ +"use client"; + +import { useState, useEffect, useCallback, useRef } from "react"; +import { useRouter } from "next/navigation"; +import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider"; +import { formatFechaCorta } from "@/lib/cobros-fechas"; +import { ProgramasTabla } from "./ProgramasTabla"; +import { PagosTabla } from "./PagosTabla"; +import type { ProgramaRow, ClienteOpt, PagoRow } from "./types"; + +// Frecuencia legible en la tabla de programas. +export function frecuenciaLegible(p: { + frecuencia: string; + diaSemana?: number | null; + diaMes?: number | null; +}): string { + const dias = [ + "domingo", + "lunes", + "martes", + "miercoles", + "jueves", + "viernes", + "sabado", + ]; + if (p.frecuencia === "semanal") { + const d = p.diaSemana ?? 0; + return `Cada ${dias[d]}`; + } + if (p.frecuencia === "quincenal") return "Cada 1 y 15"; + return `Cada dia ${p.diaMes ?? 1}`; +} + +export function CobrosClient({ + programas, + clientes, + pagosIniciales, +}: { + programas: ProgramaRow[]; + clientes: ClienteOpt[]; + pagosIniciales: PagoRow[]; +}) { + const router = useRouter(); + const showConfirm = useConfirm(); + const showPrompt = usePrompt(); + const toast = useToast(); + + // El servidor ya dejo cargado el filtro por defecto (en_revision); el effect + // solo vuelve a consultar cuando el usuario cambia un filtro. + const cargadoInicial = useRef(false); + const [pagos, setPagos] = useState(pagosIniciales); + const [cargandoPagos, setCargandoPagos] = useState(false); + const [estadoFiltro, setEstadoFiltro] = useState("en_revision"); + const [clienteFiltro, setClienteFiltro] = useState(""); + const [desdeFiltro, setDesdeFiltro] = useState(""); + const [hastaFiltro, setHastaFiltro] = useState(""); + + const cargarPagos = useCallback(async () => { + setCargandoPagos(true); + try { + const params = new URLSearchParams(); + if (estadoFiltro) params.set("estado", estadoFiltro); + if (clienteFiltro) params.set("clienteId", clienteFiltro); + if (desdeFiltro) params.set("desde", desdeFiltro); + if (hastaFiltro) params.set("hasta", hastaFiltro); + const res = await fetch(`/api/cobros/pagos?${params.toString()}`); + if (res.ok) { + const data = await res.json(); + setPagos(Array.isArray(data) ? data : []); + } + } catch { + // silencioso: la tabla queda vacia + } finally { + setCargandoPagos(false); + } + }, [estadoFiltro, clienteFiltro, desdeFiltro, hastaFiltro]); + + useEffect(() => { + // Evita el render-inicial: el servidor ya dejo los pagos del filtro por + // defecto. Solo se consulta cuando cambia un filtro. + if (!cargadoInicial.current) { + cargadoInicial.current = true; + return; + } + cargarPagos(); + }, [cargarPagos]); + + const generarAhora = async () => { + const ok = await showConfirm({ + title: "Generar cobros", + message: + "Se generaran los cobros pendientes de todos los programas activos hasta hoy. Continuar?", + confirmText: "Generar", + }); + if (!ok) return; + try { + const res = await fetch("/api/cobros/generar", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({}), + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al generar cobros", "error"); + return; + } + const n = data.generados ?? 0; + toast( + n > 0 ? `Se generaron ${n} cobros` : "No habia cobros pendientes", + "success" + ); + cargarPagos(); + router.refresh(); + } catch { + toast("Error de conexion", "error"); + } + }; + + const toggleActivo = async (p: ProgramaRow) => { + const activar = !p.activo; + const ok = await showConfirm({ + title: activar ? "Activar programa" : "Desactivar programa", + message: activar + ? `Activar el programa "${p.concepto}"? Se generaran cobros en sus proximos periodos.` + : `Desactivar el programa "${p.concepto}"? No se generaran mas cobros, pero los existentes se conservan.`, + confirmText: activar ? "Activar" : "Desactivar", + danger: !activar, + }); + if (!ok) return; + try { + const res = await fetch(`/api/cobros/programas/${p.id}`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ activo: activar }), + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al actualizar", "error"); + return; + } + toast(activar ? "Programa activado" : "Programa desactivado", "success"); + router.refresh(); + } catch { + toast("Error de conexion", "error"); + } + }; + + const aprobar = async (pago: PagoRow) => { + const ok = await showConfirm({ + title: "Aprobar comprobante", + message: `Marcar el cobro del ${formatFechaCorta(new Date(pago.fecha))} como verificado?`, + confirmText: "Aprobar", + }); + if (!ok) return; + try { + const res = await fetch(`/api/cobros/pagos/${pago.id}/aprobar`, { + method: "POST", + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al aprobar", "error"); + return; + } + toast("Cobro verificado", "success"); + cargarPagos(); + } catch { + toast("Error de conexion", "error"); + } + }; + + const rechazar = async (pago: PagoRow) => { + const motivo = await showPrompt({ + title: "Rechazar comprobante", + label: "Motivo del rechazo (opcional)", + placeholder: "Ej. ilegible, monto incorrecto...", + confirmText: "Rechazar", + }); + if (motivo === null) return; // cancelado + try { + const res = await fetch(`/api/cobros/pagos/${pago.id}/rechazar`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ motivo: motivo.trim() }), + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al rechazar", "error"); + return; + } + toast("Comprobante rechazado", "success"); + cargarPagos(); + } catch { + toast("Error de conexion", "error"); + } + }; + + return ( +
+
+ +
+ +
+
+

Cobros generados

+ +
+ +
+
+ + +
+
+ + +
+
+ + setDesdeFiltro(e.target.value)} + className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg" + /> +
+
+ + setHastaFiltro(e.target.value)} + className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg" + /> +
+
+ + +
+
+ ); +} diff --git a/src/app/(app)/cobros/EstadoPagoBadge.tsx b/src/app/(app)/cobros/EstadoPagoBadge.tsx new file mode 100644 index 0000000..d7fafb4 --- /dev/null +++ b/src/app/(app)/cobros/EstadoPagoBadge.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { ESTADOS_PAGO } from "@/lib/cobros-fechas"; + +// Badges de estado de cobro (colores locales, no reutiliza EstadoBadge que es +// para cotizaciones). pendiente=amber, en_revision=azul, verificado=verde, +// rechazado=rojizo. +const ESTILOS: Record = { + [ESTADOS_PAGO.PENDIENTE]: { + cls: "bg-amber-100 text-amber-800", + label: "Pendiente", + }, + [ESTADOS_PAGO.EN_REVISION]: { + cls: "bg-blue-100 text-blue-800", + label: "En revision", + }, + [ESTADOS_PAGO.VERIFICADO]: { + cls: "bg-green-100 text-green-800", + label: "Verificado", + }, + [ESTADOS_PAGO.RECHAZADO]: { + cls: "bg-red-100 text-red-800", + label: "Rechazado", + }, +}; + +export function EstadoPagoBadge({ estado }: { estado: string }) { + const s = ESTILOS[estado] ?? { + cls: "bg-gray-100 text-gray-700", + label: estado, + }; + return ( + + {s.label} + + ); +} diff --git a/src/app/(app)/cobros/PagosTabla.tsx b/src/app/(app)/cobros/PagosTabla.tsx new file mode 100644 index 0000000..eb43eea --- /dev/null +++ b/src/app/(app)/cobros/PagosTabla.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { Check, X, FileText } from "lucide-react"; +import { formatCurrency } from "@/lib/calculators"; +import { formatFechaCorta } from "@/lib/cobros-fechas"; +import { EstadoPagoBadge } from "./EstadoPagoBadge"; +import type { PagoRow } from "./types"; + +export function PagosTabla({ + pagos, + cargando, + onAprobar, + onRechazar, +}: { + pagos: PagoRow[]; + cargando: boolean; + onAprobar: (p: PagoRow) => void; + onRechazar: (p: PagoRow) => void; +}) { + if (cargando) { + return ( +
+

Cargando cobros...

+
+ ); + } + + if (pagos.length === 0) { + return ( +
+

No hay cobros

+

+ Genera cobros con el boton o ajusta los filtros +

+
+ ); + } + + return ( +
+ + + + + + + + + + + + + + {pagos.map((p) => ( + + + + + + + + + + ))} + +
FechaConceptoClienteMontoEstadoComprobanteAcciones
{formatFechaCorta(new Date(p.fecha))}{p.programa.concepto}{p.programa.cliente.nombre}{formatCurrency(p.monto)} + + {p.estado === "rechazado" && p.rechazoMotivo && ( +
{p.rechazoMotivo}
+ )} +
+ {p.comprobante ? ( + + + Ver + + ) : ( + — + )} + + {p.estado === "en_revision" ? ( +
+ + +
+ ) : ( + — + )} +
+
+ ); +} diff --git a/src/app/(app)/cobros/ProgramasTabla.tsx b/src/app/(app)/cobros/ProgramasTabla.tsx new file mode 100644 index 0000000..25e124a --- /dev/null +++ b/src/app/(app)/cobros/ProgramasTabla.tsx @@ -0,0 +1,377 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { Pencil, Power, Plus } from "lucide-react"; +import { useToast } from "@/components/ui/DialogProvider"; +import { formatCurrency } from "@/lib/calculators"; +import { formatFechaCorta } from "@/lib/cobros-fechas"; +import type { ProgramaRow, ClienteOpt } from "./types"; + +const DIAS = [ + "Domingo", + "Lunes", + "Martes", + "Miercoles", + "Jueves", + "Viernes", + "Sabado", +]; + +function frecuenciaTexto(p: { + frecuencia: string; + diaSemana?: number | null; + diaMes?: number | null; +}): string { + if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`; + if (p.frecuencia === "quincenal") return "Cada 1 y 15"; + return `Cada dia ${p.diaMes ?? 1}`; +} + +function EstadoProgramaBadge({ activo }: { activo: boolean }) { + return ( + + {activo ? "Activo" : "Inactivo"} + + ); +} + +type FormEstado = { + concepto: string; + monto: string; + frecuencia: string; + diaSemana: string; + diaMes: string; + fechaInicio: string; + fechaFin: string; +}; + +type DialogoState = null | "nuevo" | ProgramaRow; + +const FORM_VACIO: FormEstado = { + concepto: "", + monto: "", + frecuencia: "mensual", + diaSemana: "1", + diaMes: "1", + fechaInicio: "", + fechaFin: "", +}; + +export function ProgramasTabla({ + programas, + clientes, + onToggleActivo, +}: { + programas: ProgramaRow[]; + clientes: ClienteOpt[]; + onToggleActivo: (p: ProgramaRow) => void; +}) { + const router = useRouter(); + const toast = useToast(); + const [dialogo, setDialogo] = useState(null); + const [clienteId, setClienteId] = useState(""); + const [form, setForm] = useState(FORM_VACIO); + const [guardando, setGuardando] = useState(false); + + const abrirNuevo = () => { + setClienteId(clientes[0]?.id ?? ""); + setForm(FORM_VACIO); + setDialogo("nuevo"); + }; + + const abrirEditar = (p: ProgramaRow) => { + setClienteId(p.cliente.id); + setForm({ + concepto: p.concepto, + monto: String(p.monto), + frecuencia: p.frecuencia, + diaSemana: String(p.diaSemana ?? 0), + diaMes: String(p.diaMes ?? 1), + fechaInicio: p.fechaInicio.slice(0, 10), + fechaFin: p.fechaFin ? p.fechaFin.slice(0, 10) : "", + }); + setDialogo(p); + }; + + const set = (k: keyof FormEstado, v: string) => + setForm((f) => ({ ...f, [k]: v })); + + const guardar = async () => { + if (!form.concepto.trim()) { + toast("El concepto es requerido", "error"); + return; + } + const monto = parseFloat(form.monto); + if (!form.monto || isNaN(monto) || monto <= 0) { + toast("El monto debe ser mayor a 0", "error"); + return; + } + if (!form.fechaInicio) { + toast("La fecha de inicio es requerida", "error"); + return; + } + if (dialogo === "nuevo" && !clienteId) { + toast("Selecciona un cliente", "error"); + return; + } + + const payload: Record = { + concepto: form.concepto.trim(), + monto, + frecuencia: form.frecuencia, + fechaInicio: form.fechaInicio, + }; + if (form.frecuencia === "semanal") payload.diaSemana = parseInt(form.diaSemana, 10); + if (form.frecuencia === "mensual") payload.diaMes = parseInt(form.diaMes, 10); + if (form.fechaFin) payload.fechaFin = form.fechaFin; + + setGuardando(true); + try { + // El handler solo es invocado desde el dialogo abierto (dialogo != null). + const actual = dialogo as NonNullable; + const esNuevo = actual === "nuevo"; + const url = esNuevo + ? "/api/cobros/programas" + : `/api/cobros/programas/${actual.id}`; + const method = esNuevo ? "POST" : "PATCH"; + const body = esNuevo ? { ...payload, clienteId } : payload; + const res = await fetch(url, { + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + const data = await res.json(); + if (!res.ok) { + toast(data.error || "Error al guardar", "error"); + return; + } + toast(esNuevo ? "Programa creado" : "Programa actualizado", "success"); + setDialogo(null); + router.refresh(); + } catch { + toast("Error de conexion", "error"); + } finally { + setGuardando(false); + } + }; + + return ( + <> +
+

Programas de pago

+ +
+ + {programas.length === 0 ? ( +
+

No hay programas de pago

+

+ Crea un programa para empezar a generar cobros recurrentes +

+
+ ) : ( +
+ + + + + + + + + + + + + + {programas.map((p) => ( + + + + + + + + + + ))} + +
ConceptoClienteMontoFrecuenciaProximo cobroEstadoAcciones
{p.concepto} +
{p.cliente.nombre}
+ {p.cliente.empresa && ( +
{p.cliente.empresa}
+ )} +
{formatCurrency(p.monto)}{frecuenciaTexto(p)} + {p.proximaFecha + ? formatFechaCorta(new Date(p.proximaFecha)) + : "—"} + + + +
+ + +
+
+
+ )} + + {dialogo && ( +
setDialogo(null)} + > +
e.stopPropagation()} + > +
+ {dialogo === "nuevo" ? "Nuevo programa" : "Editar programa"} +
+
+ {dialogo === "nuevo" && ( +
+ + +
+ )} +
+ + set("concepto", e.target.value)} + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + placeholder="Ej. Gestion de publicidad" + /> +
+
+ + set("monto", e.target.value)} + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + /> +
+
+ + +
+ {form.frecuencia === "semanal" && ( +
+ + +
+ )} + {form.frecuencia === "mensual" && ( +
+ + set("diaMes", e.target.value)} + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + /> +
+ )} +
+ + set("fechaInicio", e.target.value)} + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + /> +
+
+ + set("fechaFin", e.target.value)} + className="w-full px-3 py-2 border border-border rounded-lg text-sm" + /> +
+
+
+ + +
+
+
+ )} + + ); +} diff --git a/src/app/(app)/cobros/page.tsx b/src/app/(app)/cobros/page.tsx new file mode 100644 index 0000000..1b62912 --- /dev/null +++ b/src/app/(app)/cobros/page.tsx @@ -0,0 +1,117 @@ +import { prisma } from "@/lib/db"; +import { proximaFecha } from "@/lib/cobros"; +import { CobrosClient } from "./CobrosClient"; + +export const dynamic = "force-dynamic"; + +// Serializa los datos de la BD a formas planas (fechas -> ISO) para que el +// componente cliente no dependa de tipos Prisma ni de Date no-serializable. +type ProgramaConCliente = { + id: string; + concepto: string; + monto: number; + moneda: string; + frecuencia: string; + diaSemana: number | null; + diaMes: number | null; + activo: boolean; + fechaInicio: Date; + fechaFin: Date | null; + cliente: { id: string; nombre: string; empresa: string | null }; + _count: { pagos: number }; +}; + +export default async function CobrosPage() { + const [programas, clientes, pagosIniciales] = await Promise.all([ + prisma.programaPago.findMany({ + orderBy: [{ activo: "desc" }, { createdAt: "desc" }], + include: { + cliente: { select: { id: true, nombre: true, empresa: true } }, + _count: { select: { pagos: true } }, + }, + }), + prisma.cliente.findMany({ + orderBy: { nombre: "asc" }, + select: { id: true, nombre: true, empresa: true }, + }), + // Cobros en revision (filtro por defecto de la tabla) para render inicial. + prisma.pagoRecurrente.findMany({ + where: { estado: "en_revision" }, + orderBy: { fecha: "desc" }, + include: { + programa: { + select: { + concepto: true, + moneda: true, + cliente: { select: { id: true, nombre: true, empresa: true } }, + }, + }, + comprobante: true, + }, + }), + ]); + + const programasData = (programas as ProgramaConCliente[]).map((p) => { + const prox = proximaFecha(p); + return { + id: p.id, + concepto: p.concepto, + monto: p.monto, + moneda: p.moneda, + frecuencia: p.frecuencia, + diaSemana: p.diaSemana, + diaMes: p.diaMes, + activo: p.activo, + fechaInicio: p.fechaInicio.toISOString(), + fechaFin: p.fechaFin ? p.fechaFin.toISOString() : null, + cliente: p.cliente, + pagosCount: p._count.pagos, + proximaFecha: prox ? prox.toISOString() : null, + }; + }); + + const clientesData = clientes.map((c) => ({ + id: c.id, + nombre: c.nombre, + empresa: c.empresa, + })); + + const pagosData = pagosIniciales.map((p) => ({ + id: p.id, + fecha: p.fecha.toISOString(), + monto: p.monto, + estado: p.estado, + rechazoMotivo: p.rechazoMotivo, + programa: { + concepto: p.programa.concepto, + moneda: p.programa.moneda, + cliente: p.programa.cliente, + }, + comprobante: p.comprobante + ? { + id: p.comprobante.id, + archivoNombre: p.comprobante.archivoNombre, + mime: p.comprobante.mime, + tamano: p.comprobante.tamano, + subidoAt: p.comprobante.subidoAt.toISOString(), + } + : null, + })); + + return ( +
+
+

Cobros recurrentes

+

+ Programa cobros periodicos y revisa los comprobantes de tus clientes +

+
+ + +
+ ); +} diff --git a/src/app/(app)/cobros/types.ts b/src/app/(app)/cobros/types.ts new file mode 100644 index 0000000..b5a8fc7 --- /dev/null +++ b/src/app/(app)/cobros/types.ts @@ -0,0 +1,45 @@ +// Tipos serializados que consume el cliente de la pagina /cobros. + +export type ClienteOpt = { + id: string; + nombre: string; + empresa: string | null; +}; + +export type ProgramaRow = { + id: string; + concepto: string; + monto: number; + moneda: string; + frecuencia: string; + diaSemana: number | null; + diaMes: number | null; + activo: boolean; + fechaInicio: string; + fechaFin: string | null; + cliente: ClienteOpt; + pagosCount: number; + proximaFecha: string | null; +}; + +export type ComprobanteMeta = { + id: string; + archivoNombre: string; + mime: string; + tamano: number; + subidoAt: string; +}; + +export type PagoRow = { + id: string; + fecha: string; + monto: number; + estado: string; + rechazoMotivo: string | null; + programa: { + concepto: string; + moneda: string; + cliente: { id: string; nombre: string; empresa: string | null }; + }; + comprobante: ComprobanteMeta | null; +}; diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 9ea37dd..6c33496 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -38,10 +38,18 @@ export async function POST(request: NextRequest) { email: user.email, name: user.name, role: user.role, + // Requerido para que el panel cliente pueda acotar sus consultas. + ...(user.role === "cliente" && user.clienteId ? { clienteId: user.clienteId } : {}), }); const response = NextResponse.json({ - user: { id: user.id, name: user.name, email: user.email, role: user.role }, + user: { + id: user.id, + name: user.name, + email: user.email, + role: user.role, + clienteId: user.clienteId ?? null, + }, }); response.cookies.set(setSessionCookie(token)); return response; diff --git a/src/app/api/cliente/cotizaciones/[id]/route.ts b/src/app/api/cliente/cotizaciones/[id]/route.ts new file mode 100644 index 0000000..7e46c0d --- /dev/null +++ b/src/app/api/cliente/cotizaciones/[id]/route.ts @@ -0,0 +1,71 @@ +import { NextRequest, NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators"; + +// GET /api/cliente/cotizaciones/[id] — detalle completo de una cotizacion +// propia (servicios, planBucefalo, doble propuesta, cliente). +export async function GET( + _request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + if (!session.clienteId) { + return NextResponse.json( + { error: "La sesion no tiene un cliente asociado" }, + { status: 400 } + ); + } + + const { id } = await params; + + const cot = await prisma.cotizacion.findFirst({ + where: { id, clienteId: session.clienteId }, + include: { + cliente: { select: { nombre: true, empresa: true, email: true } }, + servicios: { + orderBy: [{ fase: "asc" }, { createdAt: "asc" }], + select: { + id: true, + nombre: true, + esPersonalizado: true, + opcion: true, + fase: true, + tipoPago: true, + precio: true, + modeloCobro: true, + horas: true, + tarifaHora: true, + tiempoEntrega: true, + notas: true, + }, + }, + planBucefalo: true, + }, + }); + + if (!cot) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + + return NextResponse.json({ + ...cot, + totales: calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva }), + ...(cot.esDoble + ? { + totalesOpciones: { + "1": calcularTotalesOpcion(cot.servicios, "1"), + "2": calcularTotalesOpcion(cot.servicios, "2"), + }, + } + : {}), + }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/cotizaciones/route.ts b/src/app/api/cliente/cotizaciones/route.ts new file mode 100644 index 0000000..e7acb06 --- /dev/null +++ b/src/app/api/cliente/cotizaciones/route.ts @@ -0,0 +1,73 @@ +import { NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators"; + +// GET /api/cliente/cotizaciones — lista de cotizaciones del cliente con +// servicios y totales (por opcion si es doble propuesta). +export async function GET() { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + if (!session.clienteId) { + return NextResponse.json( + { error: "La sesion no tiene un cliente asociado" }, + { status: 400 } + ); + } + + const cotizaciones = await prisma.cotizacion.findMany({ + where: { clienteId: session.clienteId }, + orderBy: { fecha: "desc" }, + include: { + servicios: { + select: { + id: true, + nombre: true, + esPersonalizado: true, + opcion: true, + fase: true, + tipoPago: true, + precio: true, + modeloCobro: true, + horas: true, + tarifaHora: true, + }, + }, + planBucefalo: { + select: { nivel: true, precio: true, seleccionado: true }, + }, + }, + }); + + const salida = cotizaciones.map((c) => ({ + id: c.id, + numero: c.numero, + proyecto: c.proyecto, + fecha: c.fecha, + vigencia: c.vigencia, + estado: c.estado, + moneda: c.moneda, + esDoble: c.esDoble, + incluirIva: c.incluirIva, + servicios: c.servicios, + planBucefalo: c.planBucefalo, + totales: calcularTotalesCotizacion(c.servicios, { incluirIva: c.incluirIva }), + ...(c.esDoble + ? { + totalesOpciones: { + "1": calcularTotalesOpcion(c.servicios, "1"), + "2": calcularTotalesOpcion(c.servicios, "2"), + }, + } + : {}), + })); + + return NextResponse.json(salida); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/pagos/[id]/comprobante/route.ts b/src/app/api/cliente/pagos/[id]/comprobante/route.ts new file mode 100644 index 0000000..9e82dbd --- /dev/null +++ b/src/app/api/cliente/pagos/[id]/comprobante/route.ts @@ -0,0 +1,112 @@ +import { NextRequest, NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { ESTADOS_PAGO } from "@/lib/cobros"; +import { ErrorUpload, eliminarComprobante, guardarComprobante } from "@/lib/uploads"; + +// POST /api/cliente/pagos/[id]/comprobante — el cliente sube su comprobante +// (imagen o PDF) para un cobro pendiente o rechazado. El pago pasa a +// "en_revision". Las notificaciones al admin NO se disparan aqui (las hace +// el frente que implementa verificacion/rechazo). +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + if (!session.clienteId) { + return NextResponse.json( + { error: "La sesion no tiene un cliente asociado" }, + { status: 400 } + ); + } + + const { id } = await params; + + const pago = await prisma.pagoRecurrente.findUnique({ + where: { id }, + include: { + programa: { select: { clienteId: true } }, + comprobante: true, + }, + }); + if (!pago || pago.programa.clienteId !== session.clienteId) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + + if (pago.estado === ESTADOS_PAGO.EN_REVISION) { + return NextResponse.json( + { error: "Ya enviaste un comprobante; espera la revisión." }, + { status: 409 } + ); + } + if (pago.estado === ESTADOS_PAGO.VERIFICADO) { + return NextResponse.json( + { error: "Este cobro ya fue verificado." }, + { status: 409 } + ); + } + + const formData = await request.formData(); + const file = formData.get("file"); + if (!(file instanceof File) || file.size === 0) { + return NextResponse.json( + { error: "Debes seleccionar un archivo." }, + { status: 400 } + ); + } + + // Comprobante residual (p.ej. un rechazo cuyo registro no se limpio): + // borrar archivo del disco y registro antes de guardar el nuevo. + if (pago.comprobante) { + await eliminarComprobante(pago.comprobante.archivoRuta); + await prisma.comprobantePago + .delete({ where: { pagoId: pago.id } }) + .catch(() => {}); + } + + let guardado; + try { + guardado = await guardarComprobante(pago.id, file); + } catch (e) { + if (e instanceof ErrorUpload) { + return NextResponse.json({ error: e.message }, { status: 400 }); + } + throw e; + } + + const [, actualizado] = await prisma.$transaction([ + prisma.comprobantePago.create({ + data: { + pagoId: pago.id, + archivoRuta: guardado.ruta, + archivoNombre: guardado.nombreOriginal, + mime: guardado.mime, + tamano: guardado.tamano, + }, + }), + prisma.pagoRecurrente.update({ + where: { id: pago.id }, + data: { + estado: ESTADOS_PAGO.EN_REVISION, + rechazadoAt: null, + rechazoMotivo: null, + }, + include: { + programa: { + select: { concepto: true, frecuencia: true, monto: true, moneda: true }, + }, + comprobante: true, + }, + }), + ]); + + return NextResponse.json(actualizado); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/pagos/route.ts b/src/app/api/cliente/pagos/route.ts new file mode 100644 index 0000000..0312c12 --- /dev/null +++ b/src/app/api/cliente/pagos/route.ts @@ -0,0 +1,36 @@ +import { NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; + +// GET /api/cliente/pagos — todos los cobros recurrentes del cliente +// (fecha descendente) con los datos del programa y la metadata del comprobante. +export async function GET() { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + if (!session.clienteId) { + return NextResponse.json( + { error: "La sesion no tiene un cliente asociado" }, + { status: 400 } + ); + } + + const pagos = await prisma.pagoRecurrente.findMany({ + where: { programa: { clienteId: session.clienteId } }, + orderBy: { fecha: "desc" }, + include: { + programa: { + select: { concepto: true, frecuencia: true, monto: true, moneda: true }, + }, + comprobante: true, + }, + }); + + return NextResponse.json(pagos); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/push/config/route.ts b/src/app/api/cliente/push/config/route.ts new file mode 100644 index 0000000..f1cdeba --- /dev/null +++ b/src/app/api/cliente/push/config/route.ts @@ -0,0 +1,24 @@ +import { NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { llavePublicaPush } from "@/lib/push"; + +// GET /api/cliente/push/config — llave VAPID publica para suscribir el +// navegador. 501 si el servidor no tiene las claves configuradas. +export async function GET() { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + + const publicKey = llavePublicaPush(); + if (!publicKey) { + return NextResponse.json({ error: "No configurado" }, { status: 501 }); + } + + return NextResponse.json({ publicKey }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/push/suscribir/route.ts b/src/app/api/cliente/push/suscribir/route.ts new file mode 100644 index 0000000..003fd01 --- /dev/null +++ b/src/app/api/cliente/push/suscribir/route.ts @@ -0,0 +1,77 @@ +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; + +// El endpoint del navegador es unico a nivel global (indice @unique); el +// upsert lo re-registra al usuario actual por si cambio de cuenta. +const suscripcionSchema = z.object({ + endpoint: z.string().min(1), + p256dh: z.string().min(1), + auth: z.string().min(1), +}); + +const endpointSchema = z.object({ + endpoint: z.string().min(1), +}); + +// POST /api/cliente/push/suscribir — guarda (o refresca) la suscripcion Web +// Push del navegador del cliente. +export async function POST(request: NextRequest) { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + + const body = await request.json(); + const parsed = suscripcionSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + + const { endpoint, p256dh, auth } = parsed.data; + const sub = await prisma.suscripcionPush.upsert({ + where: { endpoint }, + create: { userId: session.userId, endpoint, p256dh, auth }, + update: { userId: session.userId, p256dh, auth }, + }); + + return NextResponse.json({ id: sub.id, endpoint: sub.endpoint }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} + +// DELETE /api/cliente/push/suscribir — elimina la suscripcion del usuario +// actual (solo la suya; nunca toca las de otros usuarios). +export async function DELETE(request: NextRequest) { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + + const body = await request.json(); + const parsed = endpointSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + + const resultado = await prisma.suscripcionPush.deleteMany({ + where: { userId: session.userId, endpoint: parsed.data.endpoint }, + }); + + return NextResponse.json({ ok: true, eliminadas: resultado.count }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cliente/resumen/route.ts b/src/app/api/cliente/resumen/route.ts new file mode 100644 index 0000000..59c16c3 --- /dev/null +++ b/src/app/api/cliente/resumen/route.ts @@ -0,0 +1,33 @@ +import { NextResponse } from "next/server"; +import { requireRole } from "@/lib/auth"; +import { obtenerResumenCliente } from "@/app/cliente/resumen-data"; + +// GET /api/cliente/resumen — tarjetas y proximos cobros del panel de cliente. +export async function GET() { + try { + const session = await requireRole("cliente"); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 401 }); + } + if (!session.clienteId) { + return NextResponse.json( + { error: "La sesion no tiene un cliente asociado" }, + { status: 400 } + ); + } + + const resumen = await obtenerResumenCliente(session.clienteId); + if (!resumen) { + return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }); + } + + return NextResponse.json({ + cliente: resumen.cliente, + cotizaciones: resumen.cotizaciones, + pagos: resumen.pagos, + }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/clientes/[id]/acceso/route.ts b/src/app/api/clientes/[id]/acceso/route.ts new file mode 100644 index 0000000..1eaa4e1 --- /dev/null +++ b/src/app/api/clientes/[id]/acceso/route.ts @@ -0,0 +1,124 @@ +import { NextRequest, NextResponse } from "next/server"; +import { hash } from "bcryptjs"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { accesoClienteSchema } from "@/lib/schemas"; + +// POST /api/clientes/[id]/acceso — crea o rota la cuenta de panel del cliente. +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { id } = await params; + const body = await request.json(); + const parsed = accesoClienteSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + const { email, password } = parsed.data; + + const cliente = await prisma.cliente.findUnique({ + where: { id }, + include: { usuario: true }, + }); + if (!cliente) { + return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }); + } + + const passwordHash = await hash(password, 10); + + // ¿El email pertenece a OTRO usuario (no vinculado a este cliente)? + const otro = await prisma.user.findFirst({ + where: { email, NOT: { clienteId: id } }, + }); + if (otro) { + return NextResponse.json( + { error: "Ese email ya esta en uso por otro usuario" }, + { status: 409 } + ); + } + + if (cliente.usuario) { + // Rotar acceso: actualiza email+password del usuario vinculado. + const actualizado = await prisma.user.update({ + where: { id: cliente.usuario.id }, + data: { email, password: passwordHash }, + }); + return NextResponse.json({ + id: actualizado.id, + email: actualizado.email, + name: actualizado.name, + role: actualizado.role, + }); + } + + const nuevo = await prisma.user.create({ + data: { + email, + password: passwordHash, + name: cliente.nombre, + role: "cliente", + clienteId: id, + }, + }); + + return NextResponse.json( + { + id: nuevo.id, + email: nuevo.email, + name: nuevo.name, + role: nuevo.role, + }, + { status: 201 } + ); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} + +// DELETE /api/clientes/[id]/acceso — elimina la cuenta de panel (cascada limpia +// suscripciones push). +export async function DELETE( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { id } = await params; + + const cliente = await prisma.cliente.findUnique({ + where: { id }, + include: { usuario: true }, + }); + if (!cliente) { + return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }); + } + if (!cliente.usuario) { + return NextResponse.json( + { error: "Este cliente no tiene acceso de panel" }, + { status: 404 } + ); + } + + await prisma.user.delete({ where: { id: cliente.usuario.id } }); + + return NextResponse.json({ ok: true }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/generar/route.ts b/src/app/api/cobros/generar/route.ts new file mode 100644 index 0000000..bbb24fd --- /dev/null +++ b/src/app/api/cobros/generar/route.ts @@ -0,0 +1,48 @@ +import { NextRequest, NextResponse } from "next/server"; +import { z } from "zod"; +import { requireStaff } from "@/lib/auth"; +import { generarCobros, parseFechaCalendario } from "@/lib/cobros"; +import { notificarCobrosNuevos } from "@/lib/notificaciones"; + +const generarSchema = z.object({ + programaId: z.string().optional(), + hasta: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, "Fecha invalida (se espera YYYY-MM-DD)") + .optional(), +}); + +// POST /api/cobros/generar — genera los cobros vencidos (idempotente) y +// notifica por correo+push a los clientes afectados. +export async function POST(request: NextRequest) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const raw = await request.json().catch(() => ({})); + const parsed = generarSchema.safeParse(raw ?? {}); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + const { programaId, hasta } = parsed.data; + + const creados = await generarCobros({ + programaId, + hasta: hasta ? parseFechaCalendario(hasta) : undefined, + }); + + if (creados.length) { + await notificarCobrosNuevos(creados); + } + + return NextResponse.json({ generados: creados.length }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/pagos/[id]/aprobar/route.ts b/src/app/api/cobros/pagos/[id]/aprobar/route.ts new file mode 100644 index 0000000..1c523a2 --- /dev/null +++ b/src/app/api/cobros/pagos/[id]/aprobar/route.ts @@ -0,0 +1,48 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { ESTADOS_PAGO } from "@/lib/cobros"; +import { notificarVerificacion } from "@/lib/notificaciones"; + +// POST /api/cobros/pagos/[id]/aprobar — valida un comprobante en revision. +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { id } = await params; + + const pago = await prisma.pagoRecurrente.findUnique({ where: { id } }); + if (!pago) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + if (pago.estado !== ESTADOS_PAGO.EN_REVISION) { + return NextResponse.json( + { error: "Solo se pueden aprobar cobros en revision" }, + { status: 409 } + ); + } + + const actualizado = await prisma.pagoRecurrente.update({ + where: { id }, + data: { + estado: ESTADOS_PAGO.VERIFICADO, + verificadoAt: new Date(), + rechazadoAt: null, + rechazoMotivo: null, + }, + }); + + await notificarVerificacion(id); + + return NextResponse.json(actualizado); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/pagos/[id]/rechazar/route.ts b/src/app/api/cobros/pagos/[id]/rechazar/route.ts new file mode 100644 index 0000000..7f8ff35 --- /dev/null +++ b/src/app/api/cobros/pagos/[id]/rechazar/route.ts @@ -0,0 +1,57 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { ESTADOS_PAGO } from "@/lib/cobros"; +import { eliminarComprobante } from "@/lib/uploads"; +import { notificarRechazo } from "@/lib/notificaciones"; + +// POST /api/cobros/pagos/[id]/rechazar — rechaza el comprobante, borra el +// archivo del disco y el registro, y notifica al cliente. +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { id } = await params; + const raw = await request.json().catch(() => ({})); + const motivo: string | null = + typeof raw?.motivo === "string" && raw.motivo.trim() + ? raw.motivo.trim() + : null; + + const pago = await prisma.pagoRecurrente.findUnique({ + where: { id }, + include: { comprobante: true }, + }); + if (!pago) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + + if (pago.comprobante) { + await eliminarComprobante(pago.comprobante.archivoRuta); + await prisma.comprobantePago.delete({ where: { pagoId: id } }); + } + + const actualizado = await prisma.pagoRecurrente.update({ + where: { id }, + data: { + estado: ESTADOS_PAGO.RECHAZADO, + rechazadoAt: new Date(), + rechazoMotivo: motivo, + verificadoAt: null, + }, + }); + + await notificarRechazo(id, motivo || ""); + + return NextResponse.json(actualizado); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/pagos/route.ts b/src/app/api/cobros/pagos/route.ts new file mode 100644 index 0000000..4942c0f --- /dev/null +++ b/src/app/api/cobros/pagos/route.ts @@ -0,0 +1,51 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { parseFechaCalendario } from "@/lib/cobros"; + +// GET /api/cobros/pagos?estado=&programaId=&desde=&hasta= +// Pagos ordenados por fecha desc con programa+cliente y comprobante. +export async function GET(request: NextRequest) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { searchParams } = new URL(request.url); + const estado = searchParams.get("estado"); + const programaId = searchParams.get("programaId"); + const desde = searchParams.get("desde"); + const hasta = searchParams.get("hasta"); + + const where: Record = {}; + if (estado) where.estado = estado; + if (programaId) where.programaId = programaId; + if (desde || hasta) { + where.fecha = { + ...(desde ? { gte: parseFechaCalendario(desde) } : {}), + ...(hasta ? { lte: parseFechaCalendario(hasta) } : {}), + }; + } + + const pagos = await prisma.pagoRecurrente.findMany({ + where, + orderBy: { fecha: "desc" }, + include: { + programa: { + select: { + concepto: true, + moneda: true, + cliente: { select: { id: true, nombre: true, empresa: true } }, + }, + }, + comprobante: true, + }, + }); + + return NextResponse.json(pagos); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/programas/[id]/route.ts b/src/app/api/cobros/programas/[id]/route.ts new file mode 100644 index 0000000..e9855e2 --- /dev/null +++ b/src/app/api/cobros/programas/[id]/route.ts @@ -0,0 +1,77 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { programaPagoPatchSchema } from "@/lib/schemas"; +import { parseFechaCalendario } from "@/lib/cobros"; + +// PATCH /api/cobros/programas/[id] — actualiza campos editables (incluido +// `activo`). No existe DELETE: se desactiva con { activo: false }. +export async function PATCH( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const { id } = await params; + + const previo = await prisma.programaPago.findUnique({ where: { id } }); + if (!previo) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + + const body = await request.json(); + const parsed = programaPagoPatchSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + const data = parsed.data; + + // Combinar con lo previo para normalizar diaSemana/diaMes segun la + // frecuencia resultante (quincenal no usa dia; semanal limpia diaMes, etc.). + const frecuencia = data.frecuencia ?? previo.frecuencia; + let diaSemana = data.diaSemana ?? previo.diaSemana; + let diaMes = data.diaMes ?? previo.diaMes; + if (frecuencia === "quincenal") { + diaSemana = null; + diaMes = null; + } else if (frecuencia === "semanal") { + diaMes = null; + } else if (frecuencia === "mensual") { + diaSemana = null; + } + + const actualizado = await prisma.programaPago.update({ + where: { id }, + data: { + ...(data.concepto !== undefined ? { concepto: data.concepto } : {}), + ...(data.monto !== undefined ? { monto: data.monto } : {}), + ...(data.frecuencia !== undefined ? { frecuencia: data.frecuencia } : {}), + diaSemana, + diaMes, + ...(data.fechaInicio !== undefined + ? { fechaInicio: parseFechaCalendario(data.fechaInicio) } + : {}), + ...(data.fechaFin !== undefined + ? { + fechaFin: data.fechaFin + ? parseFechaCalendario(data.fechaFin) + : null, + } + : {}), + ...(data.activo !== undefined ? { activo: data.activo } : {}), + }, + }); + + return NextResponse.json(actualizado); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/cobros/programas/route.ts b/src/app/api/cobros/programas/route.ts new file mode 100644 index 0000000..38718a1 --- /dev/null +++ b/src/app/api/cobros/programas/route.ts @@ -0,0 +1,85 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "@/lib/db"; +import { requireStaff } from "@/lib/auth"; +import { programaPagoSchema } from "@/lib/schemas"; +import { parseFechaCalendario, proximaFecha } from "@/lib/cobros"; + +// GET /api/cobros/programas — lista programas con cliente, conteo de pagos y +// proxima fecha calculada. Solo staff. +export async function GET() { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const programas = await prisma.programaPago.findMany({ + orderBy: [{ activo: "desc" }, { createdAt: "desc" }], + include: { + cliente: { select: { id: true, nombre: true, empresa: true } }, + _count: { select: { pagos: true } }, + }, + }); + + const salida = programas.map((p) => { + const prox = proximaFecha(p); + return { + ...p, + proximaFecha: prox ? prox.toISOString().slice(0, 10) : null, + }; + }); + + return NextResponse.json(salida); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} + +// POST /api/cobros/programas — crea un programa de pago recurrente. +export async function POST(request: NextRequest) { + try { + const session = await requireStaff(); + if (!session) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const body = await request.json(); + const parsed = programaPagoSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues.map((i) => i.message).join(", ") }, + { status: 400 } + ); + } + const data = parsed.data; + + const cliente = await prisma.cliente.findUnique({ + where: { id: data.clienteId }, + select: { id: true }, + }); + if (!cliente) { + return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 }); + } + + const programa = await prisma.programaPago.create({ + data: { + clienteId: data.clienteId, + cotizacionId: data.cotizacionId || null, + concepto: data.concepto, + monto: data.monto, + frecuencia: data.frecuencia, + diaSemana: data.diaSemana ?? null, + diaMes: data.diaMes ?? null, + fechaInicio: parseFechaCalendario(data.fechaInicio), + fechaFin: data.fechaFin ? parseFechaCalendario(data.fechaFin) : null, + activo: true, + }, + }); + + return NextResponse.json(programa, { status: 201 }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/comprobantes/[pagoId]/route.ts b/src/app/api/comprobantes/[pagoId]/route.ts new file mode 100644 index 0000000..7adecd3 --- /dev/null +++ b/src/app/api/comprobantes/[pagoId]/route.ts @@ -0,0 +1,75 @@ +import { readFile } from "fs/promises"; +import { NextRequest, NextResponse } from "next/server"; +import path from "path"; +import { prisma } from "@/lib/db"; +import { getSession } from "@/lib/auth"; +import { archivoExiste, rutaAbsoluta } from "@/lib/uploads"; + +// GET /api/comprobantes/[pagoId] — sirve el archivo del comprobante. +// Acceso: staff O (cliente dueño del programa). Validación de pertenencia aqui +// además del gate de middleware (ruta compartida). +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ pagoId: string }> } +) { + try { + const { pagoId } = await params; + + const session = await getSession(); + const staff = session && session.role !== "cliente"; + const clienteId = session?.clienteId; + + const pago = await prisma.pagoRecurrente.findUnique({ + where: { id: pagoId }, + include: { + comprobante: true, + programa: { select: { clienteId: true } }, + }, + }); + + if (!pago) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + + const esDueno = + session?.role === "cliente" && clienteId === pago.programa.clienteId; + if (!staff && !esDueno) { + return NextResponse.json({ error: "No autorizado" }, { status: 403 }); + } + + const comprobante = pago.comprobante; + if (!comprobante) { + return NextResponse.json( + { error: "Sin comprobante para este cobro" }, + { status: 404 } + ); + } + + if (!(await archivoExiste(comprobante.archivoRuta))) { + return NextResponse.json( + { error: "El archivo del comprobante ya no existe" }, + { status: 404 } + ); + } + + const abs = rutaAbsoluta(comprobante.archivoRuta); + if (!abs) { + return NextResponse.json({ error: "Ruta invalida" }, { status: 404 }); + } + + const data = await readFile(abs); + const ext = path.extname(abs).slice(1) || "bin"; + const nombre = `comprobante.${ext.replace(/[^a-zA-Z0-9]/g, "")}`; + + return new NextResponse(new Uint8Array(data), { + headers: { + "Content-Type": comprobante.mime, + "Content-Disposition": `inline; filename="${nombre}"`, + "Cache-Control": "private, no-store", + }, + }); + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : "Error interno"; + return NextResponse.json({ error: msg }, { status: 500 }); + } +} diff --git a/src/app/api/export/pdf/[id]/route.ts b/src/app/api/export/pdf/[id]/route.ts index 016bd41..6ac691d 100644 --- a/src/app/api/export/pdf/[id]/route.ts +++ b/src/app/api/export/pdf/[id]/route.ts @@ -1,5 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; +import { getSession } from "@/lib/auth"; import { generateCotizacionPDF } from "@/lib/pdf-generator"; import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers"; import { sanitizeFilename } from "@/lib/calculators"; @@ -10,6 +11,18 @@ export async function GET( ) { try { const { id } = await params; + // Ruta compartida (staff + cliente): el cliente solo puede descargar sus + // propias cotizaciones; para staff no se toca nada mas del handler. + const session = await getSession(); + if (session?.role === "cliente") { + const propia = await prisma.cotizacion.findUnique({ + where: { id }, + select: { clienteId: true }, + }); + if (!propia || propia.clienteId !== session.clienteId) { + return NextResponse.json({ error: "No encontrado" }, { status: 404 }); + } + } const [cot, config, branding, bonos] = await Promise.all([ prisma.cotizacion.findUnique({ where: { id }, diff --git a/src/app/cliente/ClienteShell.tsx b/src/app/cliente/ClienteShell.tsx new file mode 100644 index 0000000..9e614a8 --- /dev/null +++ b/src/app/cliente/ClienteShell.tsx @@ -0,0 +1,227 @@ +"use client"; + +import { useEffect, useState } from "react"; +import Link from "next/link"; +import { usePathname, useRouter } from "next/navigation"; +import { + Bell, + BellRing, + CreditCard, + FileText, + Home, + LogOut, + Sparkles, +} from "lucide-react"; +import { useToast } from "@/components/ui/DialogProvider"; + +const NAV = [ + { href: "/cliente", label: "Inicio", icon: Home }, + { href: "/cliente/cotizaciones", label: "Cotizaciones", icon: FileText }, + { href: "/cliente/pagos", label: "Pagos", icon: CreditCard }, +]; + +function esActiva(pathname: string, href: string): boolean { + if (href === "/cliente") return pathname === href; + return pathname === href || pathname.startsWith(href + "/"); +} + +// Header del panel cliente: marca, nombre, nav con estado activo, activacion +// de notificaciones push y cierre de sesion. +export function ClienteShell({ nombre }: { nombre: string }) { + const pathname = usePathname(); + const router = useRouter(); + const toast = useToast(); + const [activas, setActivas] = useState(false); + const [activando, setActivando] = useState(false); + + // Si el navegador ya tiene una suscripcion registrada, el boton queda + // deshabilitado como "Notificaciones activas". + useEffect(() => { + let cancelado = false; + (async () => { + try { + if ( + "serviceWorker" in navigator && + "PushManager" in window && + typeof Notification !== "undefined" && + Notification.permission === "granted" + ) { + const reg = await navigator.serviceWorker.register("/sw.js"); + const sub = await reg.pushManager.getSubscription(); + if (!cancelado && sub) setActivas(true); + } + } catch { + // Sin subscription previa el boton sigue disponible para activar. + } + })(); + return () => { + cancelado = true; + }; + }, []); + + const cerrarSesion = async () => { + try { + await fetch("/api/auth/logout", { method: "POST" }); + } catch { + // Aunque falle la peticion, limpiamos la navegacion local. + } + router.push("/login"); + router.refresh(); + }; + + const activarNotificaciones = async () => { + if (activando || activas) return; + setActivando(true); + try { + if ( + !("serviceWorker" in navigator) || + !("PushManager" in window) || + typeof Notification === "undefined" + ) { + toast("Las notificaciones no están disponibles", "error"); + return; + } + + const res = await fetch("/api/cliente/push/config"); + if (res.status === 401 || res.status === 501) { + toast("Las notificaciones no están disponibles", "error"); + return; + } + if (!res.ok) { + toast("Las notificaciones no están disponibles", "error"); + return; + } + const data = (await res.json()) as { publicKey?: string }; + if (!data.publicKey) { + toast("Las notificaciones no están disponibles", "error"); + return; + } + + if (Notification.permission === "denied") { + toast( + "El navegador bloqueó las notificaciones. Actívalas en la configuración del sitio.", + "error" + ); + return; + } + + let permiso: NotificationPermission = Notification.permission; + if (permiso === "default") { + permiso = await Notification.requestPermission(); + } + if (permiso !== "granted") { + toast("No se otorgó el permiso de notificaciones", "error"); + return; + } + + const reg = await navigator.serviceWorker.register("/sw.js"); + let sub = await reg.pushManager.getSubscription(); + if (!sub) { + sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: data.publicKey, + }); + } + + const json = sub.toJSON(); + if (!json.endpoint || !json.keys?.p256dh || !json.keys?.auth) { + toast("No se pudo registrar la suscripción", "error"); + return; + } + + const guardar = await fetch("/api/cliente/push/suscribir", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + endpoint: json.endpoint, + p256dh: json.keys.p256dh, + auth: json.keys.auth, + }), + }); + if (!guardar.ok) { + const err = (await guardar.json().catch(() => ({}))) as { error?: string }; + toast(err.error || "No se pudieron activar las notificaciones", "error"); + return; + } + + setActivas(true); + toast("Notificaciones activadas", "success"); + } catch { + toast("No se pudieron activar las notificaciones", "error"); + } finally { + setActivando(false); + } + }; + + return ( +
+
+
+ + + + + + Cotizador E3 + {nombre} + + + +
+ + + +
+
+ + +
+
+ ); +} diff --git a/src/app/cliente/cotizaciones/[id]/page.tsx b/src/app/cliente/cotizaciones/[id]/page.tsx new file mode 100644 index 0000000..08dcbb7 --- /dev/null +++ b/src/app/cliente/cotizaciones/[id]/page.tsx @@ -0,0 +1,336 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { ArrowLeft, Download, FileText } from "lucide-react"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { + IVA_RATE, + conIva, + calcularTotalesCotizacion, + calcularTotalesOpcion, + formatCurrency, + formatDate, + type MetaOpcion, +} from "@/lib/calculators"; +import { EstadoBadge } from "@/components/EstadoBadge"; + +export const dynamic = "force-dynamic"; + +const TIPO_PAGO_LABEL: Record = { + unico: "Único", + mensual: "Mensual", +}; + +// Detalle de una cotizacion del cliente: servicios (respetando doble +// propuesta), totales con IVA y descarga del PDF. +export default async function ClienteCotizacionDetallePage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const session = await requireRole("cliente"); + if (!session) redirect("/login?panel=cliente"); + if (!session.clienteId) redirect("/login?panel=cliente"); + + const { id } = await params; + + const cot = await prisma.cotizacion.findFirst({ + where: { id, clienteId: session.clienteId }, + include: { + cliente: { select: { nombre: true, empresa: true } }, + servicios: { + orderBy: [{ fase: "asc" }, { createdAt: "asc" }], + include: { servicioCatalogo: { select: { nombre: true } } }, + }, + planBucefalo: true, + }, + }); + if (!cot) notFound(); + + const totales = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva }); + const opcionesMeta = + ((cot.opcionesMetadata as { "1"?: MetaOpcion; "2"?: MetaOpcion } | null) ?? {}); + + const totalConIva = (monto: number) => conIva(monto, cot.incluirIva); + + // Grupos de partidas para doble propuesta: cada servicio se lista una sola + // vez, debajo de su opcion ("ambas"/sin opcion => compartidas). Los TOTALES + // por opcion SI incluyen las partidas "ambas" (calcularTotalesOpcion). + const gruposDoble = cot.esDoble + ? [ + { + clave: "1", + titulo: `Opción 1${opcionesMeta["1"]?.titulo ? `: ${opcionesMeta["1"].titulo}` : ""}`, + descripcion: opcionesMeta["1"]?.descripcion, + servicios: cot.servicios.filter((s) => s.opcion === "1"), + totales: calcularTotalesOpcion(cot.servicios, "1"), + }, + { + clave: "2", + titulo: `Opción 2${opcionesMeta["2"]?.titulo ? `: ${opcionesMeta["2"].titulo}` : ""}`, + descripcion: opcionesMeta["2"]?.descripcion, + servicios: cot.servicios.filter((s) => s.opcion === "2"), + totales: calcularTotalesOpcion(cot.servicios, "2"), + }, + { + clave: "ambas", + titulo: "Partidas compartidas", + descripcion: undefined, + servicios: cot.servicios.filter((s) => s.opcion === "ambas" || !s.opcion), + totales: null, + }, + ].filter((g) => g.servicios.length > 0) + : []; + + const serviciosVisibles = cot.esDoble ? [] : cot.servicios.filter((s) => s.seleccionado); + + return ( +
+
+
+ + + +
+

{cot.numero}

+

+ {cot.proyecto} · {formatDate(cot.fecha)} +

+
+
+ +
+ +
+

Información general

+
+
+ Cliente +

{cot.cliente.nombre}

+
+
+ Empresa +

{cot.cliente.empresa || "-"}

+
+
+ Vigencia +

{formatDate(cot.vigencia)}

+
+
+ Moneda +

{cot.moneda}

+
+
+
+ + {cot.planBucefalo?.seleccionado && ( +
+
+

+ + Plan Bucéfalo +

+

+ Nivel {cot.planBucefalo.nivel} · CRM para tu operación +

+
+

{formatCurrency(cot.planBucefalo.precio)}/mes

+
+ )} + + {cot.esDoble ? ( +
+ {gruposDoble.map((g) => ( +
+
+

{g.titulo}

+ {g.descripcion && ( +

+ {g.descripcion} +

+ )} +
+ + + + + + + + + + {g.servicios.map((s) => ( + + + + + + ))} + +
ServicioTipo de pagoPrecio
+ {s.servicioCatalogo?.nombre || s.nombre || "Servicio"} + + {TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago} + + {formatCurrency(s.precio)} +
+ {g.totales && ( +
+
+ Total unico{cot.incluirIva ? " (c/IVA)" : ""} + + {formatCurrency(totalConIva(g.totales.totalUnico))} + +
+
+ Total mensual{cot.incluirIva ? " (c/IVA)" : ""} + + {formatCurrency(totalConIva(g.totales.totalMensual))} + +
+
+ )} +
+ ))} +
+ ) : ( +
+
+

Servicios

+
+ {serviciosVisibles.length === 0 ? ( +
+ Esta cotización no tiene servicios registrados. +
+ ) : ( + + + + + + + + + + {serviciosVisibles.map((s) => ( + + + + + + ))} + +
ServicioTipo de pagoPrecio
+ {s.servicioCatalogo?.nombre || s.nombre || "Servicio"} + + {TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago} + + {formatCurrency(s.precio)} +
+ )} +
+ )} + +
+

Totales

+ {cot.esDoble ? ( +
+ {(["1", "2"] as const).map((op) => { + const t = calcularTotalesOpcion(cot.servicios, op); + const meta = opcionesMeta[op]; + return ( +
+

+ Opción {op} + {meta?.titulo ? `: ${meta.titulo}` : ""} +

+
+
+ + Total unico{cot.incluirIva ? " (c/IVA)" : ""} + + + {formatCurrency(totalConIva(t.totalUnico))} + +
+
+ + Total mensual{cot.incluirIva ? " (c/IVA)" : ""} + + + {formatCurrency(totalConIva(t.totalMensual))} + +
+
+
+ ); + })} +
+ ) : ( +
+ {totales.incluyeIva && ( + <> +
+ Subtotal unico + {formatCurrency(totales.subtotalUnico)} +
+
+ IVA ({Math.round(IVA_RATE * 100)}%) + {formatCurrency(totales.ivaUnico)} +
+ + )} +
+ Total unico + {formatCurrency(totales.totalUnico)} +
+ {totales.incluyeIva && ( + <> +
+ Subtotal mensual + {formatCurrency(totales.subtotalMensual)} +
+
+ IVA ({Math.round(IVA_RATE * 100)}%) + {formatCurrency(totales.ivaMensual)} +
+ + )} +
+ Total mensual + {formatCurrency(totales.totalMensual)} +
+ {!totales.incluyeIva && ( +

Los precios no incluyen IVA.

+ )} +
+ )} +
+ + {cot.observaciones && ( +
+

Observaciones

+

{cot.observaciones}

+
+ )} +
+ ); +} diff --git a/src/app/cliente/cotizaciones/page.tsx b/src/app/cliente/cotizaciones/page.tsx new file mode 100644 index 0000000..5b9a0e1 --- /dev/null +++ b/src/app/cliente/cotizaciones/page.tsx @@ -0,0 +1,154 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { ArrowRight, FileText } from "lucide-react"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { + IVA_RATE, + calcularTotalesCotizacion, + calcularTotalesOpcion, + formatCurrency, + formatDate, +} from "@/lib/calculators"; +import { EstadoBadge } from "@/components/EstadoBadge"; + +export const dynamic = "force-dynamic"; + +// Lista de cotizaciones del cliente: numero, proyecto, fecha, estado y totales. +export default async function ClienteCotizacionesPage() { + const session = await requireRole("cliente"); + if (!session) redirect("/login?panel=cliente"); + if (!session.clienteId) redirect("/login?panel=cliente"); + + const cotizaciones = await prisma.cotizacion.findMany({ + where: { clienteId: session.clienteId }, + orderBy: { fecha: "desc" }, + select: { + id: true, + numero: true, + proyecto: true, + fecha: true, + estado: true, + esDoble: true, + incluirIva: true, + servicios: { select: { tipoPago: true, precio: true, seleccionado: true, opcion: true } }, + }, + }); + + return ( +
+
+

Mis cotizaciones

+

+ {cotizaciones.length === 0 + ? "Aún no tienes cotizaciones" + : `${cotizaciones.length} cotizacion${cotizaciones.length === 1 ? "" : "es"} a tu nombre`} +

+
+ + {cotizaciones.length === 0 ? ( +
+ +

No hay cotizaciones todavía

+

+ Cuando tengas una cotización disponible aparecerá en esta sección. +

+
+ ) : ( +
+ + + + + + + + + + + + + + {cotizaciones.map((c) => { + const totales = calcularTotalesCotizacion(c.servicios, { + incluirIva: c.incluirIva, + }); + const conIva = (m: number) => + c.incluirIva ? Math.round(m * (1 + IVA_RATE) * 100) / 100 : m; + return ( + + + + + + + + + + ); + })} + +
No. CotizacionProyectoFechaEstadoTotal UnicoTotal Mensual
+ + {c.numero} + + {c.esDoble && ( + + Doble propuesta + + )} + {c.proyecto}{formatDate(c.fecha)} + + + {c.esDoble ? ( +
+ {(["1", "2"] as const).map((op) => { + const t = calcularTotalesOpcion(c.servicios, op); + return ( +

+ Op {op}:{" "} + {t.totalUnico > 0 ? formatCurrency(conIva(t.totalUnico)) : "-"} +

+ ); + })} +
+ ) : totales.totalUnico > 0 ? ( + formatCurrency(totales.totalUnico) + ) : ( + "-" + )} +
+ {c.esDoble ? ( +
+ {(["1", "2"] as const).map((op) => { + const t = calcularTotalesOpcion(c.servicios, op); + return ( +

+ Op {op}:{" "} + {t.totalMensual > 0 ? formatCurrency(conIva(t.totalMensual)) : "-"} +

+ ); + })} +
+ ) : totales.totalMensual > 0 ? ( + formatCurrency(totales.totalMensual) + ) : ( + "-" + )} +
+ + Ver + + +
+
+ )} +
+ ); +} diff --git a/src/app/cliente/layout.tsx b/src/app/cliente/layout.tsx new file mode 100644 index 0000000..876b11e --- /dev/null +++ b/src/app/cliente/layout.tsx @@ -0,0 +1,34 @@ +import { redirect } from "next/navigation"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { DialogProvider } from "@/components/ui/DialogProvider"; +import { ClienteShell } from "./ClienteShell"; + +// Shell propio del panel de cliente: NO comparte el layout de (app) ni el +// Sidebar del staff. requireRole es la segunda barrera ademas del middleware. +export default async function ClienteLayout({ + children, +}: { + children: React.ReactNode; +}) { + const session = await requireRole("cliente"); + if (!session) redirect("/login?panel=cliente"); + + const cliente = session.clienteId + ? await prisma.cliente.findUnique({ + where: { id: session.clienteId }, + select: { nombre: true }, + }) + : null; + + return ( + +
+ +
+ {children} +
+
+
+ ); +} diff --git a/src/app/cliente/page.tsx b/src/app/cliente/page.tsx new file mode 100644 index 0000000..7b26b40 --- /dev/null +++ b/src/app/cliente/page.tsx @@ -0,0 +1,197 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { + ArrowRight, + CalendarClock, + ClipboardList, + Clock3, + FileText, + Inbox, + ShieldCheck, +} from "lucide-react"; +import { requireRole } from "@/lib/auth"; +import { formatCurrency, formatDate } from "@/lib/calculators"; +import { formatFechaCorta } from "@/lib/cobros"; +import { EstadoBadge } from "@/components/EstadoBadge"; +import { obtenerResumenCliente } from "./resumen-data"; + +export const dynamic = "force-dynamic"; + +export default async function ClienteInicioPage() { + const session = await requireRole("cliente"); + if (!session) redirect("/login?panel=cliente"); + + const resumen = session.clienteId + ? await obtenerResumenCliente(session.clienteId) + : null; + + if (!resumen) { + return ( +
+ +

Cuenta sin cliente asociado

+

+ Tu usuario no tiene un cliente vinculado. Contacta al administrador para + darlo de alta. +

+
+ ); + } + + const tarjetas = [ + { + label: "Cotizaciones activas", + value: resumen.cotizacionesActivas, + icon: FileText, + bg: "bg-primary-light", + color: "text-primary", + }, + { + label: "Pagos pendientes", + value: resumen.pagos.pendientes, + icon: Clock3, + bg: "bg-amber-100", + color: "text-amber-600", + }, + { + label: "En revisión", + value: resumen.pagos.enRevision, + icon: ClipboardList, + bg: "bg-blue-100", + color: "text-blue-600", + }, + { + label: "Verificados este mes", + value: resumen.pagos.verificadosMes, + icon: ShieldCheck, + bg: "bg-green-100", + color: "text-green-600", + }, + ]; + + return ( +
+
+

Hola, {resumen.cliente.nombre}

+

+ {resumen.cliente.empresa + ? resumen.cliente.empresa + " · " + : ""} + Consulta tus cotizaciones y el estado de tus pagos. +

+
+ +
+ {tarjetas.map((t) => ( +
+
+
+ +
+
+

{t.value}

+

{t.label}

+
+
+
+ ))} +
+ +
+
+

+ + Próximos cobros +

+ + Ver todos + + +
+ {resumen.pagos.proximos.length === 0 ? ( +
+ +

+ No tienes cobros programados por ahora. +

+
+ ) : ( +
    + {resumen.pagos.proximos.map((p) => ( +
  • +
    +

    {p.concepto}

    +

    {formatFechaCorta(p.fecha)}

    +
    +

    {formatCurrency(p.monto)}

    +
  • + ))} +
+ )} +
+ +
+
+

Últimas cotizaciones

+ + Ver todas + + +
+ {resumen.cotizaciones.length === 0 ? ( +
+ +

+ Todavía no tienes cotizaciones. En cuanto el administrador la envíe, + aparecerá aquí. +

+
+ ) : ( +
    + {resumen.cotizaciones.map((c) => ( +
  • + +
    +

    {c.numero}

    +

    {c.proyecto}

    +
    +
    + + {formatDate(c.fecha)} + + +
    + {c.totales.totalUnico > 0 && ( +

    + {formatCurrency(c.totales.totalUnico)} +

    + )} + {c.totales.totalMensual > 0 && ( +

    + {formatCurrency(c.totales.totalMensual)}/mes +

    + )} +
    + +
    + +
  • + ))} +
+ )} +
+
+ ); +} diff --git a/src/app/cliente/pagos/SubirComprobante.tsx b/src/app/cliente/pagos/SubirComprobante.tsx new file mode 100644 index 0000000..01dcbf4 --- /dev/null +++ b/src/app/cliente/pagos/SubirComprobante.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { Loader2, Upload } from "lucide-react"; +import { useToast } from "@/components/ui/DialogProvider"; + +// Subida de comprobante para un cobro pendiente o rechazado. multipart/form-data +// a POST /api/cliente/pagos/[id]/comprobante; en error muestra el {error} del server. +export function SubirComprobante({ pagoId }: { pagoId: string }) { + const router = useRouter(); + const toast = useToast(); + const [subiendo, setSubiendo] = useState(false); + + const onChange = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + setSubiendo(true); + try { + const fd = new FormData(); + fd.append("file", file); + const res = await fetch(`/api/cliente/pagos/${pagoId}/comprobante`, { + method: "POST", + body: fd, + }); + if (!res.ok) { + const data = (await res.json().catch(() => ({}))) as { error?: string }; + toast(data.error || "No se pudo subir el comprobante", "error"); + } else { + toast("Comprobante enviado. Espera la revisión del administrador.", "success"); + router.refresh(); + } + } catch { + toast("Error de conexión al subir el comprobante", "error"); + } finally { + setSubiendo(false); + // Permite volver a elegir el mismo archivo tras un error. + e.target.value = ""; + } + }; + + return ( + + ); +} diff --git a/src/app/cliente/pagos/page.tsx b/src/app/cliente/pagos/page.tsx new file mode 100644 index 0000000..8d00b03 --- /dev/null +++ b/src/app/cliente/pagos/page.tsx @@ -0,0 +1,184 @@ +import { redirect } from "next/navigation"; +import { CalendarClock, Inbox } from "lucide-react"; +import { requireRole } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { formatCurrency } from "@/lib/calculators"; +import { ESTADOS_PAGO, formatFechaCorta } from "@/lib/cobros"; +import { SubirComprobante } from "./SubirComprobante"; + +export const dynamic = "force-dynamic"; + +const DIAS_SEMANA = [ + "domingo", + "lunes", + "martes", + "miércoles", + "jueves", + "viernes", + "sábado", +]; + +function frecuenciaLegible(p: { + frecuencia: string; + diaSemana?: number | null; + diaMes?: number | null; +}): string { + if (p.frecuencia === "semanal") { + return `Semanal (${DIAS_SEMANA[p.diaSemana ?? 0]})`; + } + if (p.frecuencia === "quincenal") { + return "Quincenal (días 1 y 15)"; + } + if (p.frecuencia === "mensual") { + return `Mensual (día ${p.diaMes ?? 1})`; + } + return p.frecuencia; +} + +function EstadoPagoBadge({ + estado, + rechazoMotivo, +}: { + estado: string; + rechazoMotivo?: string | null; +}) { + let cls = "bg-amber-100 text-amber-700"; + let label = "Pendiente de pago"; + if (estado === ESTADOS_PAGO.EN_REVISION) { + cls = "bg-blue-100 text-blue-700"; + label = "En revisión"; + } else if (estado === ESTADOS_PAGO.VERIFICADO) { + cls = "bg-green-100 text-green-700"; + label = "Verificado ✓"; + } else if (estado === ESTADOS_PAGO.RECHAZADO) { + cls = "bg-red-100 text-red-700"; + label = "Rechazado"; + } + return ( +
+ + {label} + + {estado === ESTADOS_PAGO.RECHAZADO && rechazoMotivo && ( +

Motivo: {rechazoMotivo}

+ )} +
+ ); +} + +// Guia de pagos recurrentes: un bloque por programa y su tabla de cobros, +// con subida de comprobante para los pendientes/rechazados. +export default async function ClientePagosPage() { + const session = await requireRole("cliente"); + if (!session) redirect("/login?panel=cliente"); + if (!session.clienteId) redirect("/login?panel=cliente"); + + const programas = await prisma.programaPago.findMany({ + where: { clienteId: session.clienteId }, + orderBy: [{ activo: "desc" }, { concepto: "asc" }], + include: { + pagos: { + orderBy: { fecha: "desc" }, + include: { comprobante: { select: { archivoNombre: true, subidoAt: true } } }, + }, + }, + }); + + return ( +
+
+

Mis pagos

+

+ Historial de cobros recurrentes y carga de comprobantes +

+
+ +
+ Sube tu comprobante de pago (imagen o PDF). El administrador lo revisará y + quedará como verificado. +
+ + {programas.length === 0 ? ( +
+ +

Sin cobros programados

+

+ Cuando se configure un programa de pagos para ti, aparecerá aquí junto + con cada cobro generado. +

+
+ ) : ( + programas.map((prog) => ( +
+
+
+

+ + {prog.concepto} +

+

+ {formatCurrency(prog.monto)} · {frecuenciaLegible(prog)} · {prog.moneda} +

+
+ {!prog.activo && ( + + Programa inactivo + + )} +
+ + {prog.pagos.length === 0 ? ( +
+ Aún no se han generado cobros de este programa. +
+ ) : ( +
+ + + + + + + + + + + {prog.pagos.map((pago) => ( + + + + + + + ))} + +
FechaMontoEstadoAcción
{formatFechaCorta(pago.fecha)} + {formatCurrency(pago.monto)} + + + + {pago.estado === ESTADOS_PAGO.PENDIENTE || + pago.estado === ESTADOS_PAGO.RECHAZADO ? ( + + ) : ( + + Ver comprobante + + )} +
+
+ )} +
+ )) + )} +
+ ); +} diff --git a/src/app/cliente/resumen-data.ts b/src/app/cliente/resumen-data.ts new file mode 100644 index 0000000..32b7961 --- /dev/null +++ b/src/app/cliente/resumen-data.ts @@ -0,0 +1,118 @@ +import { prisma } from "@/lib/db"; +import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators"; +import { ESTADOS_PAGO, hoyCalendario, proximaFecha } from "@/lib/cobros"; + +// Resumen del panel de cliente. Compartido entre GET /api/cliente/resumen y la +// pagina de inicio (/cliente) para que ambas caras cuenten exactamente lo mismo. + +export interface ResumenCotizacion { + id: string; + numero: string; + proyecto: string; + fecha: Date; + estado: string; + esDoble: boolean; + totales: ReturnType; + totalesOpciones?: { + "1": ReturnType; + "2": ReturnType; + }; +} + +export interface ResumenCliente { + cliente: { nombre: string; empresa: string | null }; + cotizacionesActivas: number; + cotizaciones: ResumenCotizacion[]; + pagos: { + pendientes: number; + enRevision: number; + verificadosMes: number; + proximos: Array<{ fecha: Date; monto: number; concepto: string }>; + }; +} + +export async function obtenerResumenCliente(clienteId: string): Promise { + const cliente = await prisma.cliente.findUnique({ + where: { id: clienteId }, + select: { nombre: true, empresa: true }, + }); + if (!cliente) return null; + + const hoy = hoyCalendario(); + const inicioMes = new Date(Date.UTC(hoy.getUTCFullYear(), hoy.getUTCMonth(), 1)); + + const [cotizacionesActivas, cotizacionesBrutas, pendientes, enRevision, verificadosMes, programas] = + await Promise.all([ + prisma.cotizacion.count({ + where: { clienteId, estado: { not: "rechazada" } }, + }), + prisma.cotizacion.findMany({ + where: { clienteId }, + orderBy: { fecha: "desc" }, + take: 5, + select: { + id: true, + numero: true, + proyecto: true, + fecha: true, + estado: true, + esDoble: true, + incluirIva: true, + servicios: { + select: { tipoPago: true, precio: true, seleccionado: true, opcion: true }, + }, + }, + }), + prisma.pagoRecurrente.count({ + where: { estado: ESTADOS_PAGO.PENDIENTE, programa: { clienteId } }, + }), + prisma.pagoRecurrente.count({ + where: { estado: ESTADOS_PAGO.EN_REVISION, programa: { clienteId } }, + }), + prisma.pagoRecurrente.count({ + where: { + estado: ESTADOS_PAGO.VERIFICADO, + verificadoAt: { gte: inicioMes }, + programa: { clienteId }, + }, + }), + prisma.programaPago.findMany({ where: { clienteId, activo: true } }), + ]); + + const cotizaciones: ResumenCotizacion[] = cotizacionesBrutas.map((c) => { + const totales = calcularTotalesCotizacion(c.servicios, { incluirIva: c.incluirIva }); + return { + id: c.id, + numero: c.numero, + proyecto: c.proyecto, + fecha: c.fecha, + estado: c.estado, + esDoble: c.esDoble, + totales, + ...(c.esDoble + ? { + totalesOpciones: { + "1": calcularTotalesOpcion(c.servicios, "1"), + "2": calcularTotalesOpcion(c.servicios, "2"), + }, + } + : {}), + }; + }); + + const proximos = programas + .map((p) => { + const fecha = proximaFecha(p); + return fecha ? { fecha, monto: p.monto, concepto: p.concepto } : null; + }) + .filter((x): x is { fecha: Date; monto: number; concepto: string } => x !== null) + .sort((a, b) => a.fecha.getTime() - b.fecha.getTime()) + .slice(0, 3); + + return { + cliente, + cotizacionesActivas, + cotizaciones, + pagos: { pendientes, enRevision, verificadosMes, proximos }, + }; +} diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index a355dc2..2994b46 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -23,7 +23,10 @@ export default function LoginPage() { }); if (res.ok) { - router.push("/"); + const data = await res.json(); + // Cada rol entra a su propio panel. + const destino = data?.user?.role === "cliente" ? "/cliente" : "/"; + router.push(destino); router.refresh(); } else { const data = await res.json(); diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index 6ca9504..0494b22 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -7,6 +7,7 @@ import { FileText, Database, Users, + Receipt, Settings, Menu, X, @@ -20,6 +21,7 @@ const navigation = [ { name: "Cotizaciones", href: "/cotizaciones", icon: FileText }, { name: "Catalogo", href: "/catalogo", icon: Database }, { name: "Clientes", href: "/clientes", icon: Users }, + { name: "Cobros", href: "/cobros", icon: Receipt }, { name: "Configuracion", href: "/configuracion", icon: Settings }, ]; diff --git a/src/instrumentation.ts b/src/instrumentation.ts new file mode 100644 index 0000000..06924a2 --- /dev/null +++ b/src/instrumentation.ts @@ -0,0 +1,17 @@ +/** + * Punto de arranque del scheduler de cobros recurrentes. + * + * Next compila instrumentation.ts PARA DOS RUNTIMES (node y edge). El scheduler + * toca Prisma/correo/push, así que solo existe en el bundle de node: el import + * dinámico vive DENTRO del guard `NEXT_RUNTIME === "nodejs"` para que el + * compilador elimine la rama muerta en edge y no intente empaquetar pg ahí. + * + * La lógica (guard anti-timers-duplicados, primera ejecución a los 20 s y + * cada 60 min) está en src/lib/scheduler.ts — ver su cabecera. + */ +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + const { iniciarSchedulerCobros } = await import("./lib/scheduler"); + iniciarSchedulerCobros(); + } +} diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 9a50445..7af45a8 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -12,6 +12,10 @@ export interface SessionPayload { email: string; name: string; role: string; + // Presente solo cuando role === "cliente": identifica el registro de Cliente + // al que esta vinculada la cuenta. Las rutas del panel cliente lo usan para + // acotar las consultas sin tocar la BD. + clienteId?: string; } export async function createSession(payload: SessionPayload): Promise { @@ -64,3 +68,19 @@ export function clearSessionCookie() { maxAge: 0, }; } + +// Segunda barrera ademas del middleware: la usa cada route handler para no +// depender unicamente del gate de borde. Devuelve null si no hay sesion o si +// el rol no coincide. +export async function requireRole(rol: string): Promise { + const session = await getSession(); + if (!session || session.role !== rol) return null; + return session; +} + +// Sesion de administrador/asesor (cualquier rol que no sea "cliente"). +export async function requireStaff(): Promise { + const session = await getSession(); + if (!session || session.role === "cliente") return null; + return session; +} diff --git a/src/lib/cobros-fechas.ts b/src/lib/cobros-fechas.ts new file mode 100644 index 0000000..fc1209f --- /dev/null +++ b/src/lib/cobros-fechas.ts @@ -0,0 +1,137 @@ +// Utilidades PURAS de los cobros recurrentes: fechas de calendario, estados y +// formatos. Sin prisma ni fs — SEGURO PARA COMPONENTES "use client" (los +// componentes del navegador importan de aqui, NUNCA de @/lib/cobros, que si +// arrastra la BD y rompe el build de Next). +// +// La logica que toca la BD (generarCobros) vive en @/lib/cobros, que re-exporta +// todo lo de este archivo para el lado servidor. +// +// CONVENCION DE FECHAS: una fecha de cobro es una FECHA DE CALENDARIO en +// America/Mexico_City, persistida como medianoche UTC de ese calendario +// (Date.UTC(y, m-1, d)). Se escribe con parseFechaCalendario() y se muestra +// con formatFechaCobro(). Asi "sabado" es sabado en Mexico aunque el servidor +// este en UTC. + +import type { ProgramaPago } from "@/generated/prisma/client"; + +export const ZONA_HORARIA = "America/Mexico_City"; + +export const ESTADOS_PAGO = { + PENDIENTE: "pendiente", // generado, sin comprobante + EN_REVISION: "en_revision", // comprobante subido, esperando al admin + VERIFICADO: "verificado", // admin acepto el comprobante + RECHAZADO: "rechazado", // admin rechazo (el archivo se borro; se puede volver a subir) +} as const; + +export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO]; + +// "YYYY-MM-DD" (input de formularios) -> Date en medianoche UTC del calendario. +export function parseFechaCalendario(iso: string): Date { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim()); + if (!m) throw new Error(`Fecha invalida: ${iso} (se espera YYYY-MM-DD)`); + return new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))); +} + +// Date -> { y, m, d } usando las partes UTC (la fecha ya es calendario). +export function aCalendario(date: Date): { y: number; m: number; d: number } { + return { y: date.getUTCFullYear(), m: date.getUTCMonth() + 1, d: date.getUTCDate() }; +} + +// Hoy en America/Mexico_City como fecha de calendario (UTC midnight). +export function hoyCalendario(): Date { + const iso = new Intl.DateTimeFormat("en-CA", { + timeZone: ZONA_HORARIA, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(new Date()); // "YYYY-MM-DD" + return parseFechaCalendario(iso); +} + +function sumarDias(d: Date, dias: number): Date { + return new Date(d.getTime() + dias * 86400000); +} + +const fmtFecha = new Intl.DateTimeFormat("es-MX", { + weekday: "long", + day: "2-digit", + month: "long", + year: "numeric", + timeZone: "UTC", // la fecha YA es calendario en UTC; no convertir zona +}); + +// "Sabado, 04 de julio de 2026" para mostrar en el panel/PDF/correo. +export function formatFechaCobro(date: Date): string { + const s = fmtFecha.format(date); + return s.charAt(0).toUpperCase() + s.slice(1); +} + +// Version corta: "04/07/2026". +export function formatFechaCorta(date: Date): string { + const { y, m, d } = aCalendario(date); + return `${String(d).padStart(2, "0")}/${String(m).padStart(2, "0")}/${y}`; +} + +// Todas las fechas de periodo de un programa desde fechaInicio hasta `hasta` +// (inclusive), respetando fechaFin si existe. Cadena: +// semanal -> diaSemana (0=dom..6=sab; si no viene, el mismo dia que fechaInicio) +// quincenal -> dias 1 y 15 de cada mes +// mensual -> diaMes (se recorta al ultimo dia del mes si no existe) +export function fechasPeriodo( + programa: Pick, + hasta: Date +): Date[] { + const inicio = aCalendario(programa.fechaInicio); + const inicioD = new Date(Date.UTC(inicio.y, inicio.m - 1, inicio.d)); + const fin = programa.fechaFin ? aCalendario(programa.fechaFin) : null; + const finD = fin ? new Date(Date.UTC(fin.y, fin.m - 1, fin.d)) : null; + const limite = finD && finD < hasta ? finD : hasta; + if (inicioD > limite) return []; + + const out: Date[] = []; + + if (programa.frecuencia === "semanal") { + const dia = programa.diaSemana ?? inicioD.getUTCDay(); + let d = new Date(inicioD); + let guard = 0; + while (d.getUTCDay() !== dia && guard++ < 7) d = sumarDias(d, 1); + while (d <= limite) { + out.push(d); + d = sumarDias(d, 7); + } + } else if (programa.frecuencia === "quincenal") { + let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1)); + while (mes <= limite) { + for (const dia of [1, 15]) { + const d = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), dia)); + if (d >= inicioD && d <= limite) out.push(d); + } + mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1)); + } + } else { + // mensual + const diaMes = programa.diaMes ?? 1; + let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1)); + while (mes <= limite) { + const ultimoDia = new Date( + Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 0) + ).getUTCDate(); + const d = new Date( + Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), Math.min(diaMes, ultimoDia)) + ); + if (d >= inicioD && d <= limite) out.push(d); + mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1)); + } + } + + return out; +} + +// Proxima fecha de cobro >= `desde` (por defecto hoy MX) para el panel admin. +export function proximaFecha( + programa: Pick, + desde: Date = hoyCalendario() +): Date | null { + const ventana = fechasPeriodo(programa, sumarDias(desde, 366)); + return ventana.find((f) => f >= desde) ?? null; +} diff --git a/src/lib/cobros.ts b/src/lib/cobros.ts new file mode 100644 index 0000000..66d3ac4 --- /dev/null +++ b/src/lib/cobros.ts @@ -0,0 +1,57 @@ +import { prisma } from "@/lib/db"; +import { aCalendario, fechasPeriodo, hoyCalendario } from "@/lib/cobros-fechas"; +import type { PagoRecurrente } from "@/generated/prisma/client"; + +// LADO SERVIDOR de los cobros recurrentes. Las utilidades puras (fechas, +// estados, formatos) viven en @/lib/cobros-fechas y se re-exportan aqui para +// que el codigo de servidor siga importando de "@/lib/cobros". +// +// IMPORTANTE para componentes "use client": importen de "@/lib/cobros-fechas". +// Importar de "@/lib/cobros" desde el navegador arrastra prisma/pg y rompe el +// build de Next. +export * from "@/lib/cobros-fechas"; + +// GENERACION IDEMPOTENTE. Crea los PagoRecurrente que ya tocan (fecha <= hoy +// MX, o <= `hasta` si se pide generar adelantado) para uno o todos los +// programas activos. Repetir la llamada no duplica: la restriccion unica +// (programaId, fecha) absorbe los cruces. +// +// Devuelve los pagos REALMENTE creados (los ya existentes se ignoran), que es +// lo que el caller debe notificar por correo/push. +export async function generarCobros( + opts: { programaId?: string; hasta?: Date } = {} +): Promise { + const hasta = aCalendarioFecha(opts.hasta ?? hoyCalendario()); + + const programas = await prisma.programaPago.findMany({ + where: { + activo: true, + ...(opts.programaId ? { id: opts.programaId } : {}), + }, + }); + + const creados: PagoRecurrente[] = []; + + for (const programa of programas) { + const fechas = fechasPeriodo(programa, hasta); + for (const fecha of fechas) { + try { + const pago = await prisma.pagoRecurrente.create({ + data: { programaId: programa.id, fecha, monto: programa.monto }, + }); + creados.push(pago); + } catch (e) { + // P2002: (programaId, fecha) ya existe -> periodo ya generado. + if ((e as { code?: string }).code !== "P2002") throw e; + } + } + } + + return creados; +} + +// Normaliza cualquier Date a medianoche UTC de su parte de calendario. +function aCalendarioFecha(date: Date): Date { + const { y, m, d } = aCalendario(date); + return new Date(Date.UTC(y, m - 1, d)); +} diff --git a/src/lib/email.ts b/src/lib/email.ts new file mode 100644 index 0000000..bfb7a6a --- /dev/null +++ b/src/lib/email.ts @@ -0,0 +1,77 @@ +import nodemailer from "nodemailer"; +import type { Transporter } from "nodemailer"; + +// Servicio de correo SMTP configurable por variables de entorno. Si no hay +// configuracion, los envios se omiten con un aviso en lugar de tumbar el flujo: +// la app debe seguir funcionando con SMTP sin dar de alta. +// +// SMTP_HOST=smtp.ejemplo.com +// SMTP_PORT=587 (587=starttls, 465=ssl, 25=negociacion) +// SMTP_USER=usuario +// SMTP_PASS=contrasena +// SMTP_FROM=cotizador@e3.mx (opcional, por defecto SMTP_USER) +// SMTP_FROM_NAME=Cotizador E3 (opcional) + +export interface ResultadoEnvio { + ok: boolean; + // true cuando no hay SMTP configurado y el envio se omitio a proposito. + omitido?: boolean; + error?: string; +} + +let transport: Transporter | null | undefined; + +function crearTransport(): Transporter | null { + const host = process.env.SMTP_HOST; + if (!host) return null; + const port = parseInt(process.env.SMTP_PORT || "587", 10); + return nodemailer.createTransport({ + host, + port, + secure: port === 465, + auth: process.env.SMTP_USER + ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } + : undefined, + }); +} + +export function smtpConfigurado(): boolean { + return Boolean(process.env.SMTP_HOST); +} + +function obtenerTransport(): Transporter | null { + if (transport === undefined) transport = crearTransport(); + return transport; +} + +// Solo para tests/rotacion de credenciales: olvida el transport cacheado. +export function reiniciarTransport() { + transport = undefined; +} + +export async function enviarCorreo(opciones: { + to: string; + subject: string; + html: string; + text?: string; +}): Promise { + const t = obtenerTransport(); + if (!t) { + console.warn("[email] SMTP no configurado (SMTP_HOST ausente); se omite el envio a", opciones.to); + return { ok: false, omitido: true }; + } + try { + await t.sendMail({ + from: `"${process.env.SMTP_FROM_NAME || "Cotizador E3"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`, + to: opciones.to, + subject: opciones.subject, + html: opciones.html, + text: opciones.text, + }); + return { ok: true }; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + console.error("[email] fallo el envio a", opciones.to, "-", msg); + return { ok: false, error: msg }; + } +} diff --git a/src/lib/notificaciones.ts b/src/lib/notificaciones.ts new file mode 100644 index 0000000..5ac7b1c --- /dev/null +++ b/src/lib/notificaciones.ts @@ -0,0 +1,207 @@ +import { prisma } from "@/lib/db"; +import { enviarCorreo } from "@/lib/email"; +import { enviarPush } from "@/lib/push"; +import { ESTADOS_PAGO, formatFechaCobro, formatFechaCorta } from "@/lib/cobros"; +import type { PagoRecurrente } from "@/generated/prisma/client"; + +// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es +// best-effort: un fallo de correo/push jamas revienta el flujo que lo llamo +// (el estado en BD ya quedo escrito antes de notificar). +// +// Los handlers de rutas solo necesitan: +// - tras generar cobros: notificarCobrosNuevos(pagos) +// - al aprobar/rechazar: notificarVerificacion(pagoId) / notificarRechazo(pagoId) + +const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; +const PANEL_PAGOS = `${BASE_URL}/cliente/pagos`; + +function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string { + const botonHtml = boton + ? `

${boton.texto}

` + : ""; + return ` +
+
+

COTIZADOR E3

+

${titulo}

+
${cuerpo}
+ ${botonHtml} +

Consultoría E3 · Querétaro, México

+
+
`; +} + +function clienteDestino(usuario: { email: string } | null, emailCliente: string | null): string | null { + return usuario?.email || emailCliente || null; +} + +async function avisar( + userId: string | null, + email: string | null, + asunto: string, + html: string, + texto: string, + push: { titulo: string; cuerpo: string; url?: string } +): Promise { + if (email) { + await enviarCorreo({ to: email, subject: asunto, html, text: texto }); + } + if (userId) { + await enviarPush(userId, push); + } +} + +type ProgramaConCliente = { + id: string; + concepto: string; + monto: number; + moneda: string; + cliente: { nombre: string; email: string | null; usuario: { id: string; email: string } | null }; +}; + +// Llamada tras generarCobros(): un resumen POR CLIENTE con todos los cobros +// nuevos de la corrida (evita 52 correos si alguien genera un anio de golpe). +export async function notificarCobrosNuevos(pagos: PagoRecurrente[]): Promise { + if (pagos.length === 0) return; + + const porPrograma = new Map(); + for (const p of pagos) { + const lista = porPrograma.get(p.programaId) ?? []; + lista.push(p); + porPrograma.set(p.programaId, lista); + } + + for (const [programaId, lista] of porPrograma) { + try { + const programa = (await prisma.programaPago.findUnique({ + where: { id: programaId }, + include: { cliente: { include: { usuario: true } } }, + })) as ProgramaConCliente | null; + if (!programa) continue; + + const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email); + const userId = programa.cliente.usuario?.id ?? null; + if (!destino && !userId) continue; + + lista.sort((a, b) => a.fecha.getTime() - b.fecha.getTime()); + const primero = lista[0]; + const formatoMonto = (m: number) => + m.toLocaleString("es-MX", { style: "currency", currency: programa.moneda || "MXN" }); + + const filas = lista + .slice(0, 12) + .map((p) => `
  • ${formatFechaCobro(p.fecha)} — ${formatoMonto(p.monto)}
  • `) + .join(""); + const extra = + lista.length > 12 ? `
  • …y ${lista.length - 12} cobros más (ver panel)
  • ` : ""; + + const plural = lista.length > 1; + const titulo = plural + ? `Se ${lista.length > 1 ? "generaron" : "generó"} ${lista.length} cobros de ${programa.concepto}` + : `Nuevo cobro: ${programa.concepto}`; + const cuerpo = ` +

    Hola ${programa.cliente.nombre},

    +

    ${plural ? `Se generaron ${lista.length} cobros` : `Se generó un cobro`} de ${programa.concepto}:

    +
      ${filas}${extra}
    +

    Sube tu comprobante de pago desde el panel para darlo por liquidado.

    `; + + const texto = `${titulo}. Fechas: ${lista + .slice(0, 5) + .map((p) => formatFechaCorta(p.fecha)) + .join(", ")}. Entra al panel para subir tu comprobante.`; + + await avisar( + userId, + destino, + titulo, + plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }), + texto, + { + titulo: plural ? `${lista.length} cobros nuevos` : "Nuevo cobro pendiente", + cuerpo: `${programa.concepto} — ${formatoMonto(primero.monto)} (${formatFechaCorta(primero.fecha)})`, + url: "/cliente/pagos", + } + ); + } catch (e) { + console.error("[notificaciones] fallo al avisar cobros nuevos del programa", programaId, e); + } + } +} + +async function cargarPago(pagoId: string) { + return prisma.pagoRecurrente.findUnique({ + where: { id: pagoId }, + include: { + programa: { include: { cliente: { include: { usuario: true } } } }, + }, + }); +} + +// Tras marcar un cobro como VERIFICADO en el panel admin. +export async function notificarVerificacion(pagoId: string): Promise { + try { + const pago = await cargarPago(pagoId); + if (!pago || pago.estado !== ESTADOS_PAGO.VERIFICADO) return; + const programa = pago.programa as unknown as ProgramaConCliente; + const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email); + const userId = programa.cliente.usuario?.id ?? null; + if (!destino && !userId) return; + + const titulo = `Pago verificado: ${programa.concepto}`; + const cuerpo = ` +

    Hola ${programa.cliente.nombre},

    +

    Tu pago corresponde al ${formatFechaCobro(pago.fecha)} por + ${pago.monto.toLocaleString("es-MX", { style: "currency", currency: programa.moneda })} + fue verificado. Ya aparece como liquidado en tu panel.

    `; + + await avisar( + userId, + destino, + titulo, + plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }), + `${programa.concepto}: pago del ${formatFechaCorta(pago.fecha)} verificado.`, + { + titulo: "Pago verificado ✓", + cuerpo: `${programa.concepto} — ${formatFechaCorta(pago.fecha)}`, + url: "/cliente/pagos", + } + ); + } catch (e) { + console.error("[notificaciones] fallo al avisar verificacion", pagoId, e); + } +} + +// Tras RECHAZAR el comprobante (el archivo ya se borro del servidor). +export async function notificarRechazo(pagoId: string, motivo: string): Promise { + try { + const pago = await cargarPago(pagoId); + if (!pago) return; + const programa = pago.programa as unknown as ProgramaConCliente; + const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email); + const userId = programa.cliente.usuario?.id ?? null; + if (!destino && !userId) return; + + const titulo = `Comprobante rechazado: ${programa.concepto}`; + const cuerpo = ` +

    Hola ${programa.cliente.nombre},

    +

    Rechazamos el comprobante del pago ${formatFechaCobro(pago.fecha)} + (${programa.concepto}).

    + ${motivo ? `

    Motivo: ${motivo}

    ` : ""} +

    Puedes volver a subir un comprobante desde el panel.

    `; + + await avisar( + userId, + destino, + titulo, + plantilla(titulo, cuerpo, { texto: "Subir otro comprobante", url: PANEL_PAGOS }), + `${programa.concepto}: comprobante del ${formatFechaCorta(pago.fecha)} rechazado. ${motivo || ""}`.trim(), + { + titulo: "Comprobante rechazado", + cuerpo: `${programa.concepto} — ${formatFechaCorta(pago.fecha)}. Motivo: ${motivo || "sin detalle"}`, + url: "/cliente/pagos", + } + ); + } catch (e) { + console.error("[notificaciones] fallo al avisar rechazo", pagoId, e); + } +} diff --git a/src/lib/push.ts b/src/lib/push.ts new file mode 100644 index 0000000..829b286 --- /dev/null +++ b/src/lib/push.ts @@ -0,0 +1,85 @@ +import webpush from "web-push"; +import { prisma } from "@/lib/db"; + +// Web Push (VAPID). Requiere VAPID_PUBLIC_KEY y VAPID_PRIVATE_KEY en el entorno: +// node -e "console.log(require('web-push').generateVAPIDKeys())" +// Sin claves, las funciones se omiten con aviso (la app no debe tumbarse). +// La llave publica se entrega al panel cliente via GET /api/cliente/push/config. + +export interface ResultadoPush { + ok: boolean; + omitido?: boolean; + error?: string; + enviadas?: number; +} + +function claves(): { publica: string; privada: string } | null { + const publica = process.env.VAPID_PUBLIC_KEY; + const privada = process.env.VAPID_PRIVATE_KEY; + if (!publica || !privada) return null; + return { publica, privada }; +} + +export function pushConfigurado(): boolean { + return Boolean(claves()); +} + +export function llavePublicaPush(): string | null { + return claves()?.publica ?? null; +} + +let vapidListo = false; + +function asegurarVapid() { + if (vapidListo) return; + const k = claves(); + if (!k) return; + webpush.setVapidDetails( + "mailto:" + (process.env.VAPID_SUBJECT || process.env.SMTP_FROM || "admin@localhost"), + k.publica, + k.privada + ); + vapidListo = true; +} + +// Envia una notificacion push a TODAS las suscripciones del usuario. +// Los endpoints muertos (404/410) se purgan en el intento. +export async function enviarPush( + userId: string, + payload: { titulo: string; cuerpo: string; url?: string } +): Promise { + const k = claves(); + if (!k) { + console.warn("[push] VAPID no configurado; se omite la notificacion a", userId); + return { ok: false, omitido: true }; + } + asegurarVapid(); + + const subs = await prisma.suscripcionPush.findMany({ where: { userId } }); + if (subs.length === 0) return { ok: true, enviadas: 0 }; + + const body = JSON.stringify(payload); + let enviadas = 0; + let fallo: string | undefined; + + for (const sub of subs) { + try { + await webpush.sendNotification( + { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } }, + body + ); + enviadas++; + } catch (e) { + const status = (e as { statusCode?: number }).statusCode; + if (status === 404 || status === 410) { + // Suscripcion invalidada por el navegador: limpiarla. + await prisma.suscripcionPush.delete({ where: { id: sub.id } }).catch(() => {}); + } else { + fallo = e instanceof Error ? e.message : String(e); + console.error("[push] fallo el envio a", sub.endpoint.slice(0, 60), "-", fallo); + } + } + } + + return { ok: enviadas > 0 || !fallo, enviadas, error: fallo }; +} diff --git a/src/lib/scheduler.ts b/src/lib/scheduler.ts new file mode 100644 index 0000000..575ca74 --- /dev/null +++ b/src/lib/scheduler.ts @@ -0,0 +1,53 @@ +import { generarCobros } from "@/lib/cobros"; +import { notificarCobrosNuevos } from "@/lib/notificaciones"; + +/** + * Scheduler automático de cobros recurrentes. + * + * Qué hace: cada hora genera de forma idempotente los cobros recurrentes + * vencidos (src/lib/cobros.ts opera en la zona America/Mexico_City) y, si se + * creó alguno, notifica a los clientes afectados por correo + push + * (src/lib/notificaciones.ts, best-effort). + * + * Por qué cada hora (y no diario): el servidor puede estar en UTC, así que un + * cobro que vence un sábado en México se emite apenas empieza el sábado en + * México (aprox. 06:00 UTC), sin esperar al día siguiente. La generación es + * idempotente: aunque el proceso reinicie, no se duplican periodos. + * + * Este módulo solo se importa desde src/instrumentation.ts dentro del guard + * de runtime nodejs — nunca debe entrar al bundle de edge ni al navegador. + * + * El guard en globalThis evita timers duplicados con HMR o reinicios. + */ +export function iniciarSchedulerCobros(): void { + const g = globalThis as unknown as { __cotizadorSchedulerActivo?: boolean }; + if (g.__cotizadorSchedulerActivo) return; + g.__cotizadorSchedulerActivo = true; + + const PRIMERA_EJECUCION_MS = 20_000; // dar tiempo a que la BD esté lista al arrancar + const INTERVALO_MS = 60 * 60 * 1000; // cada 60 minutos + + async function ejecutar(): Promise { + try { + const creados = await generarCobros(); + if (creados.length) { + await notificarCobrosNuevos(creados); + } + console.log(`[cobros-scheduler] ${creados.length} cobros nuevos`); + } catch (e) { + console.error("[cobros-scheduler] error", e); + } + } + + // Nunca una promesa sin catch: ejecutar() ya trae try/catch interno total, + // pero setInterval/setTimeout no await, así que encadenamos .catch igual. + setTimeout(() => { + void ejecutar().catch((e) => console.error("[cobros-scheduler] error", e)); + }, PRIMERA_EJECUCION_MS); + + setInterval(() => { + void ejecutar().catch((e) => console.error("[cobros-scheduler] error", e)); + }, INTERVALO_MS); + + console.log("[cobros-scheduler] scheduler activo (primera ejecución en 20s, luego cada 60 min)"); +} diff --git a/src/lib/schemas.ts b/src/lib/schemas.ts index 25c10bd..3f72248 100644 --- a/src/lib/schemas.ts +++ b/src/lib/schemas.ts @@ -137,3 +137,80 @@ export function validateOrError( if (result.success) return result.data; return { error: result.error.issues.map((i) => i.message).join(", ") }; } + +// ============================================================================ +// Cobros recurrentes (Frente A: modulo admin) +// ============================================================================ + +const fechaISO = z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, "Fecha invalida (se espera YYYY-MM-DD)"); + +const FRECUENCIAS = ["semanal", "quincenal", "mensual"] as const; + +// Reglas condicionales de la frecuencia. Se comparten entre create y patch +// (en patch los campos opcionales se completan con los valores previos antes +// de validar, via `valoresFrecuencia`). +function erroresFrecuencia( + frecuencia: string, + diaSemana: number | null | undefined, + diaMes: number | null | undefined, + addIssue: (path: (string | number)[], message: string) => void +) { + if (frecuencia === "semanal" && (diaSemana === null || diaSemana === undefined)) { + addIssue(["diaSemana"], "Para frecuencia semanal se requiere diaSemana (0-6)"); + } + if (frecuencia === "mensual" && (diaMes === null || diaMes === undefined)) { + addIssue(["diaMes"], "Para frecuencia mensual se requiere diaMes (1-31)"); + } +} + +export const programaPagoSchema = z + .object({ + clienteId: z.string().min(1, "El cliente es requerido"), + cotizacionId: z.string().min(1).optional(), + concepto: z.string().min(1, "El concepto es requerido"), + monto: z.number().positive("El monto debe ser mayor a 0"), + frecuencia: z.enum(FRECUENCIAS, { message: "Frecuencia invalida" }), + diaSemana: z.number().int().min(0).max(6).optional(), + diaMes: z.number().int().min(1).max(31).optional(), + fechaInicio: fechaISO, + fechaFin: fechaISO.optional(), + }) + .superRefine((val, ctx) => { + erroresFrecuencia( + val.frecuencia, + val.diaSemana, + val.diaMes, + (path, message) => ctx.addIssue({ code: "custom", path, message }) + ); + }); + +export const programaPagoPatchSchema = z + .object({ + concepto: z.string().min(1, "El concepto es requerido").optional(), + monto: z.number().positive("El monto debe ser mayor a 0").optional(), + frecuencia: z.enum(FRECUENCIAS, { message: "Frecuencia invalida" }).optional(), + diaSemana: z.number().int().min(0).max(6).optional(), + diaMes: z.number().int().min(1).max(31).optional(), + fechaInicio: fechaISO.optional(), + fechaFin: fechaISO.nullable().optional(), + activo: z.boolean().optional(), + cotizacionId: z.string().min(1).nullable().optional(), + }) + .superRefine((val, ctx) => { + // En un patch parcial los campos de dia pueden no venir: la condicion solo + // aplica si trae frecuencia (si no, el handler combina con el registro previo). + if (!val.frecuencia) return; + erroresFrecuencia( + val.frecuencia, + val.diaSemana, + val.diaMes, + (path, message) => ctx.addIssue({ code: "custom", path, message }) + ); + }); + +export const accesoClienteSchema = z.object({ + email: z.string().email("Email invalido"), + password: z.string().min(6, "La contrasena debe tener al menos 6 caracteres"), +}); diff --git a/src/lib/uploads.ts b/src/lib/uploads.ts new file mode 100644 index 0000000..bb251b5 --- /dev/null +++ b/src/lib/uploads.ts @@ -0,0 +1,138 @@ +import { randomUUID } from "crypto"; +import { mkdir, unlink, writeFile, stat } from "fs/promises"; +import path from "path"; +import sharp from "sharp"; + +// Almacenamiento de comprobantes de pago (imagenes o PDF) fuera de /public: +// los archivos solo se sirven por un route handler autenticado. +// +// UPLOAD_DIR/uploads (por defecto /uploads) <- en Coolify es un volumen +// comprobantes//.webp|pdf +// +// Las imagenes se normalizan a WebP (calidad aceptable, tamano razonable) con +// limite de ancho; los PDF se guardan tal cual. + +const MAX_BYTES = 10 * 1024 * 1024; // 10 MB del archivo original +const MAX_ANCHO = 1920; +const MIME_IMAGENES = new Set(["image/jpeg", "image/png", "image/webp", "image/heic", "image/heif"]); +const MIME_PDF = "application/pdf"; + +export interface GuardadoComprobante { + ruta: string; // relativa a UPLOAD_DIR (clave de ComprobantePago.archivoRuta) + mime: string; // image/webp | application/pdf + tamano: number; // bytes finales en disco + nombreOriginal: string; +} + +export class ErrorUpload extends Error { + constructor(message: string) { + super(message); + this.name = "ErrorUpload"; + } +} + +export function directorioUploads(): string { + // turbopackIgnore: sin esto NFT tracer sigue process.cwd() y "traza" el + // proyecto completo (next.config.ts y demas) al bundle de esta ruta. + return process.env.UPLOAD_DIR || path.join(/*turbopackIgnore: true*/ process.cwd(), "uploads"); +} + +export function esImagen(mime: string): boolean { + return MIME_IMAGENES.has(mime); +} + +export function esPdf(mime: string): boolean { + return mime === MIME_PDF; +} + +export function esComprobantePermitido(mime: string): boolean { + return esImagen(mime) || esPdf(mime); +} + +// Convierte un File de FormData a disco. Lanza ErrorUpload con mensaje en +// espanol si el archivo no es permitido o excede el limite. +export async function guardarComprobante(pagoId: string, file: File): Promise { + if (!file || file.size === 0) throw new ErrorUpload("Debes seleccionar un archivo."); + if (file.size > MAX_BYTES) { + throw new ErrorUpload(`El archivo supera el limite de ${Math.round(MAX_BYTES / 1024 / 1024)} MB.`); + } + if (!esComprobantePermitido(file.type)) { + throw new ErrorUpload("Solo se aceptan imagenes (JPG, PNG, WebP) o PDF."); + } + + const original = Buffer.from(await file.arrayBuffer()); + // La ruta SE ALMACENA con separadores posix aunque el dev corra en Windows: + // los registros viajan a produccion (Linux) y alli un "\" no resuelve nada. + const subdir = "comprobantes/" + pagoId; + const absSubdir = path.join(directorioUploads(), "comprobantes", pagoId); + await mkdir(absSubdir, { recursive: true }); + + let bytes: Buffer; + let ext: string; + let mime: string; + + if (esImagen(file.type)) { + try { + bytes = await sharp(original) + .rotate() // respeta orientacion EXIF + .resize({ width: MAX_ANCHO, withoutEnlargement: true }) + .webp({ quality: 80, effort: 4 }) + .toBuffer(); + } catch { + throw new ErrorUpload("No se pudo procesar la imagen. Prueba con JPG o PNG."); + } + ext = "webp"; + mime = "image/webp"; + } else { + bytes = original; + ext = "pdf"; + mime = MIME_PDF; + } + + const nombre = `${randomUUID()}.${ext}`; + const abs = path.join(absSubdir, nombre); + await writeFile(abs, bytes); + + return { + ruta: `${subdir}/${nombre}`, + mime, + tamano: bytes.length, + nombreOriginal: file.name || nombre, + }; +} + +// Borra el archivo del disco (rechazo del admin). Devuelve true si existia. +// Cualquier ruta que intente salir de UPLOAD_DIR se rechaza. +export async function eliminarComprobante(rutaRelativa: string): Promise { + const abs = rutaAbsoluta(rutaRelativa); + if (!abs) return false; + try { + await unlink(abs); + return true; + } catch { + return false; + } +} + +// Resuelve una ruta relativa a una absoluta DENTRO de UPLOAD_DIR; null si es +// invalida o intenta escapar (path traversal). +export function rutaAbsoluta(rutaRelativa: string): string | null { + if (!rutaRelativa) return null; + const base = directorioUploads(); + const abs = path.resolve(base, rutaRelativa); + const rel = path.relative(base, abs); + if (rel.startsWith("..") || path.isAbsolute(rel)) return null; + return abs; +} + +// Verifica que el archivo siga en disco y devuelve su tamano. +export async function archivoExiste(rutaRelativa: string): Promise { + const abs = rutaAbsoluta(rutaRelativa); + if (!abs) return false; + try { + const s = await stat(abs); + return s.isFile(); + } catch { + return false; + } +} diff --git a/src/middleware.ts b/src/middleware.ts index 471978f..b2d4ed9 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -6,13 +6,38 @@ const PUBLIC_PATHS = [ "/api/auth/login", "/api/auth/logout", "/api/health", + // El service worker debe poder cargarse sin sesion: el navegador lo pide + // fuera del contexto de la pagina autenticada. + "/sw.js", ]; +// Prefijos a los que SOLO el rol "cliente" tiene acceso. +const CLIENTE_PATHS = ["/cliente", "/api/cliente"]; + +// Rutas autenticadas a las que acceden AMBOS roles; la pertenencia (cliente +// dueño de la cotizacion/comprobante) se valida dentro del route handler. +const RUTAS_COMPARTIDAS = ["/api/comprobantes", "/api/export/pdf"]; + +function isClientePath(pathname: string): boolean { + return CLIENTE_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/")); +} + +function esRutaCompartida(pathname: string): boolean { + return RUTAS_COMPARTIDAS.some((p) => pathname === p || pathname.startsWith(p + "/")); +} + +function deny(request: NextRequest, pathname: string, message: string, destinoPagina: string): NextResponse { + if (pathname.startsWith("/api/")) { + return NextResponse.json({ error: message }, { status: 403 }); + } + return NextResponse.redirect(new URL(destinoPagina, request.url)); +} + export async function middleware(request: NextRequest) { const { pathname } = request.nextUrl; const isPublic = - PUBLIC_PATHS.some((p) => pathname.startsWith(p)) || + PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/")) || pathname.startsWith("/_next") || pathname === "/favicon.ico"; @@ -25,7 +50,9 @@ export async function middleware(request: NextRequest) { if (isApi) { return NextResponse.json({ error: "No autenticado" }, { status: 401 }); } - return NextResponse.redirect(new URL("/login", request.url)); + // El panel de cliente tiene su propia ruta de entrada. + const destino = isClientePath(pathname) ? "/login?panel=cliente" : "/login"; + return NextResponse.redirect(new URL(destino, request.url)); } const session = await verifySession(token); @@ -40,9 +67,24 @@ export async function middleware(request: NextRequest) { return response; } + const rol = session.role || "asesor"; + const esCliente = rol === "cliente"; + + // Separacion de paneles: cliente no ve nada del admin y viceversa, + // salvo las rutas compartidas donde el handler valida la pertenencia. + if (esCliente && !isClientePath(pathname) && !esRutaCompartida(pathname)) { + // Cliente colado en rutas del admin: devolverlo a su panel. + return deny(request, pathname, "Acceso restringido al panel de cliente", "/cliente"); + } + if (!esCliente && isClientePath(pathname)) { + // Staff abriendo el panel de cliente: volver a su dashboard. + return deny(request, pathname, "Acceso restringido al panel de clientes", "/"); + } + const requestHeaders = new Headers(request.headers); requestHeaders.set("x-user-id", session.userId); - requestHeaders.set("x-user-role", session.role || "asesor"); + requestHeaders.set("x-user-role", rol); + if (session.clienteId) requestHeaders.set("x-cliente-id", session.clienteId); return NextResponse.next({ request: { headers: requestHeaders },