feat: eliminar cuenta (Google Play compliance), resiliencia offline soda y experiencia haptica sensorial
This commit is contained in:
@@ -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 });
|
||||
|
||||
|
||||
+274
-26
@@ -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 = '<span style="width: 8px; height: 8px; border-radius: 50%; background: #16a34a; display: inline-block;"></span> <span>En Línea</span>';
|
||||
} else {
|
||||
badge.className = 'pos-network-pill offline';
|
||||
badge.innerHTML = '<span style="width: 8px; height: 8px; border-radius: 50%; background: #d97706; display: inline-block;"></span> <span>Modo Offline</span>';
|
||||
}
|
||||
}
|
||||
|
||||
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 });
|
||||
|
||||
+261
-23
@@ -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)
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user