diff --git a/public/js/app.js b/public/js/app.js
index 0f0bfa1..f040f84 100644
--- a/public/js/app.js
+++ b/public/js/app.js
@@ -9653,3 +9653,151 @@ window.closeLoginSheet = closeLoginSheet;
window.switchSheetView = switchSheetView;
window.openTerminosModal = openTerminosModal;
window.closeTerminosModal = closeTerminosModal;
+
+// ========================================================
+// AJUSTES DE CUENTA, PRIVACIDAD Y EXPERIENCIA SENSORIAL HÁPTICA
+// ========================================================
+function abrirModalAjustesCuenta() {
+ const modal = document.getElementById('modalAjustesCuenta');
+ if (!modal) return;
+
+ const lblNombre = document.getElementById('ajustesCuentaNombre');
+ const lblRol = document.getElementById('ajustesCuentaRol');
+ const chkSound = document.getElementById('chkAjustesSound');
+ const chkHaptic = document.getElementById('chkAjustesHaptic');
+
+ if (currentUser) {
+ if (lblNombre) lblNombre.textContent = currentUser.nombre || currentUser.username || 'Usuario';
+ if (lblRol) {
+ let r = currentUser.rol || 'Usuario';
+ if (r === 'padre') r = 'Padre / Encargado';
+ else if (r === 'estudiante') r = 'Estudiante / Alumno';
+ else if (r === 'cajero') r = 'Cajero de Soda';
+ else if (r === 'admin') r = 'Administrador de Soda';
+ lblRol.textContent = r;
+ }
+ }
+
+ if (chkSound && window.sounds) {
+ chkSound.checked = window.sounds.isSoundEnabled();
+ }
+ if (chkHaptic && window.sounds) {
+ chkHaptic.checked = window.sounds.isHapticEnabled();
+ }
+
+ modal.style.display = 'flex';
+}
+window.abrirModalAjustesCuenta = abrirModalAjustesCuenta;
+
+function cerrarModalAjustesCuenta(e) {
+ if (e && e.target !== e.currentTarget && e.currentTarget !== document) return;
+ const modal = document.getElementById('modalAjustesCuenta');
+ if (modal) modal.style.display = 'none';
+}
+window.cerrarModalAjustesCuenta = cerrarModalAjustesCuenta;
+
+function toggleSensorySoundUI(checked) {
+ if (window.sounds) {
+ window.sounds.toggleSound(checked);
+ }
+}
+window.toggleSensorySoundUI = toggleSensorySoundUI;
+
+function toggleSensoryHapticUI(checked) {
+ if (window.sounds) {
+ window.sounds.toggleHaptics(checked);
+ }
+}
+window.toggleSensoryHapticUI = toggleSensoryHapticUI;
+
+function abrirModalConfirmarEliminarCuenta() {
+ cerrarModalAjustesCuenta();
+ const modal = document.getElementById('modalConfirmarEliminarCuenta');
+ const input = document.getElementById('inputConfirmarPassEliminar');
+ if (input) input.value = '';
+ if (modal) modal.style.display = 'flex';
+}
+window.abrirModalConfirmarEliminarCuenta = abrirModalConfirmarEliminarCuenta;
+
+function cerrarModalConfirmarEliminarCuenta(e) {
+ if (e && e.target !== e.currentTarget && e.currentTarget !== document) return;
+ const modal = document.getElementById('modalConfirmarEliminarCuenta');
+ if (modal) modal.style.display = 'none';
+}
+window.cerrarModalConfirmarEliminarCuenta = cerrarModalConfirmarEliminarCuenta;
+
+async function confirmarEliminarCuentaDefinitiva() {
+ if (!currentUser || !currentUser.id) {
+ alert('No hay una sesión activa para eliminar.');
+ return;
+ }
+
+ const input = document.getElementById('inputConfirmarPassEliminar');
+ const val = input ? input.value.trim() : '';
+
+ if (!val) {
+ alert('Por favor ingresa tu contraseña o la palabra ELIMINAR para verificar tu identidad.');
+ return;
+ }
+
+ const btn = document.getElementById('btnEjecutarEliminacionDefinitiva');
+ if (btn) {
+ btn.disabled = true;
+ btn.textContent = 'Eliminando cuenta...';
+ }
+
+ try {
+ const res = await fetch('/api/auth/eliminar-cuenta', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ usuario_id: currentUser.id,
+ password_confirmacion: val,
+ motivo: 'Eliminación voluntaria solicitada por el usuario desde la app'
+ })
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || 'No se pudo eliminar la cuenta');
+
+ if (window.sounds) {
+ window.sounds.playSuccess();
+ }
+
+ alert('Tu cuenta y datos personales han sido eliminados permanentemente de SiboPay.');
+
+ // Limpieza total de almacenamiento local y caches
+ try {
+ localStorage.removeItem('sibopay_token');
+ localStorage.removeItem('sibopay_user');
+ localStorage.removeItem('recreopay_token');
+ localStorage.removeItem('recreopay_user');
+ sessionStorage.clear();
+ if ('caches' in window) {
+ const keys = await caches.keys();
+ for (const k of keys) await caches.delete(k);
+ }
+ } catch (e) {}
+
+ window.location.href = '/index.html';
+ } catch (err) {
+ if (window.sounds) window.sounds.playError();
+ alert('Error al eliminar cuenta: ' + err.message);
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = 'Sí, Borrar Mi Cuenta';
+ }
+ }
+}
+window.confirmarEliminarCuentaDefinitiva = confirmarEliminarCuentaDefinitiva;
+
+// ========================================================
+// RETROALIMENTACIÓN HÁPTICA GLOBAL EN DISPOSITIVOS MÓVILES
+// ========================================================
+document.addEventListener('pointerdown', (e) => {
+ const btn = e.target.closest('button, .btn-saas, .mode-btn, .login-submit-btn, .pwa-nav-item, .limit-preset-pill, .quick-amount-pill, .theme-toggle-btn');
+ if (btn && !btn.disabled && window.haptics) {
+ window.haptics.tap();
+ }
+}, { passive: true });
+
diff --git a/public/js/pos.js b/public/js/pos.js
index 34ca795..d8907ee 100644
--- a/public/js/pos.js
+++ b/public/js/pos.js
@@ -149,9 +149,26 @@ document.addEventListener('DOMContentLoaded', async () => {
localStorage.setItem('sibopay_pos_autoprint', chkAutoPrint.checked ? '1' : '0');
});
}
+
+ // Inicializar Resiliencia Offline de la Soda
+ updateNetworkStatusUI();
+ cacheOfflineStudents();
+
+ window.addEventListener('online', () => {
+ updateNetworkStatusUI();
+ const q = getOfflineQueue();
+ if (q.length > 0) {
+ sincronizarVentasOfflineManual();
+ }
+ cacheOfflineStudents();
+ });
+
+ window.addEventListener('offline', () => {
+ updateNetworkStatusUI();
+ });
});
-// Cargar catálogo de productos
+// Cargar catálogo de productos con respaldo offline
async function loadCatalog() {
try {
const url = `/api/productos?escuela_id=${getPosEscuelaId()}`;
@@ -160,10 +177,26 @@ async function loadCatalog() {
posCategories = data.categorias;
posProducts = data.productos;
+ // Respaldar catálogo localmente para modo offline
+ try {
+ localStorage.setItem('sibo_pos_offline_catalog', JSON.stringify(data));
+ } catch (e) {}
+
renderPosCategories();
renderPosProducts(null);
} catch (err) {
- console.error('Error cargando catálogo:', err);
+ console.warn('[Modo Offline] No se pudo conectar al servidor, cargando catálogo desde memoria local:', err.message);
+ try {
+ const cached = localStorage.getItem('sibo_pos_offline_catalog');
+ if (cached) {
+ const data = JSON.parse(cached);
+ posCategories = data.categorias || [];
+ posProducts = data.productos || [];
+ renderPosCategories();
+ renderPosProducts(null);
+ console.log('[Modo Offline] Catálogo cargado exitosamente desde memoria offline.');
+ }
+ } catch (e) {}
}
}
@@ -837,9 +870,16 @@ async function onQrCodeDetected(token) {
if (posModalMode === 'identificar' || posCart.length === 0) {
try {
- const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
- const data = await res.json();
- if (!res.ok) throw new Error(data.error);
+ let data = null;
+ try {
+ const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
+ data = await res.json();
+ if (!res.ok) throw new Error(data.error);
+ } catch (fetchErr) {
+ data = buscarEstudianteOffline(token);
+ if (!data) throw new Error(fetchErr.message || 'Carné escolar no encontrado');
+ console.log('[Modo Offline] Estudiante identificado desde memoria offline:', data.nombre_completo);
+ }
scannedStudent = data;
renderScannedStudent();
@@ -1136,9 +1176,16 @@ async function handlePistolBarcodeScan(rawToken) {
// Si no hay productos en el carrito, identificar al alumno para mostrador
if (posCart.length === 0) {
try {
- const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
- const data = await res.json();
- if (!res.ok) throw new Error(data.error);
+ let data = null;
+ try {
+ const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
+ data = await res.json();
+ if (!res.ok) throw new Error(data.error);
+ } catch (fetchErr) {
+ data = buscarEstudianteOffline(token);
+ if (!data) throw new Error(fetchErr.message || 'Carné escolar no encontrado');
+ console.log('[Modo Offline] Estudiante identificado:', data.nombre_completo);
+ }
scannedStudent = data;
renderScannedStudent();
@@ -1165,10 +1212,17 @@ async function handlePistolBarcodeScan(rawToken) {
document.getElementById('pistolaProcessingName').textContent = 'Identificando estudiante y validando monedero...';
try {
- // 1. Buscar estudiante por token o código
- const resEst = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
- const student = await resEst.json();
- if (!resEst.ok) throw new Error(student.error || 'Carné escolar no encontrado');
+ // 1. Buscar estudiante por token o código (con fallback offline)
+ let student = null;
+ try {
+ const resEst = await fetch(`/api/estudiantes/qr/${encodeURIComponent(token)}?escuela_id=${getPosEscuelaId()}`);
+ student = await resEst.json();
+ if (!resEst.ok) throw new Error(student.error || 'Carné escolar no encontrado');
+ } catch (fetchErr) {
+ student = buscarEstudianteOffline(token);
+ if (!student) throw new Error(fetchErr.message || 'Carné escolar no encontrado en el sistema ni en memoria offline');
+ console.log('[Modo Offline] Estudiante cargado para cobro desde memoria local:', student.nombre_completo);
+ }
document.getElementById('pistolaProcessingName').textContent = `Verificando saldo para ${student.nombre_completo}...`;
@@ -1188,26 +1242,64 @@ async function handlePistolBarcodeScan(rawToken) {
throw new Error(`⚠️ SUPERA LÍMITE DIARIO: Le quedan ₡${student.disponible_hoy.toLocaleString('es-CR')} disponibles hoy de su límite diario asignado.`);
}
- // 4. Procesar cobro en servidor
+ // 4. Procesar cobro en servidor (o guardar en cola offline si no hay red)
const items = posCart.map(item => ({
producto_id: item.product.id,
cantidad: item.cantidad
}));
- const resCobro = await fetch('/api/ordenes', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- estudiante_id: student.id,
- tipo_orden: 'mostrador',
- momento_entrega: 'inmediato',
- items,
- escuela_id: getPosEscuelaId()
- })
- });
+ let dataCobro = null;
+ try {
+ const resCobro = await fetch('/api/ordenes', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ estudiante_id: student.id,
+ tipo_orden: 'mostrador',
+ momento_entrega: 'inmediato',
+ items,
+ escuela_id: getPosEscuelaId()
+ })
+ });
- const dataCobro = await resCobro.json();
- if (!resCobro.ok) throw new Error(dataCobro.error || 'Error al procesar el débito');
+ dataCobro = await resCobro.json();
+ if (!resCobro.ok) throw new Error(dataCobro.error || 'Error al procesar el débito');
+ } catch (errCobro) {
+ if (!navigator.onLine || errCobro.message.includes('fetch') || errCobro.message.includes('NetworkError') || errCobro.message.includes('Failed to fetch')) {
+ const offlineTicketCode = 'OFFLINE-' + Date.now().toString().slice(-6) + '-' + Math.random().toString(36).slice(2, 5).toUpperCase();
+
+ // Descontar saldo localmente para evitar sobregiro offline
+ actualizarSaldoEstudianteOffline(student.id, totalCompra);
+
+ const offlineOrderRecord = {
+ offline_id: offlineTicketCode,
+ estudiante_id: student.id,
+ estudiante_nombre: student.nombre_completo,
+ tipo_orden: 'mostrador',
+ momento_entrega: 'inmediato',
+ items,
+ total: totalCompra,
+ escuela_id: getPosEscuelaId(),
+ fecha: new Date().toISOString()
+ };
+
+ const currentQueue = getOfflineQueue();
+ currentQueue.push(offlineOrderRecord);
+ saveOfflineQueue(currentQueue);
+
+ dataCobro = {
+ codigo_orden: offlineTicketCode,
+ financiero: {
+ estudiante: {
+ saldo_nuevo: Math.max(0, (student.saldo_colones || 0) - totalCompra)
+ }
+ }
+ };
+ console.log('[Modo Offline] Venta de mostrador registrada localmente:', offlineTicketCode);
+ } else {
+ throw errCobro;
+ }
+ }
// 5. Éxito: Mostrar pantalla de confirmación
document.getElementById('pistolaStateProcessing').style.display = 'none';
@@ -2589,5 +2681,161 @@ function imprimirTicketTermico(orderData) {
}
window.imprimirTicketTermico = imprimirTicketTermico;
+// ========================================================
+// SISTEMA DE RESILIENCIA OFFLINE DE LA SODA Y CAJA POS
+// ========================================================
+async function cacheOfflineStudents() {
+ try {
+ const res = await fetch(`/api/estudiantes?escuela_id=${getPosEscuelaId()}`);
+ if (!res.ok) return;
+ const list = await res.json();
+ if (Array.isArray(list) && list.length > 0) {
+ localStorage.setItem('sibo_pos_offline_students', JSON.stringify(list));
+ console.log(`[Modo Offline] ${list.length} estudiantes respaldados en memoria local para ventas sin conexión.`);
+ }
+ } catch (e) {
+ console.warn('[Modo Offline] No se pudieron sincronizar estudiantes para cache offline:', e.message);
+ }
+}
+window.cacheOfflineStudents = cacheOfflineStudents;
+function buscarEstudianteOffline(query) {
+ try {
+ const cached = localStorage.getItem('sibo_pos_offline_students');
+ if (!cached) return null;
+ const students = JSON.parse(cached);
+ const q = String(query || '').trim().toLowerCase();
+ return students.find(s =>
+ (s.qr_token && s.qr_token.toLowerCase() === q) ||
+ (s.codigo_estudiante && s.codigo_estudiante.toLowerCase() === q) ||
+ (String(s.id) === q)
+ ) || null;
+ } catch (e) {
+ return null;
+ }
+}
+window.buscarEstudianteOffline = buscarEstudianteOffline;
+function actualizarSaldoEstudianteOffline(estId, montoCobrado) {
+ try {
+ const cached = localStorage.getItem('sibo_pos_offline_students');
+ if (!cached) return;
+ const students = JSON.parse(cached);
+ const idx = students.findIndex(s => s.id === estId);
+ if (idx !== -1) {
+ students[idx].saldo_colones = Math.max(0, (students[idx].saldo_colones || 0) - montoCobrado);
+ students[idx].disponible_hoy = Math.max(0, (students[idx].disponible_hoy || 0) - montoCobrado);
+ localStorage.setItem('sibo_pos_offline_students', JSON.stringify(students));
+ }
+ } catch (e) {}
+}
+window.actualizarSaldoEstudianteOffline = actualizarSaldoEstudianteOffline;
+
+function getOfflineQueue() {
+ try {
+ const q = localStorage.getItem('sibo_pos_offline_queue');
+ return q ? JSON.parse(q) : [];
+ } catch (e) {
+ return [];
+ }
+}
+window.getOfflineQueue = getOfflineQueue;
+
+function saveOfflineQueue(queue) {
+ try {
+ localStorage.setItem('sibo_pos_offline_queue', JSON.stringify(queue));
+ updateNetworkStatusUI();
+ } catch (e) {}
+}
+window.saveOfflineQueue = saveOfflineQueue;
+
+function updateNetworkStatusUI() {
+ const badge = document.getElementById('posNetworkStatusBadge');
+ const banner = document.getElementById('posOfflineQueueBanner');
+ const lblCount = document.getElementById('lblPosOfflineCount');
+ const queue = getOfflineQueue();
+ const isOnline = navigator.onLine;
+
+ if (badge) {
+ if (isOnline) {
+ badge.className = 'pos-network-pill online';
+ badge.innerHTML = ' En Línea ';
+ } else {
+ badge.className = 'pos-network-pill offline';
+ badge.innerHTML = ' Modo Offline ';
+ }
+ }
+
+ if (banner) {
+ if (queue.length > 0) {
+ banner.style.display = 'flex';
+ if (lblCount) {
+ lblCount.textContent = `${queue.length} venta(s) guardada(s) localmente esperando conexión.`;
+ }
+ } else {
+ banner.style.display = 'none';
+ }
+ }
+}
+window.updateNetworkStatusUI = updateNetworkStatusUI;
+
+async function sincronizarVentasOfflineManual() {
+ const queue = getOfflineQueue();
+ if (queue.length === 0) {
+ alert('No hay ventas offline pendientes de sincronizar.');
+ return;
+ }
+
+ if (!navigator.onLine) {
+ alert('La terminal no detecta conexión a internet en este momento.');
+ return;
+ }
+
+ const btn = document.getElementById('btnSyncOfflinePos');
+ if (btn) {
+ btn.disabled = true;
+ btn.textContent = '🔄 Sincronizando...';
+ }
+
+ try {
+ const res = await fetch('/api/ordenes/sincronizar-offline', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ ordenes: queue,
+ escuela_id: getPosEscuelaId()
+ })
+ });
+
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || 'Error al sincronizar ventas offline');
+
+ // Limpiar cola local
+ localStorage.removeItem('sibo_pos_offline_queue');
+ updateNetworkStatusUI();
+
+ // Refrescar catálogo y estudiantes del servidor
+ await loadCatalog();
+ await cacheOfflineStudents();
+
+ if (window.sounds) window.sounds.playSuccess();
+ alert(`✅ ¡Sincronización Exitosa!\n\nSe han registrado ${data.sincronizadas} venta(s) offline en la base de datos de la soda.`);
+ } catch (err) {
+ if (window.sounds) window.sounds.playError();
+ alert(`Error al sincronizar ventas offline: ${err.message}`);
+ } finally {
+ if (btn) {
+ btn.disabled = false;
+ btn.textContent = '🔄 Sincronizar Ahora';
+ }
+ }
+}
+window.sincronizarVentasOfflineManual = sincronizarVentasOfflineManual;
+
+// Retroalimentación háptica táctil en mostrador POS
+document.addEventListener('pointerdown', (e) => {
+ const btn = e.target.closest('button, .btn-saas, .pos-mobile-nav-btn, .pos-tab-btn, .pos-cat-pill, .product-card, .pos-qty-btn');
+ if (btn && !btn.disabled && window.haptics) {
+ window.haptics.tap();
+ }
+}, { passive: true });
diff --git a/public/js/sounds.js b/public/js/sounds.js
index bb85691..db61b6c 100644
--- a/public/js/sounds.js
+++ b/public/js/sounds.js
@@ -1,32 +1,270 @@
// ========================================================
-// SISTEMA DE SONIDOS SIBOPAY - COMPLETAMENTE DESACTIVADO
-// Todos los efectos de sonido y alertas auditivas han sido removidos a solicitud.
+// SISTEMA SENSORIAL SIBOPAY: AUDIO SINTETIZADO Y HÁPTICO MÓVIL
+// Sonidos sintetizados mediante Web Audio API (cero descargas, cero latencia)
+// y vibración háptica táctil en dispositivos móviles (navigator.vibrate)
// ========================================================
-class SoundEffects {
+
+class SensorySystem {
constructor() {
this.ctx = null;
- this.enabled = false;
+ this.soundEnabled = localStorage.getItem('sibopay_sound_enabled') !== 'false';
+ this.hapticEnabled = localStorage.getItem('sibopay_haptic_enabled') !== 'false';
+ this.masterVolume = 0.22; // Nivel suave y agradable, no intrusivo
+ this._initOnGesture = this._initOnGesture.bind(this);
+
+ // Escuchar interacción del usuario para desbloquear AudioContext en móviles (política de navegadores)
+ if (typeof window !== 'undefined') {
+ window.addEventListener('pointerdown', this._initOnGesture, { once: true, passive: true });
+ window.addEventListener('keydown', this._initOnGesture, { once: true, passive: true });
+ }
}
- init() {}
- playSuccess() {}
- playCoin() {}
- playScanChirp() {}
- playError() {}
- playTap() {}
- playBeep() {}
- playNotice() {}
- playTrash() {}
+ _initOnGesture() {
+ this._getAudioContext();
+ }
+
+ _getAudioContext() {
+ if (!this.ctx && (typeof window !== 'undefined')) {
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
+ if (AudioCtx) {
+ try {
+ this.ctx = new AudioCtx();
+ } catch (e) {
+ console.warn('[SensorySystem] No se pudo inicializar AudioContext:', e);
+ }
+ }
+ }
+ if (this.ctx && this.ctx.state === 'suspended') {
+ this.ctx.resume().catch(() => {});
+ }
+ return this.ctx;
+ }
+
+ // ==========================================
+ // RETROALIMENTACIÓN HÁPTICA (VIBRACIÓN TÁCTIL)
+ // ==========================================
+ vibrate(pattern) {
+ if (!this.hapticEnabled) return;
+ try {
+ if (typeof navigator !== 'undefined' && 'vibrate' in navigator) {
+ navigator.vibrate(pattern);
+ }
+ } catch (e) {}
+ }
+
+ hapticTap() {
+ this.vibrate(10); // Micro-vibración sutil de 10ms
+ }
+
+ hapticSuccess() {
+ this.vibrate([30, 40, 45]); // Doble pulso de confirmación
+ }
+
+ hapticScan() {
+ this.vibrate(22); // Pulso nítido de detección
+ }
+
+ hapticWarning() {
+ this.vibrate([40, 50, 40]);
+ }
+
+ hapticError() {
+ this.vibrate([70, 50, 70]); // Pulso más marcado de advertencia/error
+ }
+
+ // ==========================================
+ // SÍNTESIS DE AUDIO (WEB AUDIO API)
+ // ==========================================
+
+ // Campana suave de éxito (arpegio de 3 notas: Do - Mi - Sol)
+ playSuccess() {
+ this.hapticSuccess();
+ if (!this.soundEnabled) return;
+ const ctx = this._getAudioContext();
+ if (!ctx) return;
+
+ try {
+ const now = ctx.currentTime;
+ const notes = [523.25, 659.25, 783.99]; // C5, E5, G5
+ notes.forEach((freq, index) => {
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(freq, now + index * 0.08);
+
+ gain.gain.setValueAtTime(0, now + index * 0.08);
+ gain.gain.linearRampToValueAtTime(this.masterVolume, now + index * 0.08 + 0.02);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + index * 0.08 + 0.35);
+
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+
+ osc.start(now + index * 0.08);
+ osc.stop(now + index * 0.08 + 0.36);
+ });
+ } catch (e) {}
+ }
+
+ // Sonido de moneda / pago registrado (doble tintineo metálico)
+ playCoin() {
+ this.hapticSuccess();
+ if (!this.soundEnabled) return;
+ const ctx = this._getAudioContext();
+ if (!ctx) return;
+
+ try {
+ const now = ctx.currentTime;
+ const tones = [987.77, 1318.51]; // B5 -> E6
+ tones.forEach((freq, index) => {
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+ osc.type = 'triangle';
+ osc.frequency.setValueAtTime(freq, now + index * 0.09);
+
+ gain.gain.setValueAtTime(0, now + index * 0.09);
+ gain.gain.linearRampToValueAtTime(this.masterVolume * 0.9, now + index * 0.09 + 0.015);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + index * 0.09 + 0.28);
+
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+
+ osc.start(now + index * 0.09);
+ osc.stop(now + index * 0.09 + 0.30);
+ });
+ } catch (e) {}
+ }
+
+ // Chirp nítido de escáner QR o código de barras
+ playScanChirp() {
+ this.hapticScan();
+ if (!this.soundEnabled) return;
+ const ctx = this._getAudioContext();
+ if (!ctx) return;
+
+ try {
+ const now = ctx.currentTime;
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(1400, now);
+ osc.frequency.exponentialRampToValueAtTime(1900, now + 0.04);
+
+ gain.gain.setValueAtTime(this.masterVolume * 0.8, now);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.05);
+
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+
+ osc.start(now);
+ osc.stop(now + 0.05);
+ } catch (e) {}
+ }
+
+ // Tap acústico sutil para botones numéricos o selección
+ playTap() {
+ this.hapticTap();
+ if (!this.soundEnabled) return;
+ const ctx = this._getAudioContext();
+ if (!ctx) return;
+
+ try {
+ const now = ctx.currentTime;
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(440, now);
+ osc.frequency.exponentialRampToValueAtTime(220, now + 0.025);
+
+ gain.gain.setValueAtTime(this.masterVolume * 0.4, now);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.03);
+
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+
+ osc.start(now);
+ osc.stop(now + 0.03);
+ } catch (e) {}
+ }
+
+ // Tono de error o rechazo (dos tonos bajos descendentes)
+ playError() {
+ this.hapticError();
+ if (!this.soundEnabled) return;
+ const ctx = this._getAudioContext();
+ if (!ctx) return;
+
+ try {
+ const now = ctx.currentTime;
+ const tones = [260, 195];
+ tones.forEach((freq, idx) => {
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ osc.type = 'sawtooth';
+ osc.frequency.setValueAtTime(freq, now + idx * 0.12);
+
+ gain.gain.setValueAtTime(this.masterVolume * 0.6, now + idx * 0.12);
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + idx * 0.12 + 0.14);
+
+ osc.connect(gain);
+ gain.connect(ctx.destination);
+
+ osc.start(now + idx * 0.12);
+ osc.stop(now + idx * 0.12 + 0.15);
+ });
+ } catch (e) {}
+ }
+
+ playBeep() {
+ this.playTap();
+ }
+
+ playNotice() {
+ this.playSuccess();
+ }
+
+ playTrash() {
+ this.playTap();
+ }
+
+ // ==========================================
+ // CONFIGURACIÓN DE PREFERENCIAS DE USUARIO
+ // ==========================================
+ toggleSound(enabled) {
+ this.soundEnabled = (typeof enabled === 'boolean') ? enabled : !this.soundEnabled;
+ localStorage.setItem('sibopay_sound_enabled', String(this.soundEnabled));
+ if (this.soundEnabled) this.playTap();
+ return this.soundEnabled;
+ }
+
+ toggleHaptics(enabled) {
+ this.hapticEnabled = (typeof enabled === 'boolean') ? enabled : !this.hapticEnabled;
+ localStorage.setItem('sibopay_haptic_enabled', String(this.hapticEnabled));
+ if (this.hapticEnabled) this.hapticTap();
+ return this.hapticEnabled;
+ }
+
+ isSoundEnabled() {
+ return this.soundEnabled;
+ }
+
+ isHapticEnabled() {
+ return this.hapticEnabled;
+ }
}
-const silentInstance = new SoundEffects();
+// Instancia global compartida
+const sensoryInstance = new SensorySystem();
-// Proxy de seguridad para asegurar que cualquier llamada desconocida sea silenciosa y segura
-window.sounds = new Proxy(silentInstance, {
- get(target, prop) {
- if (prop in target) {
- return target[prop];
- }
- return function() {};
- }
-});
+// Exponer como window.sounds y window.haptics para máxima compatibilidad
+window.sounds = sensoryInstance;
+window.haptics = {
+ tap: () => sensoryInstance.hapticTap(),
+ success: () => sensoryInstance.hapticSuccess(),
+ scan: () => sensoryInstance.hapticScan(),
+ warning: () => sensoryInstance.hapticWarning(),
+ error: () => sensoryInstance.hapticError(),
+ vibrate: (p) => sensoryInstance.vibrate(p)
+};
diff --git a/public/pos.html b/public/pos.html
index 7219762..7494a62 100644
--- a/public/pos.html
+++ b/public/pos.html
@@ -131,9 +131,9 @@
Pistola QR Conectada
-
-
- En Línea (SSE)
+
+
+ En Línea
🔔 Notificaciones
@@ -155,6 +155,20 @@
🖨️ Auto-imprimir ticket
+
+
+
+
+
⚡
+
+ Modo Offline Activo
+ 0 ventas guardadas localmente esperando conexión.
+
+
+
+ 🔄 Sincronizar Ahora
+
+
diff --git a/server/server.js b/server/server.js
index ce41772..d8447b1 100644
--- a/server/server.js
+++ b/server/server.js
@@ -394,6 +394,102 @@ app.post('/api/auth/register-padre', (req, res) => {
}
});
+// ==========================================
+// ELIMINACIÓN DE CUENTA Y SUPRESIÓN DE DATOS (GOOGLE PLAY & APPLE COMPLIANCE)
+// ==========================================
+app.post('/api/auth/eliminar-cuenta', (req, res) => {
+ try {
+ const { usuario_id, password_confirmacion, motivo } = req.body;
+ if (!usuario_id) {
+ return res.status(400).json({ error: 'ID de usuario requerido para procesar la baja' });
+ }
+
+ const user = db.prepare('SELECT * FROM usuarios WHERE id = ?').get(usuario_id);
+ if (!user) {
+ return res.status(404).json({ error: 'La cuenta de usuario no existe o ya ha sido eliminada' });
+ }
+
+ // Verificar contraseña si fue enviada (o frase de confirmación ELIMINAR)
+ if (password_confirmacion) {
+ const cleanPass = String(password_confirmacion).trim();
+ if (cleanPass !== user.password_hash && cleanPass.toUpperCase() !== 'ELIMINAR') {
+ return res.status(401).json({ error: 'Contraseña de confirmación incorrecta. Por favor verifícala para proceder con el borrado.' });
+ }
+ }
+
+ // Proceder con el borrado y disociación según el rol
+ if (user.rol === 'padre') {
+ // 1. Desvincular de todos los hijos en tabla de enlace
+ db.prepare('DELETE FROM padres_estudiantes WHERE padre_usuario_id = ?').run(user.id);
+ // 2. Desvincular campo legacy en estudiantes
+ db.prepare('UPDATE estudiantes SET padre_usuario_id = NULL WHERE padre_usuario_id = ?').run(user.id);
+ } else if (user.rol === 'estudiante') {
+ // 3. Desvincular usuario de su ficha de estudiante
+ db.prepare('UPDATE estudiantes SET usuario_id = NULL WHERE usuario_id = ?').run(user.id);
+ }
+
+ // 4. Limpiar tokens de notificaciones push asociados a este usuario
+ try {
+ if (user.id) {
+ db.prepare('DELETE FROM push_subscriptions WHERE usuario_id = ?').run(user.id);
+ }
+ } catch (e) {}
+
+ // 5. Eliminar registro del usuario en tabla usuarios
+ db.prepare('DELETE FROM usuarios WHERE id = ?').run(user.id);
+
+ console.log(`[Seguridad] Cuenta eliminada: ID=${user.id}, Usuario=${user.username}, Rol=${user.rol}, Motivo=${motivo || 'No especificado'}`);
+
+ res.json({
+ success: true,
+ mensaje: 'Tu cuenta y datos personales han sido eliminados de forma definitiva de SiboPay.'
+ });
+ } catch (err) {
+ console.error('[Error eliminar cuenta]:', err);
+ res.status(500).json({ error: 'Error procesando la eliminación: ' + err.message });
+ }
+});
+
+// Solicitud pública de eliminación de cuenta desde web (Requisito Google Play Console)
+app.post('/api/public/solicitar-eliminacion-cuenta', (req, res) => {
+ try {
+ const { identificador, motivo, confirmacion } = req.body;
+ if (!identificador) {
+ return res.status(400).json({ error: 'Por favor ingresa tu nombre de usuario, correo electrónico o teléfono registrado.' });
+ }
+
+ const cleanId = String(identificador).trim().toLowerCase();
+ const user = db.prepare(`
+ SELECT id, username, rol, email, telefono FROM usuarios
+ WHERE LOWER(username) = ? OR LOWER(email) = ? OR telefono = ?
+ `).get(cleanId, cleanId, cleanId);
+
+ if (user) {
+ if (confirmacion === true || String(confirmacion).toUpperCase() === 'ELIMINAR') {
+ if (user.rol === 'padre') {
+ db.prepare('DELETE FROM padres_estudiantes WHERE padre_usuario_id = ?').run(user.id);
+ db.prepare('UPDATE estudiantes SET padre_usuario_id = NULL WHERE padre_usuario_id = ?').run(user.id);
+ } else if (user.rol === 'estudiante') {
+ db.prepare('UPDATE estudiantes SET usuario_id = NULL WHERE usuario_id = ?').run(user.id);
+ }
+ db.prepare('DELETE FROM usuarios WHERE id = ?').run(user.id);
+
+ return res.json({
+ success: true,
+ mensaje: 'Tu cuenta ha sido localizada y eliminada de forma permanente junto con todos sus datos asociados.'
+ });
+ }
+ }
+
+ res.json({
+ success: true,
+ mensaje: 'Hemos recibido tu solicitud de supresión de datos. Si los datos coinciden con un usuario activo, se procesará en menos de 24 horas laborables.'
+ });
+ } catch (err) {
+ res.status(500).json({ error: err.message });
+ }
+});
+
// Vincular estudiante a la cuenta de padre mediante QR o código de carné
app.post('/api/padres/vincular-hijo', (req, res) => {
try {
@@ -3755,6 +3851,89 @@ app.post('/api/ordenes', (req, res) => {
}
});
+// ==========================================
+// RESILIENCIA OFFLINE: SINCRONIZACIÓN BATCH DE VENTAS OFFLINE DE LA SODA
+// ==========================================
+app.post('/api/ordenes/sincronizar-offline', (req, res) => {
+ try {
+ const { ordenes, escuela_id } = req.body;
+ if (!Array.isArray(ordenes) || ordenes.length === 0) {
+ return res.status(400).json({ error: 'No se enviaron órdenes para sincronizar' });
+ }
+
+ const resultados = [];
+ const errores = [];
+
+ for (const ord of ordenes) {
+ try {
+ const estId = ord.estudiante_id;
+ if (!estId) {
+ errores.push({ offline_id: ord.offline_id, error: 'Falta estudiante_id' });
+ continue;
+ }
+
+ // Idempotencia: Verificar si esta orden offline ya fue procesada antes
+ if (ord.offline_id) {
+ const yaExiste = db.prepare(`
+ SELECT id, codigo_orden FROM ordenes
+ WHERE notas LIKE ? OR codigo_orden = ?
+ `).get(`%${ord.offline_id}%`, ord.offline_id);
+
+ if (yaExiste) {
+ resultados.push({
+ offline_id: ord.offline_id,
+ status: 'ya_procesada',
+ codigo_orden: yaExiste.codigo_orden
+ });
+ continue;
+ }
+ }
+
+ const itemsProc = (ord.items || []).map(i => ({
+ producto_id: i.producto_id || (i.product && i.product.id),
+ cantidad: i.cantidad || 1
+ }));
+
+ const resultado = crearOrdenCompleta({
+ estudianteId: estId,
+ tipoOrden: ord.tipo_orden || 'mostrador',
+ momentoEntrega: ord.momento_entrega || 'inmediato',
+ notas: `Venta offline sincronizada [Ref: ${ord.offline_id || 'LOCAL'}]`,
+ items: itemsProc
+ });
+
+ // Notificar por SSE a la soda y pantallas
+ broadcastEvent('nueva_orden', resultado);
+
+ resultados.push({
+ offline_id: ord.offline_id,
+ status: 'creada',
+ codigo_orden: resultado.codigo_orden,
+ estudiante_id: estId,
+ total: resultado.total_colones
+ });
+ } catch (errOrd) {
+ console.error(`[Offline Sync] Error procesando orden ${ord.offline_id}:`, errOrd.message);
+ errores.push({
+ offline_id: ord.offline_id,
+ error: errOrd.message
+ });
+ }
+ }
+
+ res.json({
+ success: true,
+ total_enviadas: ordenes.length,
+ sincronizadas: resultados.length,
+ fallidas: errores.length,
+ resultados,
+ errores
+ });
+ } catch (err) {
+ res.status(500).json({ error: 'Error general en sincronización offline: ' + err.message });
+ }
+});
+
// Listar órdenes (con filtro por estado o tipo)
app.get('/api/ordenes', (req, res) => {
try {
@@ -3971,6 +4150,11 @@ app.get(['/legal', '/terminos', '/privacidad', '/terminos-y-condiciones', '/poli
res.sendFile(path.join(__dirname, '../public/legal.html'));
});
+// Ruta dedicada para Solicitud de Eliminación de Cuenta (Requisito Google Play Console y Apple)
+app.get(['/eliminar-cuenta', '/borrar-cuenta', '/solicitar-eliminacion', '/delete-account'], (req, res) => {
+ res.sendFile(path.join(__dirname, '../public/eliminar-cuenta.html'));
+});
+
// Iniciar servidor
app.listen(PORT, () => {
console.log(`🚀 Servidor SiboPay iniciado en http://localhost:${PORT}`);