feat: saldo flotante en preordenes, bloqueo de QR por limite diario, cierre de caja y terminos sin canje en efectivo
This commit is contained in:
+56
-6
@@ -1042,6 +1042,7 @@
|
||||
<div class="parent-balance-amount-display">
|
||||
<span id="parentActiveChildBalance">₡0</span>
|
||||
</div>
|
||||
<div id="parentActiveChildRetenidoNote" style="display: none; font-size: 0.74rem; color: #b45309; background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; padding: 4px 10px; margin-top: 4px; font-weight: 700;"></div>
|
||||
|
||||
<div class="parent-balance-footer-row">
|
||||
<div class="parent-balance-limit-info">
|
||||
@@ -1156,9 +1157,9 @@
|
||||
<!-- Grid de métricas rápidas del estudiante -->
|
||||
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 18px;">
|
||||
<div style="background: var(--bg-main, #f8fafc); border: 1px solid var(--border, #e2e8f0); border-radius: 14px; padding: 14px;">
|
||||
<span style="font-size: 0.72rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Saldo Actual</span>
|
||||
<span style="font-size: 0.72rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Saldo Disponible</span>
|
||||
<div id="parentSummaryBalanceDisplay" style="font-size: 1.6rem; font-weight: 900; color: #0284c7; margin-top: 4px;">₡0</div>
|
||||
<span style="font-size: 0.68rem; color: #10b981; font-weight: 700;">● Disponible para compras</span>
|
||||
<span id="parentSummaryRetenidoSubtitle" style="font-size: 0.68rem; color: #10b981; font-weight: 700;">● Disponible para compras</span>
|
||||
</div>
|
||||
<div style="background: var(--bg-main, #f8fafc); border: 1px solid var(--border, #e2e8f0); border-radius: 14px; padding: 14px;">
|
||||
<span style="font-size: 0.72rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Límite por Día</span>
|
||||
@@ -1451,6 +1452,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 6. No Canjeable por Efectivo -->
|
||||
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
||||
<div style="width: 22px; height: 22px; border-radius: 50%; background: #fee2e2; color: #991b1b; font-weight: 900; font-size: 0.72rem; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-top: 1px;">
|
||||
6
|
||||
</div>
|
||||
<div>
|
||||
<strong style="color: #991b1b; display: block; font-size: 0.82rem;">No Canjeable por Dinero Real o Efectivo:</strong>
|
||||
<span>Los fondos recargados corresponden a créditos escolares exclusivos para consumo de alimentos en la soda. <strong>No pueden ser convertidos ni devueltos en dinero en efectivo</strong> bajo ninguna circunstancia.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Pie de Seguridad -->
|
||||
@@ -1772,6 +1784,11 @@
|
||||
<span id="walletBalance">₡0</span>
|
||||
<span class="kids-coin-icon" id="kidsCoinIcon" style="display: none;"></span>
|
||||
</div>
|
||||
<!-- Desglose transparente cuando hay pre-órdenes flotantes -->
|
||||
<div id="breakdownSaldoBox" style="display: none; font-size: 0.72rem; margin-top: 5px; line-height: 1.35; background: rgba(0, 0, 0, 0.22); padding: 5px 8px; border-radius: 8px; backdrop-filter: blur(4px);">
|
||||
<div style="color: rgba(255, 255, 255, 0.95);">Saldo total: <strong id="lblSaldoTotalBreakdown">₡0</strong></div>
|
||||
<div style="color: #fef08a;">Retenido en pre-órdenes: <strong id="lblSaldoRetenidoBreakdown">₡0</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end;">
|
||||
@@ -1798,6 +1815,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- BANNER DE ALERTA: LÍMITE DIARIO ALCANZADO (QR BLOQUEADO) -->
|
||||
<div id="bannerQrDailyLimitBlocked" style="display: none; margin: 0 16px 12px 16px; background: #fef2f2; border: 1.5px solid #fecaca; border-radius: 12px; padding: 10px 14px; font-size: 0.8rem; color: #991b1b; align-items: center; gap: 8px;">
|
||||
<span style="font-size: 1.3rem; line-height: 1;">⛔</span>
|
||||
<div>
|
||||
<strong style="display: block; font-size: 0.82rem; margin-bottom: 2px;">Límite diario alcanzado</strong>
|
||||
<span id="bannerQrDailyLimitMsg" style="font-size: 0.75rem; color: #7f1d1d; line-height: 1.35;">
|
||||
Has consumido tu límite de gasto de hoy. Tu código QR está bloqueado para nuevas compras hasta la siguiente jornada.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ALERGIAS (SI TIENE) -->
|
||||
<div id="allergyWarning" style="display:none; margin: 0 16px 12px 16px; background: #fffbeb; border: 1px solid #fde68a; border-radius: 12px; padding: 8px 12px; font-size: 0.8rem; color: #92400e; align-items: center; gap: 6px;">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#b45309" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg>
|
||||
@@ -1917,6 +1945,12 @@
|
||||
<div class="qr-immersive-card">
|
||||
<div class="qr-card-header-title">MI CARNÉ SIBOPAY</div>
|
||||
|
||||
<!-- Banner especial cuando el límite diario fue alcanzado pero tiene preórdenes -->
|
||||
<div id="qrPreorderOnlyBanner" style="display: none; background: #eff6ff; border: 1.5px solid #bfdbfe; color: #1e40af; border-radius: 10px; padding: 7px 10px; margin-bottom: 10px; font-size: 0.75rem; text-align: center; font-weight: 700; line-height: 1.35;">
|
||||
📦 Válido exclusivamente para retirar tu Pre-Orden en la soda.<br>
|
||||
<span style="font-size: 0.70rem; color: #3b82f6;">Compras nuevas en mostrador bloqueadas por límite diario.</span>
|
||||
</div>
|
||||
|
||||
<div class="qr-scanner-frame-wrapper">
|
||||
<div class="qr-frame-corner top-left"></div>
|
||||
<div class="qr-frame-corner top-right"></div>
|
||||
@@ -1971,13 +2005,18 @@
|
||||
<!-- Se llena dinámicamente -->
|
||||
</div>
|
||||
|
||||
<div style="border-top: 1px solid #e2e8f0; padding-top: 10px; margin-bottom: 14px; display: flex; justify-content: space-between; align-items: center;">
|
||||
<span style="font-weight: 800; color: #334155;">Total a Rebajar de Saldo:</span>
|
||||
<span id="modalCartTotal" style="font-size: 1.3rem; font-weight: 900; color: #0284c7;">₡0</span>
|
||||
<div style="border-top: 1px solid #e2e8f0; padding-top: 10px; margin-bottom: 14px; display: flex; flex-direction: column; gap: 4px;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span style="font-weight: 800; color: #334155; font-size: 0.92rem;">Total a Reservar (Monto Flotante):</span>
|
||||
<span id="modalCartTotal" style="font-size: 1.3rem; font-weight: 900; color: #0284c7;">₡0</span>
|
||||
</div>
|
||||
<div style="font-size: 0.73rem; color: #64748b; text-align: right;">
|
||||
🔒 El monto queda retenido y se rebajará definitivamente al retirar en la soda.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button id="btnConfirmarOrden" onclick="submitPreOrder()" style="width: 100%; padding: 12px; background: #10b981; color: white; border: none; border-radius: 12px; font-weight: 800; font-size: 1rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px;">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> <span>Confirmar y Pagar Pre-Orden</span>
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> <span>Confirmar Pre-Orden (Monto Flotante)</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -3083,6 +3122,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 6. No Canjeable por Efectivo -->
|
||||
<div style="display: flex; gap: 10px; align-items: flex-start;">
|
||||
<div style="width: 22px; height: 22px; border-radius: 50%; background: #fee2e2; color: #991b1b; font-weight: 900; font-size: 0.72rem; display: flex; align-items: center; justify-content: center; flex-shrink: 0; margin-top: 1px;">
|
||||
6
|
||||
</div>
|
||||
<div>
|
||||
<strong style="color: #991b1b; display: block; font-size: 0.82rem;">No Canjeable por Dinero Real o Efectivo:</strong>
|
||||
<span>Los fondos recargados corresponden a créditos escolares exclusivos para consumo de alimentos en la soda. <strong>No pueden ser convertidos ni devueltos en dinero en efectivo</strong> bajo ninguna circunstancia.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Pie de Seguridad y Botón de Aceptar -->
|
||||
|
||||
+119
-11
@@ -728,9 +728,32 @@ function updateStudentUI() {
|
||||
applyCardTheme(getSavedCardTheme());
|
||||
}
|
||||
|
||||
// Saldo en colones
|
||||
document.getElementById('walletBalance').textContent = `₡${currentStudent.saldo_colones.toLocaleString('es-CR')}`;
|
||||
document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE';
|
||||
// Saldo total, retenido y disponible para gastar
|
||||
const saldoTotal = (typeof currentStudent.saldo_total === 'number')
|
||||
? currentStudent.saldo_total
|
||||
: (currentStudent.saldo_colones || 0);
|
||||
const saldoRetenido = currentStudent.saldo_retenido || 0;
|
||||
const saldoDisponible = (typeof currentStudent.saldo_disponible === 'number')
|
||||
? currentStudent.saldo_disponible
|
||||
: Math.max(0, saldoTotal - saldoRetenido);
|
||||
|
||||
document.getElementById('walletBalance').textContent = `₡${saldoDisponible.toLocaleString('es-CR')}`;
|
||||
document.getElementById('balanceLabel').textContent = saldoRetenido > 0 ? 'DISPONIBLE PARA GASTAR' : 'SALDO DISPONIBLE';
|
||||
|
||||
// Desglose transparente cuando hay monto retenido en pre-órdenes
|
||||
const breakdownBox = document.getElementById('breakdownSaldoBox');
|
||||
if (breakdownBox) {
|
||||
if (saldoRetenido > 0) {
|
||||
breakdownBox.style.display = 'block';
|
||||
const lblTot = document.getElementById('lblSaldoTotalBreakdown');
|
||||
if (lblTot) lblTot.textContent = `₡${saldoTotal.toLocaleString('es-CR')}`;
|
||||
const lblRet = document.getElementById('lblSaldoRetenidoBreakdown');
|
||||
if (lblRet) lblRet.textContent = `₡${saldoRetenido.toLocaleString('es-CR')}`;
|
||||
} else {
|
||||
breakdownBox.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
const coin = document.getElementById('kidsCoinIcon');
|
||||
if (coin) coin.style.display = 'none';
|
||||
const qrBtn = document.getElementById('qrBtnText');
|
||||
@@ -743,11 +766,30 @@ function updateStudentUI() {
|
||||
const gastadoHoy = currentStudent.gastado_hoy || 0;
|
||||
const disponibleHoy = (typeof currentStudent.disponible_hoy === 'number')
|
||||
? currentStudent.disponible_hoy
|
||||
: Math.max(0, limiteDiario - gastadoHoy);
|
||||
: Math.max(0, limiteDiario - gastadoHoy - saldoRetenido);
|
||||
|
||||
document.getElementById('dailyLimitText').textContent = `₡${limiteDiario.toLocaleString('es-CR')}`;
|
||||
document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${disponibleHoy.toLocaleString('es-CR')}`;
|
||||
|
||||
const tienePreordenes = Boolean(currentStudent.tiene_preordenes_pendientes || (currentStudent.preordenes_pendientes_count > 0));
|
||||
const qrBloqueadoPorLimite = disponibleHoy <= 0 && !tienePreordenes;
|
||||
|
||||
// Banner informativo si alcanzó su límite diario
|
||||
const bannerLimitBlocked = document.getElementById('bannerQrDailyLimitBlocked');
|
||||
if (bannerLimitBlocked) {
|
||||
if (disponibleHoy <= 0) {
|
||||
bannerLimitBlocked.style.display = 'flex';
|
||||
const msgEl = document.getElementById('bannerQrDailyLimitMsg');
|
||||
if (msgEl) {
|
||||
msgEl.textContent = tienePreordenes
|
||||
? 'Has alcanzado tu límite diario de consumo. Tu código QR solo podrá ser escaneado en la soda para retirar tu Pre-Orden.'
|
||||
: `Has alcanzado tu límite diario de ₡${limiteDiario.toLocaleString('es-CR')} asignado por tus padres. La generación del código QR para compras está bloqueada hasta mañana.`;
|
||||
}
|
||||
} else {
|
||||
bannerLimitBlocked.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// Alerta de Tarjeta Bloqueada
|
||||
const bannerBlocked = document.getElementById('bannerCardBlocked');
|
||||
if (bannerBlocked) {
|
||||
@@ -757,12 +799,29 @@ function updateStudentUI() {
|
||||
if (currentStudent.tarjeta_bloqueada) {
|
||||
btn.style.opacity = '0.45';
|
||||
btn.style.pointerEvents = 'none';
|
||||
} else if (qrBloqueadoPorLimite) {
|
||||
btn.style.opacity = '0.55';
|
||||
btn.style.filter = 'grayscale(0.85)';
|
||||
btn.title = 'Límite diario alcanzado: no puedes generar QR para compras';
|
||||
btn.style.pointerEvents = 'auto'; // Permitir clic para mostrar el mensaje explicativo
|
||||
} else {
|
||||
btn.style.opacity = '1';
|
||||
btn.style.filter = 'none';
|
||||
btn.style.pointerEvents = 'auto';
|
||||
}
|
||||
});
|
||||
|
||||
const pwaNavQr = document.getElementById('pwaNavQr');
|
||||
if (pwaNavQr) {
|
||||
if (qrBloqueadoPorLimite) {
|
||||
pwaNavQr.style.opacity = '0.55';
|
||||
pwaNavQr.title = 'Límite diario alcanzado';
|
||||
} else {
|
||||
pwaNavQr.style.opacity = '1';
|
||||
pwaNavQr.title = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Gray-out del botón Transferir cuando los padres lo desactivan
|
||||
const btnCardTransfer = document.getElementById('btnCardTransfer');
|
||||
const pwaNavTransfer = document.getElementById('pwaNavTransfer');
|
||||
@@ -1362,7 +1421,7 @@ async function submitPreOrder() {
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
|
||||
alert(`¡Pre-Orden confirmada con éxito!\n\n📋 Código de retiro: ${data.codigo_orden}\n⏰ Horario: ${momentoBadge.full}\n💰 Total rebajado: ₡${data.total_colones.toLocaleString('es-CR')}\n\nPodrás retirarla en la soda durante el recreo programado presentando tu carné QR.`);
|
||||
alert(`¡Pre-Orden confirmada con éxito!\n\n📋 Código de retiro: ${data.codigo_orden}\n⏰ Horario: ${momentoBadge.full}\n🔒 Monto reservado (flotante): ₡${data.total_colones.toLocaleString('es-CR')}\n\nNota: Este saldo queda retenido y se rebajará formalmente en la soda al retirar tu pedido presentando tu carné QR.`);
|
||||
|
||||
// Limpiar carrito y recargar datos del estudiante o padre
|
||||
cart = [];
|
||||
@@ -1383,7 +1442,7 @@ async function submitPreOrder() {
|
||||
alert(`No se pudo procesar: ${err.message}`);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span>Confirmar y Pagar Pre-Orden</span>';
|
||||
btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span>Confirmar Pre-Orden (Monto Flotante)</span>';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1392,6 +1451,31 @@ async function submitPreOrder() {
|
||||
// ==========================================
|
||||
|
||||
function openQrModal() {
|
||||
if (currentStudent) {
|
||||
const limiteDiario = currentStudent.limite_diario_colones || 0;
|
||||
const gastadoHoy = currentStudent.gastado_hoy || 0;
|
||||
const saldoRetenido = currentStudent.saldo_retenido || 0;
|
||||
const disponibleHoy = (typeof currentStudent.disponible_hoy === 'number')
|
||||
? currentStudent.disponible_hoy
|
||||
: Math.max(0, limiteDiario - gastadoHoy - saldoRetenido);
|
||||
|
||||
const tienePreordenes = Boolean(currentStudent.tiene_preordenes_pendientes || (currentStudent.preordenes_pendientes_count > 0));
|
||||
|
||||
// Si superó su límite diario y NO tiene pre-órdenes pendientes, bloquear apertura
|
||||
if (disponibleHoy <= 0 && !tienePreordenes) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`⛔ Límite Diario Alcanzado\n\nHas consumido tu límite máximo diario de ₡${limiteDiario.toLocaleString('es-CR')} establecido por tus padres.\n\nNo es posible generar códigos QR para nuevas compras hasta la siguiente jornada escolar.`);
|
||||
resetPwaNavActive();
|
||||
return;
|
||||
}
|
||||
|
||||
// Si tiene pre-órdenes pendientes pero agotó el límite diario de mostrador, mostrar aviso informativo
|
||||
const preBanner = document.getElementById('qrPreorderOnlyBanner');
|
||||
if (preBanner) {
|
||||
preBanner.style.display = (disponibleHoy <= 0 && tienePreordenes) ? 'block' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
if (window.sounds) window.sounds.playScanChirp();
|
||||
document.getElementById('modalQr').style.display = 'flex';
|
||||
}
|
||||
@@ -2717,10 +2801,13 @@ function renderParentDashboardView() {
|
||||
</div>
|
||||
${isBlocked ? '<span style="font-size: 0.65rem; background: #fee2e2; color: #dc2626; padding: 2px 6px; border-radius: 4px; font-weight: 800; flex-shrink: 0;">BLOQUEADO</span>' : ''}
|
||||
</div>
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border); padding-top: 8px; margin-top: 2px; width: 100%;">
|
||||
<span style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">Saldo:</span>
|
||||
<div style="display: flex; justify-content: space-between; align-items: flex-end; border-top: 1px solid var(--border); padding-top: 8px; margin-top: 2px; width: 100%;">
|
||||
<div>
|
||||
<span style="font-size: 0.72rem; color: var(--text-muted); font-weight: 700; display: block;">Disponible:</span>
|
||||
${(h.saldo_retenido || 0) > 0 ? `<span style="font-size: 0.65rem; color: #b45309; font-weight: 800;">(₡${h.saldo_retenido.toLocaleString('es-CR')} retenido)</span>` : ''}
|
||||
</div>
|
||||
<strong style="font-size: 1.05rem; color: #0284c7; font-weight: 900; letter-spacing: -0.3px;">
|
||||
₡${(h.saldo_colones || 0).toLocaleString('es-CR')}
|
||||
₡${((typeof h.saldo_disponible === 'number') ? h.saldo_disponible : (h.saldo_colones - (h.saldo_retenido || 0))).toLocaleString('es-CR')}
|
||||
</strong>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2991,7 +3078,21 @@ function renderActiveChildDetails(child) {
|
||||
}
|
||||
if (name) name.textContent = child.nombre_completo;
|
||||
if (meta) meta.textContent = `${child.grado} - Sección ${child.seccion} • Cód: ${child.codigo_estudiante}`;
|
||||
if (balance) balance.textContent = `₡${(child.saldo_colones || 0).toLocaleString('es-CR')}`;
|
||||
const saldoTotal = (typeof child.saldo_total === 'number') ? child.saldo_total : (child.saldo_colones || 0);
|
||||
const saldoRetenido = child.saldo_retenido || 0;
|
||||
const saldoDisponible = (typeof child.saldo_disponible === 'number') ? child.saldo_disponible : Math.max(0, saldoTotal - saldoRetenido);
|
||||
|
||||
if (balance) balance.textContent = `₡${saldoDisponible.toLocaleString('es-CR')}`;
|
||||
|
||||
const retenidoNote = document.getElementById('parentActiveChildRetenidoNote');
|
||||
if (retenidoNote) {
|
||||
if (saldoRetenido > 0) {
|
||||
retenidoNote.style.display = 'block';
|
||||
retenidoNote.innerHTML = `🔒 Saldo total: <strong>₡${saldoTotal.toLocaleString('es-CR')}</strong> | Retenido en pre-órdenes: <strong style="color: #92400e;">₡${saldoRetenido.toLocaleString('es-CR')}</strong>`;
|
||||
} else {
|
||||
retenidoNote.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
const currentLimit = child.limite_diario_colones || 3000;
|
||||
if (lblLimit) lblLimit.textContent = `₡${currentLimit.toLocaleString('es-CR')} / día`;
|
||||
@@ -3011,7 +3112,14 @@ function renderActiveChildDetails(child) {
|
||||
const summaryName = document.getElementById('parentSummaryChildName');
|
||||
const summaryAllergies = document.getElementById('parentSummaryAllergyStatus');
|
||||
|
||||
if (summaryBalance) summaryBalance.textContent = `₡${(child.saldo_colones || 0).toLocaleString('es-CR')}`;
|
||||
if (summaryBalance) summaryBalance.textContent = `₡${saldoDisponible.toLocaleString('es-CR')}`;
|
||||
const summarySub = document.getElementById('parentSummaryRetenidoSubtitle');
|
||||
if (summarySub) {
|
||||
summarySub.textContent = saldoRetenido > 0
|
||||
? `● ₡${saldoRetenido.toLocaleString('es-CR')} retenido en pre-órdenes`
|
||||
: '● Disponible para compras';
|
||||
summarySub.style.color = saldoRetenido > 0 ? '#b45309' : '#10b981';
|
||||
}
|
||||
if (summaryLimit) summaryLimit.textContent = `₡${currentLimit.toLocaleString('es-CR')}`;
|
||||
if (summaryName) summaryName.textContent = child.nombre_completo || 'Estudiante';
|
||||
|
||||
|
||||
+153
-8
@@ -1523,18 +1523,23 @@ function renderPreOrdersList() {
|
||||
|
||||
<div class="pos-preorder-footer">
|
||||
<div class="pos-preorder-total">
|
||||
<span class="pos-preorder-total-label">Total Cobrado:</span>
|
||||
<span class="pos-preorder-total-label">${ord.estado === 'entregado' ? 'Total Cobrado:' : 'Total a Cobrar (Monto Flotante):'}</span>
|
||||
<strong class="pos-preorder-total-val">₡${ord.total_colones.toLocaleString('es-CR')}</strong>
|
||||
</div>
|
||||
<div>
|
||||
${ord.estado !== 'entregado' ? `
|
||||
<button onclick="updateOrderStatus(${ord.id}, 'entregado')" class="btn-saas pos-btn-entregar" title="Marcar como entregado al estudiante">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
|
||||
<span>Entregar Pedido</span>
|
||||
</button>
|
||||
<div style="display: flex; gap: 6px; align-items: center;">
|
||||
<button onclick="updateOrderStatus(${ord.id}, 'entregado')" class="btn-saas pos-btn-entregar" title="Cobrar y entregar pedido al estudiante">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
|
||||
<span>Cobrar y Entregar</span>
|
||||
</button>
|
||||
<button type="button" onclick="cancelarPreordenManual(${ord.id})" class="btn-saas" style="padding: 6px 10px; font-size: 0.76rem; font-weight: 700; color: #dc2626; background: #fef2f2; border: 1.5px solid #fecaca; border-radius: 8px; cursor: pointer;" title="Cancelar pre-orden y liberar saldo flotante al estudiante">
|
||||
✕ Cancelar
|
||||
</button>
|
||||
</div>
|
||||
` : `
|
||||
<span class="saas-status-badge saas-status-active" style="padding: 6px 12px; font-size: 0.8rem;">
|
||||
<span class="saas-dot"></span>Despachado en Soda
|
||||
<span class="saas-dot"></span>Cobrado y Entregado
|
||||
</span>
|
||||
`}
|
||||
</div>
|
||||
@@ -1563,19 +1568,113 @@ async function loadPreOrders() {
|
||||
|
||||
async function updateOrderStatus(orderId, nuevoEstado) {
|
||||
try {
|
||||
let cajeroId = 6;
|
||||
const storedUser = localStorage.getItem('sibopay_user') || localStorage.getItem('recreopay_user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
const u = JSON.parse(storedUser);
|
||||
if (u && u.id) cajeroId = u.id;
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/ordenes/${orderId}/estado`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ estado: nuevoEstado })
|
||||
body: JSON.stringify({ estado: nuevoEstado, cajero_id: cajeroId })
|
||||
});
|
||||
if (!res.ok) throw new Error('Error actualizando orden');
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || 'Error actualizando orden');
|
||||
}
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
loadPreOrders();
|
||||
loadCatalog();
|
||||
} catch (e) {
|
||||
alert(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Cancelación manual de pre-orden desde mostrador (libera fondos y retorna inventario)
|
||||
async function cancelarPreordenManual(orderId) {
|
||||
const razon = prompt(
|
||||
"¿Deseas cancelar esta pre-orden?\n\nEl monto retenido se liberará de inmediato al disponible del estudiante y el producto volverá al inventario.\n\nMotivo de cancelación (opcional):",
|
||||
"Cancelada a solicitud de la soda / estudiante"
|
||||
);
|
||||
if (razon === null) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/ordenes/${orderId}/estado`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ estado: 'cancelado', motivo: razon })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Error cancelando orden');
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
await loadPreOrders();
|
||||
await loadCatalog();
|
||||
alert('✅ Pre-orden cancelada. El saldo flotante ha sido liberado al estudiante.');
|
||||
} catch (err) {
|
||||
alert('❌ ' + err.message);
|
||||
}
|
||||
}
|
||||
window.cancelarPreordenManual = cancelarPreordenManual;
|
||||
|
||||
// Cierre de Caja del Día: finaliza jornada y expira pre-órdenes no retiradas
|
||||
async function ejecutarCierreDeCaja() {
|
||||
const confirma = confirm(
|
||||
"¿Deseas realizar el Cierre de Caja del turno?\n\n" +
|
||||
"Esta acción:\n" +
|
||||
"• Finalizará la jornada de ventas de la soda.\n" +
|
||||
"• Cancelará todas las pre-órdenes pendientes no retiradas.\n" +
|
||||
"• Liberará de inmediato el saldo retenido devolviéndolo al disponible de los estudiantes.\n" +
|
||||
"• Restituirá el inventario de los productos reservados."
|
||||
);
|
||||
|
||||
if (!confirma) return;
|
||||
|
||||
try {
|
||||
let escuelaId = 1;
|
||||
const storedUser = localStorage.getItem('sibopay_user') || localStorage.getItem('recreopay_user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
const u = JSON.parse(storedUser);
|
||||
if (u && u.escuela_id) escuelaId = u.escuela_id;
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
const res = await fetch('/api/pos/cierre-caja', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ escuela_id: escuelaId })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
throw new Error(data.error || 'Error al ejecutar el cierre de caja');
|
||||
}
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
await loadPreOrders();
|
||||
await loadCatalog();
|
||||
|
||||
const cantExp = data.ordenes_expiradas || 0;
|
||||
const montoLib = (data.monto_liberado_colones || 0).toLocaleString('es-CR');
|
||||
|
||||
alert(
|
||||
`🌙 CIERRE DE CAJA COMPLETADO CON ÉXITO\n\n` +
|
||||
`• Pre-órdenes no retiradas canceladas: ${cantExp}\n` +
|
||||
`• Monto liberado al disponible de alumnos: ₡${montoLib}\n\n` +
|
||||
`El turno ha sido liquidado correctamente.`
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Error en cierre de caja:', err);
|
||||
alert('❌ ' + err.message);
|
||||
}
|
||||
}
|
||||
window.ejecutarCierreDeCaja = ejecutarCierreDeCaja;
|
||||
|
||||
// Despacho Express en 3 segundos mediante escaneo de QR
|
||||
async function dispatchPreOrderExpress(qrToken) {
|
||||
try {
|
||||
@@ -1663,6 +1762,52 @@ function initSSE() {
|
||||
loadPreOrders();
|
||||
});
|
||||
|
||||
sseSource.addEventListener('preordenes_actualizadas', () => {
|
||||
loadPreOrders();
|
||||
});
|
||||
|
||||
sseSource.addEventListener('recargar_catalogo', () => {
|
||||
loadCatalog();
|
||||
});
|
||||
|
||||
sseSource.addEventListener('cierre_caja_realizado', (e) => {
|
||||
try {
|
||||
const res = JSON.parse(e.data);
|
||||
console.log('🌙 [POS] SSE cierre_caja_realizado:', res);
|
||||
loadPreOrders();
|
||||
loadCatalog();
|
||||
const count = res.count || 0;
|
||||
const monto = (res.liberadoColones || 0).toLocaleString('es-CR');
|
||||
showInAppNotification({
|
||||
title: '🌙 Cierre de Caja Realizado',
|
||||
message: count > 0
|
||||
? `Se cancelaron ${count} pre-orden(es) no retiradas y se liberaron ₡${monto} al disponible de los estudiantes.`
|
||||
: `Turno cerrado sin pre-órdenes pendientes por liberar.`,
|
||||
buttonText: 'Ver Pre-Órdenes'
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Error en SSE cierre_caja_realizado:', err);
|
||||
}
|
||||
});
|
||||
|
||||
sseSource.addEventListener('preordenes_expiradas', (e) => {
|
||||
try {
|
||||
const res = JSON.parse(e.data);
|
||||
console.log('⏳ [POS] SSE preordenes_expiradas:', res);
|
||||
loadPreOrders();
|
||||
loadCatalog();
|
||||
if (res && res.count > 0) {
|
||||
showInAppNotification({
|
||||
title: '⏳ Pre-órdenes Expiradas',
|
||||
message: `Se expiraron ${res.count} pre-orden(es) pendientes por límite de horario y se liberaron ₡${(res.liberadoColones || 0).toLocaleString('es-CR')}.`,
|
||||
buttonText: 'Ver Pre-Órdenes'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Error en SSE preordenes_expiradas:', err);
|
||||
}
|
||||
});
|
||||
|
||||
// Disparo recibido desde pistola remota (teléfono celular)
|
||||
sseSource.addEventListener('pistola_scan', async (e) => {
|
||||
try {
|
||||
|
||||
@@ -185,6 +185,7 @@
|
||||
</p>
|
||||
<div class="border border-slate-200 bg-slate-50/50 rounded-xl p-4 space-y-2 text-xs sm:text-sm text-slate-700">
|
||||
<p><strong>• Naturaleza del Saldo:</strong> El saldo acreditado representa un crédito escolar prepagado, utilizable exclusivamente para el consumo de productos y servicios autorizados en las sodas escolares afiliadas.</p>
|
||||
<p><strong>• Prohibición de Conversión y Retiro a Efectivo (No Cashback):</strong> Los fondos y saldos acreditados en la plataforma constituyen créditos escolares de consumo prepagado, utilizables única y exclusivamente para compras y consumo dentro de las sodas escolares afiliadas. Bajo ninguna circunstancia podrán ser canjeados, devueltos en dinero en efectivo, transferidos a cuentas bancarias externas ni liquidados en moneda de curso legal fuera del ecosistema escolar.</p>
|
||||
<p><strong>• Procedimiento de Recarga:</strong> Las recargas se realizan mediante transferencias bancarias o SINPE Móvil. Los fondos quedan disponibles una vez confirmada y verificada la transferencia por los mecanismos de control del sistema.</p>
|
||||
<p><strong>• Reversiones de Cobro:</strong> En caso de errores materiales o cargos involuntarios ocurridos en el mostrador, el personal autorizado de la soda puede procesar la reversión inmediata de la transacción para reintegrar el saldo al alumno en tiempo real.</p>
|
||||
</div>
|
||||
|
||||
@@ -146,6 +146,10 @@
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
<span>Admin</span>
|
||||
</a>
|
||||
<button type="button" onclick="ejecutarCierreDeCaja()" class="btn-saas" style="height: 30px; font-size: 0.76rem; display: inline-flex; align-items: center; gap: 5px; font-weight: 800; color: #92400e; background: #fef3c7; border: 1.5px solid #fde68a; border-radius: 8px; cursor: pointer;" title="Cierre de Caja del Día: finaliza el turno y cancela pre-órdenes no retiradas liberando el saldo a los estudiantes">
|
||||
<span>🌙</span>
|
||||
<span>Cierre de Caja</span>
|
||||
</button>
|
||||
<label style="display: inline-flex; align-items: center; gap: 6px; font-size: 0.74rem; font-weight: 700; color: #475569; background: #ffffff; padding: 4px 10px; border-radius: 8px; border: 1.5px solid #cbd5e1; cursor: pointer; user-select: none;" title="Imprimir comanda o ticket térmico automáticamente al finalizar cada cobro">
|
||||
<input type="checkbox" id="chkPosAutoPrint" style="cursor: pointer; width: 14px; height: 14px;">
|
||||
<span>🖨️ Auto-imprimir ticket</span>
|
||||
|
||||
+283
-16
@@ -724,7 +724,7 @@ function debitoCompraTransaction({ estudianteId, montoTotal, ordenId, descripcio
|
||||
`).get(estudianteId);
|
||||
|
||||
const totalGastadoHoy = gastoHoyRow ? gastoHoyRow.total_gastado_hoy : 0;
|
||||
if (totalGastadoHoy + montoTotal > est.limite_diario_colones) {
|
||||
if (tipoOrden !== 'preorden' && totalGastadoHoy + montoTotal > est.limite_diario_colones) {
|
||||
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')}`);
|
||||
}
|
||||
@@ -863,13 +863,44 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
const estadoInicial = tipoOrden === 'mostrador' ? 'entregado' : 'pendiente';
|
||||
const entregadoEn = tipoOrden === 'mostrador' ? new Date().toISOString() : null;
|
||||
|
||||
// Consultar estudiante para registrar saldos históricos y evitar campos NULL
|
||||
// Consultar estudiante para registrar saldos y validaciones
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(estudianteId);
|
||||
if (!est) throw new Error(`Estudiante #${estudianteId} no existe`);
|
||||
if (!est.activo) throw new Error('La cuenta del estudiante se encuentra inactiva');
|
||||
if (est.tarjeta_bloqueada) throw new Error('⛔ Tarjeta suspendida por la administración de la soda.');
|
||||
|
||||
// Calcular saldo retenido actual en pre-órdenes flotantes pendientes
|
||||
const retenidoRow = db.prepare(`
|
||||
SELECT COALESCE(SUM(total_colones), 0) as total_retenido
|
||||
FROM ordenes
|
||||
WHERE estudiante_id = ? AND tipo_orden = 'preorden' AND estado IN ('pendiente', 'en_preparacion', 'listo')
|
||||
`).get(estudianteId);
|
||||
const saldoRetenidoActual = retenidoRow ? retenidoRow.total_retenido : 0;
|
||||
const saldoDisponibleActual = Math.max(0, est.saldo_colones - saldoRetenidoActual);
|
||||
|
||||
// Gastado hoy en compras de mostrador
|
||||
const gastoHoyRow = db.prepare(`
|
||||
SELECT COALESCE(SUM(ABS(monto_colones)), 0) as total_gastado_hoy
|
||||
FROM transacciones_saldo
|
||||
WHERE estudiante_id = ? AND monto_colones < 0 AND date(fecha, 'localtime') = date('now', 'localtime')
|
||||
`).get(estudianteId);
|
||||
const totalGastadoHoy = gastoHoyRow ? gastoHoyRow.total_gastado_hoy : 0;
|
||||
const disponibleHoyActual = Math.max(0, (est.limite_diario_colones || 0) - totalGastadoHoy - saldoRetenidoActual);
|
||||
|
||||
// Validación de solvencia de saldo disponible y límite diario
|
||||
if (saldoDisponibleActual < totalColones) {
|
||||
throw new Error(`Saldo disponible insuficiente. Saldo total: ₡${est.saldo_colones.toLocaleString('es-CR')}, Retenido en pre-órdenes: ₡${saldoRetenidoActual.toLocaleString('es-CR')}, Disponible: ₡${saldoDisponibleActual.toLocaleString('es-CR')}, Total orden: ₡${totalColones.toLocaleString('es-CR')}`);
|
||||
}
|
||||
|
||||
if (disponibleHoyActual < totalColones) {
|
||||
throw new Error(`Límite diario superado. Su límite por día es ₡${(est.limite_diario_colones || 0).toLocaleString('es-CR')}. Disponible hoy considerando pedidos pendientes: ₡${disponibleHoyActual.toLocaleString('es-CR')}`);
|
||||
}
|
||||
|
||||
const saldoAnterior = est.saldo_colones;
|
||||
const saldoPosterior = Math.max(0, saldoAnterior - totalColones);
|
||||
// Si es preorden, no se descuenta de saldo_colones aún; queda como monto flotante
|
||||
const saldoPosterior = tipoOrden === 'mostrador' ? Math.max(0, saldoAnterior - totalColones) : saldoAnterior;
|
||||
const cajeroVal = (tipoOrden === 'mostrador' ? 6 : 1);
|
||||
const obsVal = (tipoOrden === 'mostrador' ? 'Venta realizada en mostrador' : 'Pre-orden retiro en recreo');
|
||||
const obsVal = (tipoOrden === 'mostrador' ? 'Venta realizada en mostrador' : 'Pre-orden con monto retenido');
|
||||
const notasVal = notas || '';
|
||||
const momentoVal = momentoEntrega || (tipoOrden === 'mostrador' ? 'inmediato' : 'recreo_1');
|
||||
|
||||
@@ -898,7 +929,7 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
|
||||
const ordenId = resultOrden.lastInsertRowid;
|
||||
|
||||
// Insertar detalle de productos y descontar inventario
|
||||
// Insertar detalle de productos y descontar/reservar inventario
|
||||
const insertDetalle = db.prepare(`
|
||||
INSERT INTO orden_detalles (orden_id, producto_id, nombre_producto, cantidad, precio_unitario, subtotal)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
@@ -909,7 +940,7 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
const nombreProd = det.nombre || `Producto #${det.producto_id}`;
|
||||
insertDetalle.run(ordenId, det.producto_id, nombreProd, det.cantidad, det.precio_unitario, det.subtotal);
|
||||
|
||||
// Descontar inventario si tiene control de stock activo
|
||||
// Descontar inventario si tiene control de stock activo (reservado)
|
||||
const prod = db.prepare('SELECT control_stock, stock FROM productos WHERE id = ?').get(det.producto_id);
|
||||
if (prod && prod.control_stock === 1) {
|
||||
const nuevoStock = Math.max(0, prod.stock - det.cantidad);
|
||||
@@ -928,14 +959,47 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
}
|
||||
}
|
||||
|
||||
// Efectuar débito financiero
|
||||
const resultadoDebito = debitoCompraTransaction({
|
||||
estudianteId,
|
||||
montoTotal: totalColones,
|
||||
ordenId,
|
||||
descripcion: `Orden ${codigoOrden} (${tipoOrden})`,
|
||||
tipoOrden: tipoOrden === 'mostrador' ? 'compra_mostrador' : 'preorden'
|
||||
});
|
||||
let resultadoFinanciero;
|
||||
if (tipoOrden === 'mostrador') {
|
||||
// Efectuar débito financiero en mostrador
|
||||
resultadoFinanciero = debitoCompraTransaction({
|
||||
estudianteId,
|
||||
montoTotal: totalColones,
|
||||
ordenId,
|
||||
descripcion: `Orden ${codigoOrden} (mostrador)`,
|
||||
tipoOrden: 'compra_mostrador'
|
||||
});
|
||||
resultadoFinanciero.estudiante.saldo_total = resultadoFinanciero.estudiante.saldo_nuevo;
|
||||
resultadoFinanciero.estudiante.saldo_retenido = saldoRetenidoActual;
|
||||
resultadoFinanciero.estudiante.saldo_disponible = Math.max(0, resultadoFinanciero.estudiante.saldo_nuevo - saldoRetenidoActual);
|
||||
} else {
|
||||
// Pre-orden: El dinero queda como saldo retenido / flotante sin débito inmediato
|
||||
const nuevoSaldoRetenido = saldoRetenidoActual + totalColones;
|
||||
const nuevoSaldoDisp = Math.max(0, est.saldo_colones - nuevoSaldoRetenido);
|
||||
const nuevoDispHoy = Math.max(0, (est.limite_diario_colones || 0) - totalGastadoHoy - nuevoSaldoRetenido);
|
||||
|
||||
resultadoFinanciero = {
|
||||
exito: true,
|
||||
monto_flotante: true,
|
||||
estudiante: {
|
||||
id: est.id,
|
||||
nombre: est.nombre_completo,
|
||||
grado: est.grado,
|
||||
seccion: est.seccion,
|
||||
foto_url: est.foto_url,
|
||||
saldo_total: est.saldo_colones,
|
||||
saldo_anterior: est.saldo_colones,
|
||||
saldo_nuevo: est.saldo_colones,
|
||||
saldo_retenido: nuevoSaldoRetenido,
|
||||
saldo_disponible: nuevoSaldoDisp,
|
||||
limite_diario: est.limite_diario_colones,
|
||||
gastado_hoy: totalGastadoHoy,
|
||||
disponible_hoy: nuevoDispHoy,
|
||||
tiene_preordenes_pendientes: true,
|
||||
qr_bloqueado: false
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
orden_id: ordenId,
|
||||
@@ -953,7 +1017,7 @@ function crearOrdenCompleta({ estudianteId, tipoOrden, momentoEntrega, notas, it
|
||||
detalles: detallesParaInsertar,
|
||||
items: detallesParaInsertar,
|
||||
productosActualizados,
|
||||
financiero: resultadoDebito
|
||||
financiero: resultadoFinanciero
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1502,6 +1566,205 @@ function eliminarSuscripcionPush(endpoint) {
|
||||
return db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ?').run(endpoint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expira automáticamente pre-órdenes no retiradas (por cierre de caja o fin de jornada a las 5:00 PM)
|
||||
* Restituye el inventario y libera el saldo retenido.
|
||||
*/
|
||||
function expirarPreordenesVencidas({ motivo = 'tiempo_limite', escuelaId = null } = {}) {
|
||||
let condition = `
|
||||
tipo_orden = 'preorden'
|
||||
AND estado IN ('pendiente', 'en_preparacion', 'listo')
|
||||
`;
|
||||
const params = [];
|
||||
|
||||
if (motivo === 'cierre_caja') {
|
||||
if (escuelaId) {
|
||||
condition += ' AND (escuela_id = ? OR escuela_id IS NULL)';
|
||||
params.push(escuelaId);
|
||||
}
|
||||
} else {
|
||||
condition += ` AND (
|
||||
date(creado_en, 'localtime') < date('now', 'localtime')
|
||||
OR (date(creado_en, 'localtime') = date('now', 'localtime') AND strftime('%H:%M', 'now', 'localtime') >= '17:00')
|
||||
)`;
|
||||
if (escuelaId) {
|
||||
condition += ' AND (escuela_id = ? OR escuela_id IS NULL)';
|
||||
params.push(escuelaId);
|
||||
}
|
||||
}
|
||||
|
||||
const vencidas = db.prepare(`SELECT * FROM ordenes WHERE ${condition}`).all(...params);
|
||||
if (!vencidas || vencidas.length === 0) {
|
||||
return { count: 0, liberadoColones: 0, ordenes: [] };
|
||||
}
|
||||
|
||||
const tx = db.transaction(() => {
|
||||
let liberadoColones = 0;
|
||||
const ordenesExpiradas = [];
|
||||
|
||||
const stmtUpdateOrden = db.prepare(`
|
||||
UPDATE ordenes
|
||||
SET estado = 'expirado', observaciones = COALESCE(observaciones || ' | ', '') || ?
|
||||
WHERE id = ?
|
||||
`);
|
||||
|
||||
const stmtGetDetalles = db.prepare(`
|
||||
SELECT producto_id, cantidad FROM orden_detalles WHERE orden_id = ?
|
||||
`);
|
||||
|
||||
const stmtRestoreStock = db.prepare(`
|
||||
UPDATE productos
|
||||
SET stock = stock + ?, disponible = 1
|
||||
WHERE id = ? AND control_stock = 1
|
||||
`);
|
||||
|
||||
for (const ord of vencidas) {
|
||||
const obs = motivo === 'cierre_caja'
|
||||
? 'Expirado por Cierre de Caja del turno'
|
||||
: 'Expirado automáticamente a las 5:00 PM por no retiro';
|
||||
stmtUpdateOrden.run(obs, ord.id);
|
||||
liberadoColones += ord.total_colones;
|
||||
|
||||
const detalles = stmtGetDetalles.all(ord.id);
|
||||
for (const det of detalles) {
|
||||
stmtRestoreStock.run(det.cantidad, det.producto_id);
|
||||
}
|
||||
|
||||
ordenesExpiradas.push(ord);
|
||||
}
|
||||
|
||||
return {
|
||||
count: vencidas.length,
|
||||
liberadoColones,
|
||||
ordenes: ordenesExpiradas
|
||||
};
|
||||
});
|
||||
|
||||
return tx();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancela una pre-orden individual y devuelve el stock
|
||||
*/
|
||||
function cancelarPreorden(ordenId, motivo = 'Cancelada') {
|
||||
const ord = db.prepare("SELECT * FROM ordenes WHERE id = ?").get(ordenId);
|
||||
if (!ord) throw new Error('Orden no encontrada');
|
||||
if (ord.estado === 'entregado') throw new Error('No se puede cancelar una orden ya entregada');
|
||||
if (ord.estado === 'cancelado' || ord.estado === 'expirado') throw new Error(`Esta orden ya se encuentra ${ord.estado}`);
|
||||
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare(`
|
||||
UPDATE ordenes
|
||||
SET estado = 'cancelado', observaciones = COALESCE(observaciones || ' | ', '') || ?
|
||||
WHERE id = ?
|
||||
`).run(motivo, ordenId);
|
||||
|
||||
const detalles = db.prepare('SELECT producto_id, cantidad FROM orden_detalles WHERE orden_id = ?').all(ordenId);
|
||||
for (const det of detalles) {
|
||||
db.prepare('UPDATE productos SET stock = stock + ?, disponible = 1 WHERE id = ? AND control_stock = 1').run(det.cantidad, det.producto_id);
|
||||
}
|
||||
|
||||
return ord;
|
||||
});
|
||||
|
||||
return tx();
|
||||
}
|
||||
|
||||
/**
|
||||
* Despacha y cobra formalmente una pre-orden en la soda (POS)
|
||||
*/
|
||||
function despacharPreordenTransaction({ ordenId, cajeroId = 6 }) {
|
||||
const transaction = db.transaction(() => {
|
||||
const preorden = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
if (!preorden) throw new Error('Pre-orden no encontrada');
|
||||
if (preorden.estado === 'entregado') throw new Error('Esta pre-orden ya fue entregada previamente');
|
||||
if (preorden.estado === 'cancelado' || preorden.estado === 'expirado') {
|
||||
throw new Error(`Esta pre-orden se encuentra ${preorden.estado} y no puede ser despachada`);
|
||||
}
|
||||
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(preorden.estudiante_id);
|
||||
if (!est) throw new Error('Estudiante no encontrado');
|
||||
|
||||
// Efectuar débito oficial de saldo
|
||||
const resDebito = debitoCompraTransaction({
|
||||
estudianteId: est.id,
|
||||
montoTotal: preorden.total_colones,
|
||||
ordenId: preorden.id,
|
||||
descripcion: `Cobro Pre-orden ${preorden.codigo_orden} (${formatMomentoLabel(preorden.momento_entrega)})`,
|
||||
tipoOrden: 'preorden'
|
||||
});
|
||||
|
||||
db.prepare(`
|
||||
UPDATE ordenes
|
||||
SET estado = 'entregado', entregado_en = datetime('now', 'localtime'), cajero_id = ?,
|
||||
saldo_anterior = ?, saldo_posterior = ?
|
||||
WHERE id = ?
|
||||
`).run(cajeroId, est.saldo_colones, resDebito.estudiante.saldo_nuevo, preorden.id);
|
||||
|
||||
const ordenActualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(preorden.id);
|
||||
const finanzasActualizadas = enriquecerEstudianteFinanzas(db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(est.id));
|
||||
|
||||
return {
|
||||
orden: ordenActualizada,
|
||||
estudiante: finanzasActualizadas,
|
||||
debito: resDebito
|
||||
};
|
||||
});
|
||||
|
||||
return transaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriquece el objeto de estudiante con su desglose financiero de saldo total,
|
||||
* saldo retenido (preórdenes flotantes), saldo disponible, gasto hoy, límite disponible
|
||||
* y estado de bloqueo de QR.
|
||||
*/
|
||||
function enriquecerEstudianteFinanzas(est) {
|
||||
if (!est) return null;
|
||||
// Revisión previa de posibles pre-órdenes vencidas
|
||||
expirarPreordenesVencidas();
|
||||
|
||||
const gastoHoyRow = 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(est.id);
|
||||
const gastadoHoy = gastoHoyRow ? gastoHoyRow.total : 0;
|
||||
|
||||
const retenidoRow = db.prepare(`
|
||||
SELECT COALESCE(SUM(total_colones), 0) as total_retenido
|
||||
FROM ordenes
|
||||
WHERE estudiante_id = ? AND tipo_orden = 'preorden' AND estado IN ('pendiente', 'en_preparacion', 'listo')
|
||||
`).get(est.id);
|
||||
const saldoRetenido = retenidoRow ? retenidoRow.total_retenido : 0;
|
||||
|
||||
const limiteDiario = est.limite_diario_colones || 0;
|
||||
const saldoTotal = est.saldo_colones || 0;
|
||||
const saldoDisponible = Math.max(0, saldoTotal - saldoRetenido);
|
||||
const disponibleHoy = Math.max(0, limiteDiario - gastadoHoy - saldoRetenido);
|
||||
|
||||
const preordenesPendientesCount = db.prepare(`
|
||||
SELECT COUNT(*) as count FROM ordenes
|
||||
WHERE estudiante_id = ? AND tipo_orden = 'preorden' AND estado IN ('pendiente', 'en_preparacion', 'listo')
|
||||
`).get(est.id).count;
|
||||
|
||||
const tienePreordenes = preordenesPendientesCount > 0;
|
||||
// El QR se bloquea si el estudiante alcanzó su límite diario (disponible_hoy <= 0) Y NO tiene preórdenes pendientes
|
||||
const qrBloqueado = (disponibleHoy <= 0 && !tienePreordenes) || est.tarjeta_bloqueada === 1;
|
||||
|
||||
return {
|
||||
...est,
|
||||
saldo_total: saldoTotal,
|
||||
saldo_retenido: saldoRetenido,
|
||||
saldo_disponible: saldoDisponible,
|
||||
gastado_hoy: gastadoHoy,
|
||||
disponible_hoy: disponibleHoy,
|
||||
tiene_preordenes_pendientes: tienePreordenes,
|
||||
preordenes_pendientes_count: preordenesPendientesCount,
|
||||
qr_bloqueado: qrBloqueado
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
db,
|
||||
initDatabase,
|
||||
@@ -1520,5 +1783,9 @@ module.exports = {
|
||||
guardarSuscripcionPush,
|
||||
obtenerSuscripcionesPush,
|
||||
eliminarSuscripcionPush,
|
||||
formatMomentoLabel
|
||||
formatMomentoLabel,
|
||||
expirarPreordenesVencidas,
|
||||
cancelarPreorden,
|
||||
despacharPreordenTransaction,
|
||||
enriquecerEstudianteFinanzas
|
||||
};
|
||||
|
||||
+108
-70
@@ -28,7 +28,11 @@ const {
|
||||
guardarSuscripcionPush,
|
||||
obtenerSuscripcionesPush,
|
||||
eliminarSuscripcionPush,
|
||||
formatMomentoLabel
|
||||
formatMomentoLabel,
|
||||
expirarPreordenesVencidas,
|
||||
cancelarPreorden,
|
||||
despacharPreordenTransaction,
|
||||
enriquecerEstudianteFinanzas
|
||||
} = require('./db');
|
||||
const { checkSinpeEmailsOnce, simularSinpeEmail } = require('./sinpeImapService');
|
||||
const { normalizarCodigoDetalle, parseSinpeEmail } = require('./sinpeParser');
|
||||
@@ -266,13 +270,7 @@ app.post('/api/auth/login', (req, res) => {
|
||||
`).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);
|
||||
estudiante = enriquecerEstudianteFinanzas(estudiante);
|
||||
}
|
||||
} else if (user.rol === 'padre') {
|
||||
hijos = db.prepare(`
|
||||
@@ -291,18 +289,7 @@ app.post('/api/auth/login', (req, res) => {
|
||||
WHERE e.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)
|
||||
};
|
||||
});
|
||||
hijos = hijos.map(h => enriquecerEstudianteFinanzas(h));
|
||||
}
|
||||
|
||||
res.json({
|
||||
@@ -454,18 +441,7 @@ app.get('/api/padres/mis-hijos', (req, res) => {
|
||||
`).all(padre_usuario_id);
|
||||
}
|
||||
|
||||
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)
|
||||
};
|
||||
});
|
||||
const hijosEnriquecidos = hijos.map(h => enriquecerEstudianteFinanzas(h));
|
||||
|
||||
res.json({ success: true, hijos: hijosEnriquecidos });
|
||||
} catch (err) {
|
||||
@@ -1971,10 +1947,7 @@ app.get('/api/estudiantes', (req, res) => {
|
||||
WHERE activo = 1
|
||||
ORDER BY grado, seccion, nombre_completo
|
||||
`).all();
|
||||
const listWithDisp = list.map(e => ({
|
||||
...e,
|
||||
disponible_hoy: Math.max(0, (e.limite_diario_colones || 0) - (e.gastado_hoy || 0))
|
||||
}));
|
||||
const listWithDisp = list.map(e => enriquecerEstudianteFinanzas(e));
|
||||
res.json(listWithDisp);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
@@ -1987,12 +1960,7 @@ app.get('/api/estudiantes/:id', (req, res) => {
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(req.params.id);
|
||||
if (!est) return res.status(404).json({ error: 'Estudiante no encontrado' });
|
||||
|
||||
// Gastado hoy
|
||||
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(est.id).total;
|
||||
const finanzas = enriquecerEstudianteFinanzas(est);
|
||||
|
||||
// Transacciones recientes
|
||||
const transacciones = db.prepare(`
|
||||
@@ -2009,9 +1977,7 @@ app.get('/api/estudiantes/:id', (req, res) => {
|
||||
`).all(est.id);
|
||||
|
||||
res.json({
|
||||
...est,
|
||||
gastado_hoy: gastoHoy,
|
||||
disponible_hoy: Math.max(0, est.limite_diario_colones - gastoHoy),
|
||||
...finanzas,
|
||||
transacciones,
|
||||
ordenes_activas: ordenesActivas
|
||||
});
|
||||
@@ -2071,11 +2037,7 @@ app.get('/api/estudiantes/qr/:token', (req, res) => {
|
||||
return res.status(404).json({ error: 'Código QR no reconocido en la base de datos de la escuela' });
|
||||
}
|
||||
|
||||
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(est.id).total;
|
||||
const finanzas = enriquecerEstudianteFinanzas(est);
|
||||
|
||||
// Verificar si tiene pre-órdenes listas para retirar en el recreo
|
||||
const preordenesPendientes = db.prepare(`
|
||||
@@ -2095,9 +2057,7 @@ app.get('/api/estudiantes/qr/:token', (req, res) => {
|
||||
}));
|
||||
|
||||
res.json({
|
||||
...est,
|
||||
gastado_hoy: gastoHoy,
|
||||
disponible_hoy: Math.max(0, est.limite_diario_colones - gastoHoy),
|
||||
...finanzas,
|
||||
preordenes_pendientes: preordenesFormateadas
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -2108,7 +2068,23 @@ app.get('/api/estudiantes/qr/:token', (req, res) => {
|
||||
// Generar imagen QR en PNG/SVG para el carné
|
||||
app.get('/api/qr-image/:token', async (req, res) => {
|
||||
try {
|
||||
const qrDataUrl = await QRCode.toDataURL(req.params.token, {
|
||||
const rawToken = req.params.token;
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(rawToken, rawToken);
|
||||
|
||||
// Si el estudiante existe y su QR está bloqueado por superar límite diario (sin pre-órdenes pendientes)
|
||||
if (est && !req.query.bypass) {
|
||||
const finanzas = enriquecerEstudianteFinanzas(est);
|
||||
if (finanzas.qr_bloqueado) {
|
||||
return res.status(403).json({
|
||||
error: 'Código QR bloqueado: Límite diario alcanzado y no hay pre-órdenes pendientes para retirar.',
|
||||
bloqueado: true,
|
||||
limite_diario: finanzas.limite_diario_colones,
|
||||
disponible_hoy: finanzas.disponible_hoy
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const qrDataUrl = await QRCode.toDataURL(rawToken, {
|
||||
width: 350,
|
||||
margin: 3,
|
||||
errorCorrectionLevel: 'H',
|
||||
@@ -2871,33 +2847,58 @@ app.get('/api/ordenes', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Actualizar estado de una orden (Cocina -> Listo -> Entregado)
|
||||
// Actualizar estado de una orden (Cocina -> Listo -> Entregado / Cancelado)
|
||||
app.put('/api/ordenes/:id/estado', (req, res) => {
|
||||
try {
|
||||
const { estado } = req.body;
|
||||
const { estado, motivo, cajero_id } = req.body;
|
||||
const ordenId = req.params.id;
|
||||
|
||||
const entregadoEn = estado === 'entregado' ? new Date().toISOString() : null;
|
||||
const ord = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
if (!ord) return res.status(404).json({ error: 'Orden no encontrada' });
|
||||
|
||||
db.prepare(`
|
||||
UPDATE ordenes
|
||||
SET estado = ?, entregado_en = COALESCE(?, entregado_en)
|
||||
WHERE id = ?
|
||||
`).run(estado, entregadoEn, ordenId);
|
||||
let actualizada;
|
||||
if (estado === 'entregado') {
|
||||
// Si es preorden y no ha sido debitada todavía
|
||||
const yaDebitada = db.prepare('SELECT COUNT(*) as count FROM transacciones_saldo WHERE orden_id = ?').get(ordenId).count > 0;
|
||||
if (ord.tipo_orden === 'preorden' && !yaDebitada) {
|
||||
const despacho = despacharPreordenTransaction({ ordenId, cajeroId: cajero_id || 6 });
|
||||
actualizada = despacho.orden;
|
||||
broadcastEvent('estudiante_actualizado', despacho.estudiante);
|
||||
broadcastEvent('saldo_actualizado', despacho.estudiante);
|
||||
} else {
|
||||
db.prepare("UPDATE ordenes SET estado = 'entregado', entregado_en = datetime('now', 'localtime') WHERE id = ?").run(ordenId);
|
||||
actualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
}
|
||||
} else if (estado === 'cancelado') {
|
||||
cancelarPreorden(ordenId, motivo || 'Cancelada desde terminal');
|
||||
actualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE id = ?').get(ord.estudiante_id);
|
||||
if (est) {
|
||||
const finEst = enriquecerEstudianteFinanzas(est);
|
||||
broadcastEvent('estudiante_actualizado', finEst);
|
||||
broadcastEvent('saldo_actualizado', finEst);
|
||||
}
|
||||
broadcastEvent('recargar_catalogo', {});
|
||||
} else {
|
||||
db.prepare(`
|
||||
UPDATE ordenes
|
||||
SET estado = ?
|
||||
WHERE id = ?
|
||||
`).run(estado, ordenId);
|
||||
actualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
}
|
||||
|
||||
const actualizada = db.prepare('SELECT * FROM ordenes WHERE id = ?').get(ordenId);
|
||||
broadcastEvent('orden_actualizada', actualizada);
|
||||
|
||||
res.json(actualizada);
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Despacho ultra-rápido en fila de pre-órdenes mediante escaneo de QR
|
||||
// Despacho ultra-rápido en fila de pre-órdenes mediante escaneo de QR (con débito contable oficial)
|
||||
app.post('/api/ordenes/despachar-qr', (req, res) => {
|
||||
try {
|
||||
const { qr_token } = req.body;
|
||||
const { qr_token, cajero_id } = req.body;
|
||||
if (!qr_token) return res.status(400).json({ error: 'Se requiere el código QR del estudiante' });
|
||||
|
||||
const est = db.prepare('SELECT * FROM estudiantes WHERE qr_token = ? OR codigo_estudiante = ?').get(qr_token, qr_token);
|
||||
@@ -2916,8 +2917,8 @@ app.post('/api/ordenes/despachar-qr', (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Marcar como entregada
|
||||
db.prepare("UPDATE ordenes SET estado = 'entregado', entregado_en = datetime('now', 'localtime') WHERE id = ?").run(preorden.id);
|
||||
// Efectuar débito financiero formal y marcar entregada
|
||||
const despacho = despacharPreordenTransaction({ ordenId: preorden.id, cajeroId: cajero_id || 6 });
|
||||
|
||||
// Obtener detalles para mostrar en pantalla de caja
|
||||
const items = db.prepare(`
|
||||
@@ -2929,8 +2930,8 @@ app.post('/api/ordenes/despachar-qr', (req, res) => {
|
||||
|
||||
const responseData = {
|
||||
exito: true,
|
||||
mensaje: `¡Pre-orden ${preorden.codigo_orden} despachada con éxito!`,
|
||||
estudiante: est,
|
||||
mensaje: `¡Pre-orden ${preorden.codigo_orden} cobrada y despachada con éxito!`,
|
||||
estudiante: despacho.estudiante,
|
||||
orden: {
|
||||
id: preorden.id,
|
||||
codigo: preorden.codigo_orden,
|
||||
@@ -2942,12 +2943,49 @@ app.post('/api/ordenes/despachar-qr', (req, res) => {
|
||||
};
|
||||
|
||||
broadcastEvent('orden_despachada', responseData);
|
||||
broadcastEvent('orden_actualizada', despacho.orden);
|
||||
broadcastEvent('estudiante_actualizado', despacho.estudiante);
|
||||
broadcastEvent('saldo_actualizado', despacho.estudiante);
|
||||
|
||||
res.json(responseData);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Cierre de caja del día: expira y libera pre-órdenes no retiradas
|
||||
app.post('/api/pos/cierre-caja', (req, res) => {
|
||||
try {
|
||||
const { escuela_id } = req.body;
|
||||
const resultado = expirarPreordenesVencidas({ motivo: 'cierre_caja', escuelaId: escuela_id || 1 });
|
||||
broadcastEvent('cierre_caja_realizado', resultado);
|
||||
broadcastEvent('recargar_catalogo', {});
|
||||
broadcastEvent('preordenes_actualizadas', {});
|
||||
res.json({
|
||||
exito: true,
|
||||
mensaje: `Cierre de caja completado con éxito. ${resultado.count} pre-orden(es) no retiradas fueron canceladas y su monto fue liberado al disponible de los estudiantes.`,
|
||||
ordenes_expiradas: resultado.count,
|
||||
monto_liberado_colones: resultado.liberadoColones
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Verificador automático periódico de preórdenes vencidas (cada 60 segundos)
|
||||
setInterval(() => {
|
||||
try {
|
||||
const exp = expirarPreordenesVencidas({ motivo: 'tiempo_limite' });
|
||||
if (exp && exp.count > 0) {
|
||||
console.log(`[AUTO-EXPIRACION] ${exp.count} pre-orden(es) vencidas canceladas. Liberado: ₡${exp.liberadoColones}`);
|
||||
broadcastEvent('preordenes_expiradas', exp);
|
||||
broadcastEvent('recargar_catalogo', {});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[AUTO-EXPIRACION] Error en verificación periódica:', e.message);
|
||||
}
|
||||
}, 60 * 1000);
|
||||
|
||||
// Información de conectividad y túnel HTTPS
|
||||
app.get('/api/server-info', (req, res) => {
|
||||
res.json({
|
||||
|
||||
Reference in New Issue
Block a user