fix(balance): actualizacion de saldo y disponible hoy en tiempo real via SSE y correccion de zona horaria local
This commit is contained in:
@@ -1840,3 +1840,15 @@ body.dark-mode .selected-student-banner {
|
|||||||
border-color: #38bdf8;
|
border-color: #38bdf8;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Animación de actualización de saldo y disponible en tiempo real */
|
||||||
|
@keyframes balancePulseHighlight {
|
||||||
|
0% { transform: scale(1); filter: drop-shadow(0 0 0 rgba(56, 189, 248, 0)); }
|
||||||
|
35% { transform: scale(1.08); filter: drop-shadow(0 0 10px rgba(56, 189, 248, 0.9)); color: #0284c7; }
|
||||||
|
100% { transform: scale(1); filter: drop-shadow(0 0 0 rgba(56, 189, 248, 0)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-updated {
|
||||||
|
animation: balancePulseHighlight 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -10,7 +10,7 @@
|
|||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||||
<meta name="apple-mobile-web-app-title" content="RecreoPay">
|
<meta name="apple-mobile-web-app-title" content="RecreoPay">
|
||||||
<meta name="mobile-web-app-capable" content="yes">
|
<meta name="mobile-web-app-capable" content="yes">
|
||||||
<link rel="stylesheet" href="/css/styles.css?v=8.4">
|
<link rel="stylesheet" href="/css/styles.css?v=8.5">
|
||||||
<style>
|
<style>
|
||||||
/* Transiciones suaves */
|
/* Transiciones suaves */
|
||||||
.fade-enter { animation: fadeIn 0.2s ease-in-out; }
|
.fade-enter { animation: fadeIn 0.2s ease-in-out; }
|
||||||
@@ -1098,8 +1098,8 @@
|
|||||||
</button>
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<script src="/js/sounds.js?v=8.4"></script>
|
<script src="/js/sounds.js?v=8.5"></script>
|
||||||
<script src="/js/jsQR.js"></script>
|
<script src="/js/jsQR.js"></script>
|
||||||
<script src="/js/app.js?v=8.4"></script>
|
<script src="/js/app.js?v=8.5"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+120
-6
@@ -390,9 +390,15 @@ function updateStudentUI() {
|
|||||||
const transferBtn = document.getElementById('transferBtnText');
|
const transferBtn = document.getElementById('transferBtnText');
|
||||||
if (transferBtn) transferBtn.textContent = 'Transferir ⚡';
|
if (transferBtn) transferBtn.textContent = 'Transferir ⚡';
|
||||||
|
|
||||||
// Límite diario
|
// Límite diario y disponible hoy
|
||||||
document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`;
|
const limiteDiario = currentStudent.limite_diario_colones || 0;
|
||||||
document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${currentStudent.disponible_hoy.toLocaleString('es-CR')}`;
|
const gastadoHoy = currentStudent.gastado_hoy || 0;
|
||||||
|
const disponibleHoy = (typeof currentStudent.disponible_hoy === 'number')
|
||||||
|
? currentStudent.disponible_hoy
|
||||||
|
: Math.max(0, limiteDiario - gastadoHoy);
|
||||||
|
|
||||||
|
document.getElementById('dailyLimitText').textContent = `₡${limiteDiario.toLocaleString('es-CR')}`;
|
||||||
|
document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${disponibleHoy.toLocaleString('es-CR')}`;
|
||||||
|
|
||||||
// Alerta de Tarjeta Bloqueada
|
// Alerta de Tarjeta Bloqueada
|
||||||
const bannerBlocked = document.getElementById('bannerCardBlocked');
|
const bannerBlocked = document.getElementById('bannerCardBlocked');
|
||||||
@@ -1384,17 +1390,106 @@ async function onToggleAllowTransfer(checked) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function triggerBalancePulse() {
|
||||||
|
const el = document.getElementById('walletBalance');
|
||||||
|
if (el) {
|
||||||
|
el.classList.remove('balance-updated');
|
||||||
|
void el.offsetWidth;
|
||||||
|
el.classList.add('balance-updated');
|
||||||
|
}
|
||||||
|
const dispEl = document.getElementById('dailyAvailableText');
|
||||||
|
if (dispEl) {
|
||||||
|
dispEl.classList.remove('balance-updated');
|
||||||
|
void dispEl.offsetWidth;
|
||||||
|
dispEl.classList.add('balance-updated');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SSE en tiempo real para eventos de la soda y monederos
|
// SSE en tiempo real para eventos de la soda y monederos
|
||||||
function initStudentSSE() {
|
function initStudentSSE() {
|
||||||
const sse = new EventSource('/api/events');
|
const sse = new EventSource('/api/events');
|
||||||
|
|
||||||
|
// Cobro inmediato en caja / pre-orden realizada
|
||||||
|
sse.addEventListener('nueva_orden', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(e.data);
|
||||||
|
const estId = data.estudiante_id || (data.financiero && data.financiero.estudiante && data.financiero.estudiante.id);
|
||||||
|
|
||||||
|
// Si el estudiante en pantalla fue a quien se le cobró
|
||||||
|
if (currentStudent && currentStudent.id === estId) {
|
||||||
|
if (window.sounds) window.sounds.playCoin();
|
||||||
|
|
||||||
|
if (data.financiero && data.financiero.estudiante) {
|
||||||
|
const f = data.financiero.estudiante;
|
||||||
|
currentStudent.saldo_colones = f.saldo_nuevo;
|
||||||
|
currentStudent.gastado_hoy = f.gastado_hoy;
|
||||||
|
currentStudent.disponible_hoy = (typeof f.disponible_hoy === 'number')
|
||||||
|
? f.disponible_hoy
|
||||||
|
: Math.max(0, (f.limite_diario || currentStudent.limite_diario_colones || 0) - (f.gastado_hoy || 0));
|
||||||
|
updateStudentUI();
|
||||||
|
triggerBalancePulse();
|
||||||
|
}
|
||||||
|
selectStudent(currentStudent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si es padre de este estudiante
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
loadParentDashboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si es admin
|
||||||
|
if (currentUser && currentUser.rol === 'admin') {
|
||||||
|
loadAdminData();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Error en SSE nueva_orden:', err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Saldo actualizado (débito, recarga, ajuste de límite)
|
||||||
|
sse.addEventListener('saldo_actualizado', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(e.data);
|
||||||
|
const estId = data.estudiante_id || data.id;
|
||||||
|
|
||||||
|
if (currentStudent && currentStudent.id === estId) {
|
||||||
|
if (window.sounds) window.sounds.playCoin();
|
||||||
|
if (typeof data.saldo_colones === 'number') currentStudent.saldo_colones = data.saldo_colones;
|
||||||
|
if (typeof data.disponible_hoy === 'number') currentStudent.disponible_hoy = data.disponible_hoy;
|
||||||
|
if (typeof data.gastado_hoy === 'number') currentStudent.gastado_hoy = data.gastado_hoy;
|
||||||
|
updateStudentUI();
|
||||||
|
triggerBalancePulse();
|
||||||
|
selectStudent(currentStudent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
loadParentDashboard();
|
||||||
|
}
|
||||||
|
if (currentUser && currentUser.rol === 'admin') {
|
||||||
|
loadAdminData();
|
||||||
|
}
|
||||||
|
} catch (err) {}
|
||||||
|
});
|
||||||
|
|
||||||
sse.addEventListener('transferencia_realizada', (e) => {
|
sse.addEventListener('transferencia_realizada', (e) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (currentStudent && data.receptor.id === currentStudent.id) {
|
if (currentStudent && data.receptor && data.receptor.id === currentStudent.id) {
|
||||||
if (window.sounds) window.sounds.playCoin();
|
if (window.sounds) window.sounds.playCoin();
|
||||||
alert(`🔔 ¡Te pasaron plata!\n${data.emisor.nombre} te transfirió ₡${data.monto.toLocaleString('es-CR')}.\nMotivo: ${data.motivo}`);
|
alert(`🔔 ¡Te pasaron plata!\n${data.emisor.nombre} te transfirió ₡${data.monto.toLocaleString('es-CR')}.\nMotivo: ${data.motivo}`);
|
||||||
selectStudent(currentStudent.id);
|
selectStudent(currentStudent.id);
|
||||||
|
triggerBalancePulse();
|
||||||
|
} else if (currentStudent && data.emisor && data.emisor.id === currentStudent.id) {
|
||||||
|
if (typeof data.emisor.saldo_nuevo === 'number') {
|
||||||
|
currentStudent.saldo_colones = data.emisor.saldo_nuevo;
|
||||||
|
updateStudentUI();
|
||||||
|
triggerBalancePulse();
|
||||||
|
}
|
||||||
|
selectStudent(currentStudent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
loadParentDashboard();
|
||||||
}
|
}
|
||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
});
|
});
|
||||||
@@ -1402,10 +1497,19 @@ function initStudentSSE() {
|
|||||||
sse.addEventListener('recarga_exitosa', (e) => {
|
sse.addEventListener('recarga_exitosa', (e) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (currentStudent && data.estudiante_id === currentStudent.id) {
|
const estId = data.estudiante_id || data.id;
|
||||||
|
if (currentStudent && currentStudent.id === estId) {
|
||||||
if (window.sounds) window.sounds.playCoin();
|
if (window.sounds) window.sounds.playCoin();
|
||||||
|
if (typeof data.saldo_nuevo === 'number') {
|
||||||
|
currentStudent.saldo_colones = data.saldo_nuevo;
|
||||||
|
updateStudentUI();
|
||||||
|
triggerBalancePulse();
|
||||||
|
}
|
||||||
selectStudent(currentStudent.id);
|
selectStudent(currentStudent.id);
|
||||||
}
|
}
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
loadParentDashboard();
|
||||||
|
}
|
||||||
if (currentUser && currentUser.rol === 'admin') {
|
if (currentUser && currentUser.rol === 'admin') {
|
||||||
loadAdminData();
|
loadAdminData();
|
||||||
}
|
}
|
||||||
@@ -1435,9 +1539,19 @@ function initStudentSSE() {
|
|||||||
sse.addEventListener('estudiante_actualizado', (e) => {
|
sse.addEventListener('estudiante_actualizado', (e) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
if (currentStudent && currentStudent.id === data.id) {
|
const estId = data.id || data.estudiante_id;
|
||||||
|
if (currentStudent && currentStudent.id === estId) {
|
||||||
|
if (typeof data.saldo_colones === 'number') currentStudent.saldo_colones = data.saldo_colones;
|
||||||
|
if (typeof data.disponible_hoy === 'number') currentStudent.disponible_hoy = data.disponible_hoy;
|
||||||
|
if (typeof data.gastado_hoy === 'number') currentStudent.gastado_hoy = data.gastado_hoy;
|
||||||
|
if (typeof data.limite_diario_colones === 'number') currentStudent.limite_diario_colones = data.limite_diario_colones;
|
||||||
|
updateStudentUI();
|
||||||
|
triggerBalancePulse();
|
||||||
selectStudent(currentStudent.id);
|
selectStudent(currentStudent.id);
|
||||||
}
|
}
|
||||||
|
if (currentUser && currentUser.rol === 'padre') {
|
||||||
|
loadParentDashboard();
|
||||||
|
}
|
||||||
if (currentUser && currentUser.rol === 'admin') {
|
if (currentUser && currentUser.rol === 'admin') {
|
||||||
loadAdminData();
|
loadAdminData();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -974,4 +974,28 @@ function initSSE() {
|
|||||||
sseSource.addEventListener('orden_actualizada', () => {
|
sseSource.addEventListener('orden_actualizada', () => {
|
||||||
loadPreOrders();
|
loadPreOrders();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
sseSource.addEventListener('estudiante_actualizado', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(e.data);
|
||||||
|
const estId = data.id || data.estudiante_id;
|
||||||
|
if (scannedStudent && scannedStudent.id === estId) {
|
||||||
|
if (typeof data.saldo_colones === 'number') scannedStudent.saldo_colones = data.saldo_colones;
|
||||||
|
if (typeof data.disponible_hoy === 'number') scannedStudent.disponible_hoy = data.disponible_hoy;
|
||||||
|
renderScannedStudent();
|
||||||
|
}
|
||||||
|
} catch (err) {}
|
||||||
|
});
|
||||||
|
|
||||||
|
sseSource.addEventListener('saldo_actualizado', (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(e.data);
|
||||||
|
const estId = data.id || data.estudiante_id;
|
||||||
|
if (scannedStudent && scannedStudent.id === estId) {
|
||||||
|
if (typeof data.saldo_colones === 'number') scannedStudent.saldo_colones = data.saldo_colones;
|
||||||
|
if (typeof data.disponible_hoy === 'number') scannedStudent.disponible_hoy = data.disponible_hoy;
|
||||||
|
renderScannedStudent();
|
||||||
|
}
|
||||||
|
} catch (err) {}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -318,8 +318,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/js/sounds.js?v=8.3"></script>
|
<script src="/js/sounds.js?v=8.5"></script>
|
||||||
<script src="/js/jsQR.js"></script>
|
<script src="/js/jsQR.js"></script>
|
||||||
<script src="/js/pos.js?v=8.3"></script>
|
<script src="/js/pos.js?v=8.5"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+9
-8
@@ -328,17 +328,13 @@ function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcio
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Verificar límite diario
|
// 3. Verificar límite diario
|
||||||
const startOfDay = new Date();
|
|
||||||
startOfDay.setHours(0, 0, 0, 0);
|
|
||||||
const startOfDayISO = startOfDay.toISOString().replace('T', ' ').substring(0, 19);
|
|
||||||
|
|
||||||
const gastoHoyRow = db.prepare(`
|
const gastoHoyRow = db.prepare(`
|
||||||
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total_gastado_hoy
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total_gastado_hoy
|
||||||
FROM transacciones_saldo
|
FROM transacciones_saldo
|
||||||
WHERE estudiante_id = ? AND monto_colones < 0 AND fecha >= ?
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
`).get(estudianteId, startOfDayISO);
|
`).get(estudianteId);
|
||||||
|
|
||||||
const totalGastadoHoy = gastoHoyRow.total_gastado_hoy;
|
const totalGastadoHoy = gastoHoyRow ? gastoHoyRow.total_gastado_hoy : 0;
|
||||||
if (totalGastadoHoy + montoTotal > est.limite_diario_colones) {
|
if (totalGastadoHoy + montoTotal > est.limite_diario_colones) {
|
||||||
const disponibleHoy = Math.max(0, est.limite_diario_colones - totalGastadoHoy);
|
const disponibleHoy = Math.max(0, est.limite_diario_colones - totalGastadoHoy);
|
||||||
throw new Error(`Límite diario superado. Su límite por día es ₡${est.limite_diario_colones.toLocaleString('es-CR')}. Disponible hoy: ₡${disponibleHoy.toLocaleString('es-CR')}`);
|
throw new Error(`Límite diario superado. Su límite por día es ₡${est.limite_diario_colones.toLocaleString('es-CR')}. Disponible hoy: ₡${disponibleHoy.toLocaleString('es-CR')}`);
|
||||||
@@ -363,6 +359,9 @@ function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcio
|
|||||||
descripcion || 'Compra en soda escolar'
|
descripcion || 'Compra en soda escolar'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const nuevoGastadoHoy = totalGastadoHoy + montoTotal;
|
||||||
|
const nuevoDisponibleHoy = Math.max(0, est.limite_diario_colones - nuevoGastadoHoy);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
exito: true,
|
exito: true,
|
||||||
estudiante: {
|
estudiante: {
|
||||||
@@ -374,7 +373,8 @@ function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcio
|
|||||||
saldo_anterior: est.saldo_colones,
|
saldo_anterior: est.saldo_colones,
|
||||||
saldo_nuevo: nuevoSaldo,
|
saldo_nuevo: nuevoSaldo,
|
||||||
limite_diario: est.limite_diario_colones,
|
limite_diario: est.limite_diario_colones,
|
||||||
gastado_hoy: totalGastadoHoy + montoTotal
|
gastado_hoy: nuevoGastadoHoy,
|
||||||
|
disponible_hoy: nuevoDisponibleHoy
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -510,6 +510,7 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
|||||||
return {
|
return {
|
||||||
orden_id: ordenId,
|
orden_id: ordenId,
|
||||||
codigo_orden: codigoOrden,
|
codigo_orden: codigoOrden,
|
||||||
|
estudiante_id: estudianteId,
|
||||||
tipo_orden: tipoOrden,
|
tipo_orden: tipoOrden,
|
||||||
momento_entrega: momentoEntrega,
|
momento_entrega: momentoEntrega,
|
||||||
estado: estadoInicial,
|
estado: estadoInicial,
|
||||||
|
|||||||
+80
-5
@@ -76,6 +76,15 @@ app.post('/api/auth/login', (req, res) => {
|
|||||||
if (!estudiante) {
|
if (!estudiante) {
|
||||||
estudiante = db.prepare('SELECT * FROM estudiantes ORDER BY id ASC LIMIT 1').get();
|
estudiante = db.prepare('SELECT * FROM estudiantes ORDER BY id ASC LIMIT 1').get();
|
||||||
}
|
}
|
||||||
|
if (estudiante) {
|
||||||
|
const gastoHoy = db.prepare(`
|
||||||
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
|
FROM transacciones_saldo
|
||||||
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
|
`).get(estudiante.id).total;
|
||||||
|
estudiante.gastado_hoy = gastoHoy;
|
||||||
|
estudiante.disponible_hoy = Math.max(0, (estudiante.limite_diario_colones || 0) - gastoHoy);
|
||||||
|
}
|
||||||
} else if (user.rol === 'padre') {
|
} else if (user.rol === 'padre') {
|
||||||
hijos = db.prepare(`
|
hijos = db.prepare(`
|
||||||
SELECT e.*
|
SELECT e.*
|
||||||
@@ -87,6 +96,18 @@ app.post('/api/auth/login', (req, res) => {
|
|||||||
if (hijos.length === 0) {
|
if (hijos.length === 0) {
|
||||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(user.id);
|
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(user.id);
|
||||||
}
|
}
|
||||||
|
hijos = hijos.map(h => {
|
||||||
|
const gastoHoy = db.prepare(`
|
||||||
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
|
FROM transacciones_saldo
|
||||||
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
|
`).get(h.id).total;
|
||||||
|
return {
|
||||||
|
...h,
|
||||||
|
gastado_hoy: gastoHoy,
|
||||||
|
disponible_hoy: Math.max(0, (h.limite_diario_colones || 0) - gastoHoy)
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
@@ -230,7 +251,20 @@ app.get('/api/padres/mis-hijos', (req, res) => {
|
|||||||
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(padre_usuario_id);
|
hijos = db.prepare('SELECT * FROM estudiantes WHERE padre_usuario_id = ?').all(padre_usuario_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ success: true, hijos });
|
const hijosEnriquecidos = hijos.map(h => {
|
||||||
|
const gastoHoy = db.prepare(`
|
||||||
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
|
FROM transacciones_saldo
|
||||||
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
|
`).get(h.id).total;
|
||||||
|
return {
|
||||||
|
...h,
|
||||||
|
gastado_hoy: gastoHoy,
|
||||||
|
disponible_hoy: Math.max(0, (h.limite_diario_colones || 0) - gastoHoy)
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ success: true, hijos: hijosEnriquecidos });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({ error: err.message });
|
res.status(500).json({ error: err.message });
|
||||||
}
|
}
|
||||||
@@ -513,6 +547,8 @@ app.post('/api/admin/estudiantes/:id/recarga-manual', (req, res) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
broadcastEvent('recarga_exitosa', resultado);
|
broadcastEvent('recarga_exitosa', resultado);
|
||||||
|
broadcastEvent('estudiante_actualizado', { id: est.id, estudiante_id: est.id, saldo_colones: nuevoSaldo });
|
||||||
|
broadcastEvent('saldo_actualizado', { id: est.id, estudiante_id: est.id, saldo_colones: nuevoSaldo });
|
||||||
res.json(resultado);
|
res.json(resultado);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({ error: err.message });
|
res.status(500).json({ error: err.message });
|
||||||
@@ -532,13 +568,17 @@ app.get('/api/estudiantes', (req, res) => {
|
|||||||
SELECT SUM(ABS(monto_colones))
|
SELECT SUM(ABS(monto_colones))
|
||||||
FROM transacciones_saldo
|
FROM transacciones_saldo
|
||||||
WHERE estudiante_id = e.id AND monto_colones < 0
|
WHERE estudiante_id = e.id AND monto_colones < 0
|
||||||
AND date(fecha) = date('now', 'localtime')
|
AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
), 0) as gastado_hoy
|
), 0) as gastado_hoy
|
||||||
FROM estudiantes e
|
FROM estudiantes e
|
||||||
WHERE activo = 1
|
WHERE activo = 1
|
||||||
ORDER BY grado, seccion, nombre_completo
|
ORDER BY grado, seccion, nombre_completo
|
||||||
`).all();
|
`).all();
|
||||||
res.json(list);
|
const listWithDisp = list.map(e => ({
|
||||||
|
...e,
|
||||||
|
disponible_hoy: Math.max(0, (e.limite_diario_colones || 0) - (e.gastado_hoy || 0))
|
||||||
|
}));
|
||||||
|
res.json(listWithDisp);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
@@ -554,7 +594,7 @@ app.get('/api/estudiantes/:id', (req, res) => {
|
|||||||
const gastoHoy = db.prepare(`
|
const gastoHoy = db.prepare(`
|
||||||
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
FROM transacciones_saldo
|
FROM transacciones_saldo
|
||||||
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha) = date('now', 'localtime')
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
`).get(est.id).total;
|
`).get(est.id).total;
|
||||||
|
|
||||||
// Transacciones recientes
|
// Transacciones recientes
|
||||||
@@ -596,7 +636,7 @@ app.get('/api/estudiantes/qr/:token', (req, res) => {
|
|||||||
const gastoHoy = db.prepare(`
|
const gastoHoy = db.prepare(`
|
||||||
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
FROM transacciones_saldo
|
FROM transacciones_saldo
|
||||||
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha) = date('now', 'localtime')
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
`).get(est.id).total;
|
`).get(est.id).total;
|
||||||
|
|
||||||
// Verificar si tiene pre-órdenes listas para retirar en el recreo
|
// Verificar si tiene pre-órdenes listas para retirar en el recreo
|
||||||
@@ -662,6 +702,8 @@ app.post('/api/estudiantes/:id/recarga', (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
broadcastEvent('recarga_exitosa', resultado);
|
broadcastEvent('recarga_exitosa', resultado);
|
||||||
|
broadcastEvent('estudiante_actualizado', { id: estudianteId, estudiante_id: estudianteId, saldo_colones: resultado.saldo_nuevo });
|
||||||
|
broadcastEvent('saldo_actualizado', { id: estudianteId, estudiante_id: estudianteId, saldo_colones: resultado.saldo_nuevo });
|
||||||
res.json(resultado);
|
res.json(resultado);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
@@ -684,6 +726,16 @@ app.put('/api/estudiantes/:id/limite', (req, res) => {
|
|||||||
`).run(limite_diario_colones, alergias, bloquear_chucherias, permitir_transferencias, estId);
|
`).run(limite_diario_colones, alergias, bloquear_chucherias, permitir_transferencias, estId);
|
||||||
|
|
||||||
const actualizado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId);
|
const actualizado = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estId);
|
||||||
|
if (actualizado) {
|
||||||
|
const gastoHoy = db.prepare(`
|
||||||
|
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total
|
||||||
|
FROM transacciones_saldo
|
||||||
|
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||||
|
`).get(estId).total;
|
||||||
|
actualizado.gastado_hoy = gastoHoy;
|
||||||
|
actualizado.disponible_hoy = Math.max(0, (actualizado.limite_diario_colones || 0) - gastoHoy);
|
||||||
|
broadcastEvent('estudiante_actualizado', actualizado);
|
||||||
|
}
|
||||||
res.json(actualizado);
|
res.json(actualizado);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
@@ -707,6 +759,12 @@ app.post('/api/transferencias', (req, res) => {
|
|||||||
|
|
||||||
// Notificar en tiempo real por SSE
|
// Notificar en tiempo real por SSE
|
||||||
broadcastEvent('transferencia_realizada', resultado);
|
broadcastEvent('transferencia_realizada', resultado);
|
||||||
|
if (resultado.emisor) {
|
||||||
|
broadcastEvent('estudiante_actualizado', { id: resultado.emisor.id, estudiante_id: resultado.emisor.id, saldo_colones: resultado.emisor.saldo_nuevo });
|
||||||
|
}
|
||||||
|
if (resultado.receptor) {
|
||||||
|
broadcastEvent('estudiante_actualizado', { id: resultado.receptor.id, estudiante_id: resultado.receptor.id, saldo_colones: resultado.receptor.saldo_nuevo });
|
||||||
|
}
|
||||||
|
|
||||||
res.json(resultado);
|
res.json(resultado);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -765,6 +823,23 @@ app.post('/api/ordenes', (req, res) => {
|
|||||||
// Notificar en tiempo real a la pantalla de cocina/caja de la soda
|
// Notificar en tiempo real a la pantalla de cocina/caja de la soda
|
||||||
broadcastEvent('nueva_orden', resultado);
|
broadcastEvent('nueva_orden', resultado);
|
||||||
|
|
||||||
|
// Notificar actualización de estudiante (saldo y disponible) en tiempo real a clientes
|
||||||
|
if (resultado && resultado.financiero && resultado.financiero.estudiante) {
|
||||||
|
const fEst = resultado.financiero.estudiante;
|
||||||
|
const payloadActualizacion = {
|
||||||
|
id: targetEstudianteId,
|
||||||
|
estudiante_id: targetEstudianteId,
|
||||||
|
saldo_colones: fEst.saldo_nuevo,
|
||||||
|
gastado_hoy: fEst.gastado_hoy,
|
||||||
|
disponible_hoy: (typeof fEst.disponible_hoy === 'number')
|
||||||
|
? fEst.disponible_hoy
|
||||||
|
: Math.max(0, (fEst.limite_diario || 0) - (fEst.gastado_hoy || 0)),
|
||||||
|
orden: resultado
|
||||||
|
};
|
||||||
|
broadcastEvent('estudiante_actualizado', payloadActualizacion);
|
||||||
|
broadcastEvent('saldo_actualizado', payloadActualizacion);
|
||||||
|
}
|
||||||
|
|
||||||
res.status(201).json(resultado);
|
res.status(201).json(resultado);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
|
|||||||
Reference in New Issue
Block a user