From 459a007596bda68cdf95a4958a6cbbb5a172f25f Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 13 Oct 2026 09:31:21 -0600 Subject: [PATCH] feat(auth): actualizar registro con fecha de nacimiento, clave min 6 chars y restablecimiento por correo --- package-lock.json | 16 +- package.json | 1 + public/agenda_structured_app.html | 878 ++++++++++++++++++++++++++++ public/app_carousel_mockup.html | 938 ++++++++++++++++++++++++++++++ public/index.html | 88 ++- public/js/app.js | 180 +++++- public/structured_demo.html | 627 ++++++++++++++++++++ server/db.js | 24 +- server/emailService.js | 75 +++ server/server.js | 123 +++- 10 files changed, 2919 insertions(+), 31 deletions(-) create mode 100644 public/agenda_structured_app.html create mode 100644 public/app_carousel_mockup.html create mode 100644 public/structured_demo.html create mode 100644 server/emailService.js diff --git a/package-lock.json b/package-lock.json index 6ac599d..bd08005 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "imap-simple": "^5.1.0", "jsqr": "^1.4.0", "mailparser": "^3.9.36", + "nodemailer": "^10.1.0", "pg": "^8.23.1", "puppeteer-core": "^25.12.0", "qrcode": "^1.5.4", @@ -1391,6 +1392,15 @@ "node": ">=20.0.0" } }, + "node_modules/mailparser/node_modules/nodemailer": { + "version": "10.0.14", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.14.tgz", + "integrity": "sha512-eJoLFKg55fesSlzUekmfOv/SBXh4KUYT8oiQc2RLP0tfG0rbNMJBK7wgHJwXTJwqyKlSJMz9UzDZ4v+aHEvo8g==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1541,9 +1551,9 @@ "license": "MIT" }, "node_modules/nodemailer": { - "version": "10.0.14", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.14.tgz", - "integrity": "sha512-eJoLFKg55fesSlzUekmfOv/SBXh4KUYT8oiQc2RLP0tfG0rbNMJBK7wgHJwXTJwqyKlSJMz9UzDZ4v+aHEvo8g==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.0.tgz", + "integrity": "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg==", "license": "MIT-0", "engines": { "node": ">=20.0.0" diff --git a/package.json b/package.json index a0415b3..16f8d40 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "imap-simple": "^5.1.0", "jsqr": "^1.4.0", "mailparser": "^3.9.36", + "nodemailer": "^10.1.0", "pg": "^8.23.1", "puppeteer-core": "^25.12.0", "qrcode": "^1.5.4", diff --git a/public/agenda_structured_app.html b/public/agenda_structured_app.html new file mode 100644 index 0000000..a9dc682 --- /dev/null +++ b/public/agenda_structured_app.html @@ -0,0 +1,878 @@ + + + + + + Structured Flow — App de Agenda y Recordatorios Visuales + + + + + + +
+
+
+ ⚡ +
+
+
+ flow + + Agenda & Recordatorios • Estilo Structured + +
+

Timeline visual de tareas y carrusel de rutinas en colores pastel

+
+
+ + +
+ +
+ Fondo: + + + + + + +
+ + + +
+
+ + +
+ + +
+ + +
+ + +
+ 9:41 + + +
+
+ flow app +
+
+ +
+ +
+
+
+
+
+ + +
+ + +
+
+ + viernes, 10 de octubre + +

+ mi agenda de hoy +

+
+ + +
+
+ 50% +
+
+ completado + 2 de 4 +
+
+
+ + +
+ + + + + +
+ + + + +
+
+
+ plantillas & hábitos +

+ rutinas conectadas +

+
+ + +
+ + +
+
+ + +
+
+ + +
+
+
+
+ 🌅 +
+ hábito diario +
+ + 45 min + +
+ +
+

+ rutina mañanera +

+

+ café, 10 min meditación y journaling +

+
+ +
+ 07:00 am + +
+
+ + +
+ + + + + +
+ + +
+
+
+
+ ⚡ +
+ productividad +
+ + 90 min + +
+ +
+

+ enfoque profundo (deep work) +

+

+ cero notificaciones, proyecto principal +

+
+ +
+ 10:00 am + +
+
+ + +
+ + + + + +
+ + +
+
+
+
+ 🏃‍♂️ +
+ bienestar +
+ + 60 min + +
+ +
+

+ sesión de entrenamiento +

+

+ rutina funcional y estiramiento activo +

+
+ +
+ 05:30 pm + +
+
+ + +
+ + + + + +
+ + +
+
+
+
+ 🌙 +
+ descanso +
+ + 30 min + +
+ +
+

+ rutina de descanso +

+

+ cero pantallas, preparar el día de mañana +

+
+ +
+ 09:30 pm + +
+
+ +
+
+ + +
+ + + + +
+
+ + + + +
+
+
+ línea de tiempo +

+ timeline del día +

+
+ + toca el círculo para tachar + +
+ + +
+ + +
+ + +
+ +
+ +
+
+ ☕ +
+
+
+ 07:30 am • 30m +
+
+ desayuno & planificar el día +
+

revisar prioridades y tomar café

+
+
+ + +
+ ✓ +
+
+ + +
+
+ +
+
+ 💼 +
+
+
+ 09:00 am • 45m +
+
+ daily sprint con el equipo +
+

revisión de avances del prototipo

+
+
+ +
+ ✓ +
+
+ + +
+
+ +
+
+ 💻 +
+
+
+ 10:00 am • 90m + en curso +
+
+ diseño de la arquitectura & api +
+

bloque de concentración profunda

+
+
+ +
+ ✓ +
+
+ + +
+ ⏱️ 1h libre para descanso y caminata +
+ + +
+
+ +
+
+ 🥗 +
+
+
+ 01:00 pm • 60m +
+
+ almuerzo saludable & lectura +
+

desconectarse de pantallas

+
+
+ +
+ ✓ +
+
+ +
+
+ +
+ + +
+
+ + + + + + + + + + + + + + + +
+
+ + +
+ + +
+ ¡Rutina añadida a tu agenda! + ✓ +
+ +
+
+ + +
+ + +
+
+ ✨ App Independiente de Agenda & Recordatorios +
+ +

+ ¿cómo funciona esta app de recordatorios? +

+ +

+ Esta aplicación adopta el concepto exacto de Structured: transformar listas de tareas aburridas en una línea de tiempo visual con colores pasteles, donde cada momento de tu día tiene un espacio claro y conectado. +

+ +
+
+ 🧩 +
+ 1. carrusel de rutinas con conectores puzzle +

Las cápsulas del carrusel son plantillas de hábitos frecuentes (rutina mañanera, deep work, gym). Al tocar cualquiera, se inserta directo en tu timeline.

+
+
+ +
+ 🕒 +
+ 2. timeline visual interactivo +

Cada tarea tiene su horario y duración. Puedes tocar el círculo verde para marcarla como completada y ver cómo avanza tu porcentaje del día.

+
+
+ +
+ 🎨 +
+ 3. paleta pastel relajante +

Usa los colores suaves de SiboPay (Cielo, Menta, Melocotón, Lavanda, Vainilla) que reducen el estrés visual característico de Structured.

+
+
+
+
+ + +
+

+ acciones interactivas de prueba +

+ +
+ + + + +
+
+ +
+ +
+ + +
+
+ +
+

nueva tarea o recordatorio

+ +
+ + +
+ + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + + + + +
+
+ + +
+ +
+ + + + + + +
+
+ + +
+ +
+ +
+
+ + + + + diff --git a/public/app_carousel_mockup.html b/public/app_carousel_mockup.html new file mode 100644 index 0000000..bc71eb5 --- /dev/null +++ b/public/app_carousel_mockup.html @@ -0,0 +1,938 @@ + + + + + + SiboPay — Carrusel Estilo Structured en la App + + + + + + +
+
+
+ S +
+
+
+ sibopay + + Diseño In-App • Structured + +
+

Así luce el carrusel de cápsulas y conectores dentro de la pantalla del celular

+
+
+ + +
+ +
+ Fondo App: + + + + + + +
+ + +
+ + +
+ + + +
+
+ + +
+ + +
+ + +
+ + +
+ 9:41 + + +
+
+ sibopay +
+
+ +
+ + +
+
+
+
+
+ + +
+ + +
+
+
+ Avatar +
+
+
+
+ colegio saint paul + • + 2° A +
+

+ hola, mateo 👋 +

+
+
+ + +
+ saldo disponible + ₡14.500 +
+
+ + +
+ + + + + +
+ + + + +
+
+
+ combos & promociones +

+ destacados del día +

+
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+
+
+ 🥪 +
+ + recreo 1 • 09:30 am + +
+ + popular + +
+ + +
+

+ sandwich artesanal & jugo +

+

+ jamón de pavo, queso suizo y jugo de naranja +

+
+ + +
+
+ ₡ + 1.850 +
+ +
+
+ + +
+ + + + + + + + +
+ + +
+ +
+
+
+ ⚡ +
+ + sinpe móvil directo + +
+ + inmediato + +
+ + +
+

+ recarga de saldo en 1 toque +

+

+ acreditación sin comisión al número 8888-7777 +

+
+ + +
+
+ 0% comisiones +
+ +
+
+ + +
+ + + + + +
+ + +
+ +
+
+
+ 🍛 +
+ + almuerzo • 11:45 am + +
+ + menú chef + +
+ + +
+

+ casado completo con pollo +

+

+ arroz, frijoles, plátano maduro, ensalada y té frío +

+
+ + +
+
+ ₡ + 2.600 +
+ +
+
+ + +
+ + + + + +
+ + +
+ +
+
+
+ 📢 +
+ + aviso cafeteria + +
+ + especial + +
+ + +
+

+ viernes de pizza horneada +

+

+ pre-órdenes abiertas hasta el jueves 4:00 pm +

+
+ + +
+ + cupos 48/80 + + +
+
+ + +
+ + + + + +
+ + +
+ +
+
+
+ 🍎 +
+ + snack saludable + +
+ + 100% natural + +
+ + +
+

+ bowl de frutas & miel +

+

+ fresas, banano, piña, yogurt griego y avena +

+
+ + +
+
+ ₡ + 1.200 +
+ +
+
+ +
+
+ + +
+ + + + + +
+
+ + + + +
+
+

+ accesos directos +

+ toca para abrir +
+ +
+ +
+
+ ⚡ +
+ recarga +
+ + +
+
+ 📱 +
+ mi qr +
+ + +
+
+ 🥪 +
+ menú +
+ + +
+
+ ❤️ +
+ nutrición +
+
+
+ + + + +
+
+
+ horario estructurado +

+ timeline de hoy +

+
+ + 4 eventos + +
+ + +
+ +
+ + +
+
+
+
+ 🥛 +
+
+
desayuno ligero
+

07:15 am • cafetería principal

+
+
+ completado +
+ + +
+
+
+
+ 🥪 +
+
+
+
primer recreo: retiro combo
+ +
+

09:30 am • ventanilla rápida #2

+
+
+ en curso +
+ + +
+
+
+
+ 🍛 +
+
+
almuerzo en comedor
+

11:45 am • casado con pollo

+
+
+ reservado +
+ + +
+
+
+
+ 🍎 +
+
+
segundo recreo: snack
+

01:45 pm • bowl de frutas

+
+
+ pendiente +
+
+
+ +
+ + +
+
+ + + + + + + + + + + + + + + +
+
+ + +
+ + +
+ ¡Pre-orden agregada con éxito! + ✓ +
+ +
+
+ + +
+ + +
+
+ ✨ Claves del Diseño Structured en la App +
+ +

+ ¿por qué se ve exactamente como structured? +

+ +

+ Structured destaca por tres elementos gráficos inconfundibles que fueron trasladados a la escala real de una pantalla móvil (390px): +

+ +
+ +
+ 🧩 +
+ 1. conectores de rompecabezas vectoriales +

En lugar de tarjetas sueltas, cada cápsula se encaja con la siguiente mediante juntas de rompecabezas con colores que coinciden exactamente con ambas tarjetas.

+
+
+ + +
+ 🎨 +
+ 2. paleta pastel de alto contraste +

Cielo SiboPay (#e0f2fe), Menta (#d1fae5), Melocotón (#ffedd5) y Lavanda con texto legible y oscuro.

+
+
+ + +
+ 📱 +
+ 3. snap swipe + micro-interacciones +

El usuario puede deslizar con el dedo en el móvil (touch snap) y cada combo se pre-ordena con un solo toque, sincronizado con el timeline escolar del día.

+
+
+
+
+ + +
+

+ acciones interactivas para probar ahora +

+ +
+ + + + +
+
+ +
+ +
+ + +
+
+
+ ⚡ +
+

recarga rápida sinpe móvil

+

Envía tu comprobante al 8888-7777 o digita el monto a abonar a la cuenta de Mateo.

+ +
+ + + +
+ +
+ + +
+
+
+ + + + + diff --git a/public/index.html b/public/index.html index e29296b..481b0f7 100644 --- a/public/index.html +++ b/public/index.html @@ -79,11 +79,15 @@ -
+ +
+ +
+ +

@@ -127,15 +131,15 @@ - + +
+ + +
+
- - + +
@@ -162,14 +171,14 @@ @@ -180,6 +189,67 @@

+ + + diff --git a/public/js/app.js b/public/js/app.js index c68e0bd..ab854f1 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -332,15 +332,29 @@ function closeLoginSheet(e) { function switchSheetView(view) { const loginContent = document.getElementById('sheetContentLogin'); const registerContent = document.getElementById('sheetContentRegister'); + const forgotContent = document.getElementById('sheetContentForgot'); const title = document.getElementById('bottomSheetTitle'); + if (loginContent) loginContent.style.display = 'none'; + if (registerContent) registerContent.style.display = 'none'; + if (forgotContent) forgotContent.style.display = 'none'; + if (view === 'register') { - if (loginContent) loginContent.style.display = 'none'; if (registerContent) registerContent.style.display = 'block'; - if (title) title.textContent = 'Registro de Padres'; + if (title) title.textContent = 'Crear Cuenta'; + } else if (view === 'forgot') { + if (forgotContent) forgotContent.style.display = 'block'; + if (title) title.textContent = 'Restablecer Contraseña'; + const step1 = document.getElementById('forgotStep1'); + const step2 = document.getElementById('forgotStep2'); + if (step1) step1.style.display = 'block'; + if (step2) step2.style.display = 'none'; + const msg1 = document.getElementById('forgotMsgStep1'); + if (msg1) msg1.style.display = 'none'; + const msg2 = document.getElementById('forgotMsgStep2'); + if (msg2) msg2.style.display = 'none'; } else { if (loginContent) loginContent.style.display = 'block'; - if (registerContent) registerContent.style.display = 'none'; if (title) title.textContent = 'Iniciar Sesión'; } } @@ -407,6 +421,8 @@ function selectRegisterRole(role) { async function handleRegisterPadreSubmit(event) { if (event) event.preventDefault(); const nombre = document.getElementById('regNombre').value.trim(); + const fechaNacInput = document.getElementById('regFechaNacimiento'); + const fecha_nacimiento = fechaNacInput ? fechaNacInput.value.trim() : ''; const telefono = document.getElementById('regTelefono').value.trim(); const emailInput = document.getElementById('regEmail'); const email = emailInput ? emailInput.value.trim() : ''; @@ -416,14 +432,31 @@ async function handleRegisterPadreSubmit(event) { const btnSubmit = document.getElementById('btnRegisterSubmit'); if (errorMsg) errorMsg.style.display = 'none'; + + if (!email) { + if (errorMsg) { + errorMsg.textContent = 'El correo electrónico es requerido.'; + errorMsg.style.display = 'block'; + } + return; + } + + if (password.length < 6) { + if (errorMsg) { + errorMsg.textContent = 'La contraseña debe tener al menos 6 caracteres.'; + errorMsg.style.display = 'block'; + } + return; + } + btnSubmit.disabled = true; - btnSubmit.textContent = 'Creando cuenta de padre...'; + btnSubmit.textContent = 'Creando cuenta...'; try { const res = await fetch('/api/auth/register-padre', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ nombre, telefono, email, username, password }) + body: JSON.stringify({ nombre, fecha_nacimiento, telefono, email, username, password }) }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Error al registrar la cuenta'); @@ -440,7 +473,7 @@ async function handleRegisterPadreSubmit(event) { if (window.sounds) window.sounds.playSuccess(); await showAppAlert({ title: '¡Bienvenido(a) a SiboPay!', - message: `Hola ${data.user.nombre}, tu cuenta de padre fue creada exitosamente.\n\nYa puedes vincular a tus hijos, asignar límites diarios y realizar recargas por SINPE Móvil de forma segura.`, + message: `Hola ${data.user.nombre}, tu cuenta fue creada exitosamente.\n\nYa puedes acceder a todos los servicios y monedero digital SiboPay.`, type: 'success', confirmText: 'Entrar a mi Panel' }); @@ -453,7 +486,140 @@ async function handleRegisterPadreSubmit(event) { if (window.sounds) window.sounds.playError(); } finally { btnSubmit.disabled = false; - btnSubmit.innerHTML = ' Crear Cuenta de Padre y Entrar'; + btnSubmit.innerHTML = ' Crear Cuenta y Entrar'; + } +} + +let pendingForgotEmail = ''; + +async function handleForgotRequestSubmit(event) { + if (event) event.preventDefault(); + const emailInput = document.getElementById('forgotEmail'); + const email = emailInput ? emailInput.value.trim() : ''; + const msg = document.getElementById('forgotMsgStep1'); + const btn = document.getElementById('btnForgotSendCode'); + + if (!email) return; + if (msg) msg.style.display = 'none'; + btn.disabled = true; + btn.innerHTML = '⏳ Enviando código...'; + + try { + const res = await fetch('/api/auth/forgot-password', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'No se pudo enviar el código de recuperación.'); + + pendingForgotEmail = email; + document.getElementById('forgotStep1').style.display = 'none'; + document.getElementById('forgotStep2').style.display = 'block'; + + const msg2 = document.getElementById('forgotMsgStep2'); + if (msg2) { + msg2.textContent = `Código enviado a ${email}. Revisa tu bandeja de entrada o spam e ingrésalo abajo.`; + msg2.style.background = '#dcfce7'; + msg2.style.borderColor = '#86efac'; + msg2.style.color = '#166534'; + msg2.style.border = '1px solid #86efac'; + msg2.style.display = 'block'; + } + const inputCode = document.getElementById('forgotCode'); + if (inputCode) inputCode.focus(); + } catch (err) { + if (msg) { + msg.textContent = err.message; + msg.style.background = '#fee2e2'; + msg.style.borderColor = '#fca5a5'; + msg.style.color = '#991b1b'; + msg.style.border = '1px solid #fca5a5'; + msg.style.display = 'block'; + } + if (window.sounds) window.sounds.playError(); + } finally { + btn.disabled = false; + btn.innerHTML = ' Enviar Código al Correo'; + } +} + +async function handleForgotConfirmSubmit(event) { + if (event) event.preventDefault(); + const email = pendingForgotEmail || (document.getElementById('forgotEmail') ? document.getElementById('forgotEmail').value.trim() : ''); + const code = document.getElementById('forgotCode') ? document.getElementById('forgotCode').value.trim() : ''; + const newPass = document.getElementById('forgotNewPass') ? document.getElementById('forgotNewPass').value.trim() : ''; + const confirmPass = document.getElementById('forgotConfirmPass') ? document.getElementById('forgotConfirmPass').value.trim() : ''; + const msg = document.getElementById('forgotMsgStep2'); + const btn = document.getElementById('btnForgotResetPass'); + + if (msg) msg.style.display = 'none'; + + if (newPass.length < 6) { + if (msg) { + msg.textContent = 'La nueva contraseña debe tener al menos 6 caracteres.'; + msg.style.background = '#fee2e2'; + msg.style.borderColor = '#fca5a5'; + msg.style.color = '#991b1b'; + msg.style.border = '1px solid #fca5a5'; + msg.style.display = 'block'; + } + return; + } + + if (newPass !== confirmPass) { + if (msg) { + msg.textContent = 'Las contraseñas no coinciden. Por favor verifícalas.'; + msg.style.background = '#fee2e2'; + msg.style.borderColor = '#fca5a5'; + msg.style.color = '#991b1b'; + msg.style.border = '1px solid #fca5a5'; + msg.style.display = 'block'; + } + return; + } + + btn.disabled = true; + btn.innerHTML = '⏳ Guardando nueva contraseña...'; + + try { + const res = await fetch('/api/auth/reset-password', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email, code, new_password: newPass }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Error al restablecer la contraseña.'); + + if (window.sounds) window.sounds.playSuccess(); + await showAppAlert({ + title: '¡Contraseña Restablecida!', + message: 'Tu contraseña ha sido actualizada exitosamente. Ya puedes iniciar sesión con tu nueva contraseña.', + type: 'success', + confirmText: 'Iniciar Sesión' + }); + + switchSheetView('login'); + const loginUserInput = document.getElementById('loginUsername'); + if (loginUserInput) loginUserInput.value = email; + const loginPassInput = document.getElementById('loginPassword'); + if (loginPassInput) { + loginPassInput.value = ''; + loginPassInput.focus(); + } + } catch (err) { + if (msg) { + msg.textContent = err.message; + msg.style.background = '#fee2e2'; + msg.style.borderColor = '#fca5a5'; + msg.style.color = '#991b1b'; + msg.style.border = '1px solid #fca5a5'; + msg.style.display = 'block'; + } + if (window.sounds) window.sounds.playError(); + } finally { + btn.disabled = false; + btn.innerHTML = ' Cambiar Contraseña y Entrar'; } } diff --git a/public/structured_demo.html b/public/structured_demo.html new file mode 100644 index 0000000..994eeee --- /dev/null +++ b/public/structured_demo.html @@ -0,0 +1,627 @@ + + + + + + SiboPay — Carrusel Idéntico a Structured.app + + + + + + + + + +
+
+ + CARRUSEL DE CÁPSULAS Y CONECTORES DE STRUCTURED.APP +
+ +

+ el carrusel idéntico de
+ structured con los colores de sibopay +

+ +

+ Cápsulas gigantes de 646px × 193px con radio de curvatura de 100px, estrellas doradas, conectores visuales tipo rompecabezas y dos filas que se desplazan de forma continua en sentidos opuestos. +

+ + +
+ + + + + +
+
+ + + + +
+
+
más de 50.000 clientes satisfechos
+
experiencias en tiempo real
+
+ +
+ + + + +
+
+ + +
+
+ +
+ ★ ★ ★ ★ ★ +
+

+ “La recarga por SINPE Móvil entra en 2 segundos y a mi hijo le llega el saldo de inmediato. Cero filas en la soda.” +

+
+ 💬 + Reseña WhatsApp de Padres +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Cuando alguien agenda un servicio en mi página, le llega el WhatsApp con la ruta de Waze al instante. Espectacular.” +

+
+ 📸 + Instagram Comment +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Tengo dos páginas web con el mismo número de WhatsApp enviando recordatorios automáticos sin pagar líneas extra.” +

+
+ ⭐ + Google Business Review +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Los banners de aviso en tiempo real nos salvaron cuando tuvimos que pausar el comedor. Todos los papás lo vieron.” +

+
+ 🍎 + App Store Review +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “La recarga por SINPE Móvil entra en 2 segundos y a mi hijo le llega el saldo de inmediato. Cero filas en la soda.” +

+
+ 💬 + Reseña WhatsApp de Padres +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Cuando alguien agenda un servicio en mi página, le llega el WhatsApp con la ruta de Waze al instante. Espectacular.” +

+
+ 📸 + Instagram Comment +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Tengo dos páginas web con el mismo número de WhatsApp enviando recordatorios automáticos sin pagar líneas extra.” +

+
+ ⭐ + Google Business Review +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Los banners de aviso en tiempo real nos salvaron cuando tuvimos que pausar el comedor. Todos los papás lo vieron.” +

+
+ 🍎 + App Store Review +
+
+
+ +
+
+
+ +
+
+ + + + +
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Poder bloquear alimentos chatarra y alergenos en caja desde mi celular me da una tranquilidad inmensa como mamá.” +

+
+ 🛡️ + Comentario Portal Padres +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Mi peluquería ahora llena la agenda sola. Los clientes reservan a la medianoche y les llega la confirmación por correo y WhatsApp.” +

+
+ ✂️ + Testimonio de Comercio +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “El interruptor en caliente para pausar SINPE Móvil nos permitió hacer mantenimiento sin que ningún padre tuviera errores.” +

+
+ ⚙️ + Panel de Administración +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Comprar con carné digital por QR es más rápido que pagar con efectivo. Despachamos 300 estudiantes en 15 minutos.” +

+
+ 🥪 + Cajero Soda Escolar +
+
+
+ + +
+
+
+ + +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Poder bloquear alimentos chatarra y alergenos en caja desde mi celular me da una tranquilidad inmensa como mamá.” +

+
+ 🛡️ + Comentario Portal Padres +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Mi peluquería ahora llena la agenda sola. Los clientes reservan a la medianoche y les llega la confirmación por correo y WhatsApp.” +

+
+ ✂️ + Testimonio de Comercio +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “El interruptor en caliente para pausar SINPE Móvil nos permitió hacer mantenimiento sin que ningún padre tuviera errores.” +

+
+ ⚙️ + Panel de Administración +
+
+
+ +
+
+
+ +
+
+
+ ★ ★ ★ ★ ★ +
+

+ “Comprar con carné digital por QR es más rápido que pagar con efectivo. Despachamos 300 estudiantes en 15 minutos.” +

+
+ 🥪 + Cajero Soda Escolar +
+
+
+ +
+
+
+ +
+
+ +
+
+ + + + +
+
+
explora todas las
+
funcionalidades
+
+ + +
+ + +
+
+
+ 💳 + sinpe móvil +
+
+
+ pagos
instantáneos +
+
+ + +
+
+
+ 💬 + meta api +
+
+
+ whatsapp
automático +
+
+ + +
+
+
+ 🗓️ + turnos 24/7 +
+
+
+ reservas
sin llamadas +
+
+ + +
+
+
+ 📢 + difusión +
+
+
+ avisos
en caliente +
+
+ + +
+
+
+ 🛡️ + seguridad +
+
+
+ control
parental +
+
+ +
+
+ + + + +
+
+
una sola línea de tiempo
+
tu día organizado bloque a bloque
+
+ +
+ + +
+
+ 💳 +
+
08:00 AM • Pagos
+

Recarga SINPE de ₡10,000 confirmada

+

Comprobante #9412 verificado automáticamente

+
+
+ Completado ✅ +
+ + +
+
+ ✂️ +
+
11:30 AM • Cita de Servicio
+

Corte & Tratamiento Capilar

+

Recordatorio de WhatsApp enviado al cliente

+
+
+ En 45 min +
+ + +
+
+ 🥪 +
+
01:45 PM • Comedor
+

Despacho de Pre-órdenes

+

Alergias validadas: 0 incidentes reportados

+
+
+ Programado ☕ +
+ +
+
+ + + + + + + diff --git a/server/db.js b/server/db.js index ffa7340..b252536 100644 --- a/server/db.js +++ b/server/db.js @@ -216,6 +216,16 @@ function initDatabase() { db.exec('ALTER TABLE transacciones_saldo ADD COLUMN IF NOT EXISTS revertido_en TIMESTAMP;'); db.exec('ALTER TABLE transacciones_saldo ADD COLUMN IF NOT EXISTS escuela_id INTEGER DEFAULT 1 REFERENCES escuelas(id);'); db.exec('ALTER TABLE usuarios ADD COLUMN IF NOT EXISTS escuela_id INTEGER DEFAULT 1 REFERENCES escuelas(id);'); + db.exec('ALTER TABLE usuarios ADD COLUMN IF NOT EXISTS fecha_nacimiento VARCHAR(50);'); + db.exec(` + CREATE TABLE IF NOT EXISTS password_resets ( + id SERIAL PRIMARY KEY, + email VARCHAR(150) NOT NULL, + code VARCHAR(10) NOT NULL, + expires_at TIMESTAMP NOT NULL, + creado_en TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); + `); db.exec('ALTER TABLE estudiantes ADD COLUMN IF NOT EXISTS escuela_id INTEGER DEFAULT 1 REFERENCES escuelas(id);'); db.exec('ALTER TABLE estudiantes ADD COLUMN IF NOT EXISTS card_theme VARCHAR(50);'); db.exec('ALTER TABLE estudiantes ADD COLUMN IF NOT EXISTS bloqueo_qr_biometrico INTEGER DEFAULT 0;'); @@ -265,6 +275,7 @@ function initDatabase() { nombre TEXT NOT NULL, telefono TEXT, email TEXT, + fecha_nacimiento TEXT, creado_en DATETIME DEFAULT CURRENT_TIMESTAMP ); @@ -435,8 +446,19 @@ function initDatabase() { try { db.exec('ALTER TABLE ordenes ADD COLUMN observaciones TEXT'); } catch (e) {} try { db.exec('ALTER TABLE ordenes ADD COLUMN escuela_id INTEGER DEFAULT 1'); } catch (e) {} try { db.exec('ALTER TABLE estudiantes ADD COLUMN card_theme TEXT'); } catch (e) {} - try { db.exec('ALTER TABLE usuarios ADD COLUMN card_theme TEXT'); } catch (e) {} try { db.exec('ALTER TABLE estudiantes ADD COLUMN bloqueo_qr_biometrico INTEGER DEFAULT 0'); } catch (e) {} + try { db.exec('ALTER TABLE usuarios ADD COLUMN fecha_nacimiento TEXT'); } catch (e) {} + try { + db.exec(` + CREATE TABLE IF NOT EXISTS password_resets ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT NOT NULL, + code TEXT NOT NULL, + expires_at DATETIME NOT NULL, + creado_en DATETIME DEFAULT CURRENT_TIMESTAMP + ); + `); + } catch (e) {} // 10. Diseños de Tarjetas Virtuales para Estudiantes try { diff --git a/server/emailService.js b/server/emailService.js new file mode 100644 index 0000000..c68306f --- /dev/null +++ b/server/emailService.js @@ -0,0 +1,75 @@ +const nodemailer = require('nodemailer'); + +/** + * Servicio de envío de correos electrónicos transaccionales para SiboPay + */ + +function getTransporter() { + const user = process.env.SMTP_USER || process.env.SINPE_EMAIL_USER || 'pampo32@gmail.com'; + const rawPass = process.env.SMTP_PASSWORD || process.env.SINPE_EMAIL_PASSWORD || 'aeguiflzmskmaswq'; + const pass = String(rawPass).replace(/\s+/g, ''); + + return nodemailer.createTransport({ + host: process.env.SMTP_HOST || 'smtp.gmail.com', + port: parseInt(process.env.SMTP_PORT || '465', 10), + secure: (process.env.SMTP_PORT || '465') === '465', // true para 465, false para 587 + auth: { + user: user, + pass: pass + } + }); +} + +/** + * Envía el código numérico de 6 dígitos para restablecer contraseña + */ +async function enviarCodigoRecuperacion(destinatario, codigo, nombreUsuario = 'Usuario') { + const transporter = getTransporter(); + const remitente = process.env.SMTP_FROM || `SiboPay Soporte <${process.env.SMTP_USER || 'pampo32@gmail.com'}>`; + + const mailOptions = { + from: remitente, + to: destinatario, + subject: `🔐 SiboPay - Código para restablecer contraseña: ${codigo}`, + text: `Hola ${nombreUsuario},\n\nTu código de verificación para restablecer tu contraseña en SiboPay es: ${codigo}\n\nEste código es válido durante 15 minutos. Si no solicitaste este cambio, puedes ignorar este mensaje.\n\nAtentamente,\nEquipo SiboPay`, + html: ` +
+
+ +
+

SiboPay

+

Recuperación Segura de Cuenta

+
+ +
+

Restablecer tu Contraseña

+

+ Hola ${nombreUsuario}, recibimos una solicitud para restablecer la contraseña de tu cuenta. Ingresa el siguiente código de verificación en la aplicación: +

+ +
+ ${codigo} +
+ +

+ ⏳ Este código vencerá en 15 minutos.
+ Si no solicitaste este cambio, haz caso omiso a este correo. +

+
+ +
+

+ © SiboPay - Sistema Inteligente de Billetera Online. Todos los derechos reservados. +

+
+
+
+ ` + }; + + return transporter.sendMail(mailOptions); +} + +module.exports = { + enviarCodigoRecuperacion +}; diff --git a/server/server.js b/server/server.js index 8c5a415..384ec00 100644 --- a/server/server.js +++ b/server/server.js @@ -53,6 +53,7 @@ const { const { checkSinpeEmailsOnce, simularSinpeEmail } = require('./sinpeImapService'); const { normalizarCodigoDetalle, parseSinpeEmail } = require('./sinpeParser'); const { simpleParser } = require('mailparser'); +const { enviarCodigoRecuperacion } = require('./emailService'); const webpush = require('web-push'); @@ -533,25 +534,29 @@ app.post('/api/auth/login', (req, res) => { } }); -// Registro de nuevos padres desde la pantalla de bienvenida +// Registro de nuevos usuarios desde la pantalla de bienvenida app.post('/api/auth/register-padre', (req, res) => { try { - const { nombre, telefono, email, username, password } = req.body; - if (!nombre || !username || !password) { - return res.status(400).json({ error: 'Nombre completo, usuario y contraseña son requeridos' }); + const { nombre, telefono, email, username, password, fecha_nacimiento } = req.body; + if (!nombre || !username || !password || !email) { + return res.status(400).json({ error: 'Nombre completo, correo electrónico, usuario y contraseña son requeridos' }); } const cleanUser = String(username).trim().toLowerCase(); const cleanPass = String(password).trim(); const cleanNombre = String(nombre).trim(); const cleanTel = telefono ? String(telefono).trim() : ''; - const cleanEmail = email ? String(email).trim().toLowerCase() : ''; + const cleanEmail = String(email).trim().toLowerCase(); + const cleanFechaNac = fecha_nacimiento ? String(fecha_nacimiento).trim() : ''; if (cleanUser.length < 3) { return res.status(400).json({ error: 'El nombre de usuario debe tener al menos 3 caracteres' }); } - if (cleanPass.length < 4) { - return res.status(400).json({ error: 'La contraseña debe tener al menos 4 caracteres' }); + if (cleanPass.length < 6) { + return res.status(400).json({ error: 'La contraseña debe tener al menos 6 caracteres' }); + } + if (!cleanEmail.includes('@') || !cleanEmail.includes('.')) { + return res.status(400).json({ error: 'Ingresa un correo electrónico válido' }); } // Comprobar si el usuario ya existe @@ -560,11 +565,17 @@ app.post('/api/auth/register-padre', (req, res) => { return res.status(400).json({ error: 'Ese nombre de usuario ya está en uso. Por favor elige otro.' }); } + // Comprobar si el correo ya está registrado + const emailExists = db.prepare('SELECT id FROM usuarios WHERE LOWER(email) = ?').get(cleanEmail); + if (emailExists) { + return res.status(400).json({ error: 'Ese correo electrónico ya está registrado. Puedes iniciar sesión o restablecer tu contraseña.' }); + } + const insert = db.prepare(` - INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email) - VALUES (?, ?, 'padre', ?, ?, ?) + INSERT INTO usuarios (username, password_hash, rol, nombre, telefono, email, fecha_nacimiento) + VALUES (?, ?, 'padre', ?, ?, ?, ?) `); - const result = insert.run(cleanUser, cleanPass, cleanNombre, cleanTel, cleanEmail); + const result = insert.run(cleanUser, cleanPass, cleanNombre, cleanTel, cleanEmail, cleanFechaNac); const newUser = { id: result.lastInsertRowid, @@ -572,7 +583,8 @@ app.post('/api/auth/register-padre', (req, res) => { rol: 'padre', nombre: cleanNombre, telefono: cleanTel, - email: cleanEmail + email: cleanEmail, + fecha_nacimiento: cleanFechaNac }; res.json({ @@ -585,6 +597,95 @@ app.post('/api/auth/register-padre', (req, res) => { } }); +// ========================================== +// RESTABLECIMIENTO DE CONTRASEÑA VÍA CORREO +// ========================================== + +// 1. Enviar código de 6 dígitos al correo +app.post('/api/auth/forgot-password', async (req, res) => { + try { + const { email } = req.body; + if (!email) { + return res.status(400).json({ error: 'Por favor ingresa tu correo electrónico' }); + } + + const cleanEmail = String(email).trim().toLowerCase(); + const user = db.prepare('SELECT id, username, nombre, email FROM usuarios WHERE LOWER(email) = ?').get(cleanEmail); + if (!user) { + return res.status(404).json({ error: 'No encontramos ninguna cuenta asociada a este correo electrónico.' }); + } + + // Generar código numérico de 6 dígitos + const code = Math.floor(100000 + Math.random() * 900000).toString(); + const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString(); + + // Guardar código en la base de datos (eliminar previos para este correo) + try { + db.prepare('DELETE FROM password_resets WHERE LOWER(email) = ?').run(cleanEmail); + } catch (_) {} + db.prepare('INSERT INTO password_resets (email, code, expires_at) VALUES (?, ?, ?)').run(cleanEmail, code, expiresAt); + + // Enviar código por correo electrónico vía SMTP + await enviarCodigoRecuperacion(cleanEmail, code, user.nombre || user.username); + + res.json({ + success: true, + message: 'Hemos enviado un código de 6 dígitos a tu correo electrónico.' + }); + } catch (err) { + console.error('[AUTH] ❌ Error en forgot-password:', err); + res.status(500).json({ error: 'Error al enviar el código de recuperación: ' + (err.message || 'Error de conexión') }); + } +}); + +// 2. Validar código y asignar nueva contraseña +app.post('/api/auth/reset-password', (req, res) => { + try { + const { email, code, new_password } = req.body; + if (!email || !code || !new_password) { + return res.status(400).json({ error: 'Correo, código y nueva contraseña son requeridos' }); + } + + const cleanEmail = String(email).trim().toLowerCase(); + const cleanCode = String(code).trim(); + const cleanPass = String(new_password).trim(); + + if (cleanPass.length < 6) { + return res.status(400).json({ error: 'La nueva contraseña debe tener al menos 6 caracteres' }); + } + + const resetEntry = db.prepare('SELECT id, code, expires_at FROM password_resets WHERE LOWER(email) = ? ORDER BY id DESC LIMIT 1').get(cleanEmail); + if (!resetEntry || resetEntry.code !== cleanCode) { + return res.status(400).json({ error: 'El código de verificación es inválido. Verifícalo e intenta de nuevo.' }); + } + + const now = new Date(); + const expires = new Date(resetEntry.expires_at); + if (now > expires) { + return res.status(400).json({ error: 'El código de verificación ha expirado (validez de 15 minutos). Solicita uno nuevo.' }); + } + + // Actualizar contraseña del usuario + const update = db.prepare('UPDATE usuarios SET password_hash = ? WHERE LOWER(email) = ?').run(cleanPass, cleanEmail); + if (update.changes === 0) { + return res.status(404).json({ error: 'No se pudo encontrar la cuenta para actualizar la contraseña.' }); + } + + // Eliminar código utilizado + try { + db.prepare('DELETE FROM password_resets WHERE LOWER(email) = ?').run(cleanEmail); + } catch (_) {} + + res.json({ + success: true, + message: '¡Contraseña actualizada exitosamente! Ya puedes iniciar sesión con tu nueva contraseña.' + }); + } catch (err) { + console.error('[AUTH] ❌ Error en reset-password:', err); + res.status(500).json({ error: 'Error al restablecer la contraseña: ' + (err.message || 'Error interno') }); + } +}); + // ========================================== // ELIMINACIÓN DE CUENTA Y SUPRESIÓN DE DATOS (GOOGLE PLAY & APPLE COMPLIANCE) // ==========================================