feat: Validacion SINPE con monto y comprobante, modulo de aprobacion en POS y estilo gray-out en transferencias deshabilitadas
This commit is contained in:
@@ -3596,6 +3596,27 @@ body.dark-mode .admin-student-row.is-blocked {
|
||||
}
|
||||
}
|
||||
|
||||
/* Botón de transferir en gris claro / gray out cuando los padres lo desactivan */
|
||||
.qr-toggle-btn.transfer-btn-disabled {
|
||||
background: rgba(241, 245, 249, 0.85) !important;
|
||||
color: #94a3b8 !important;
|
||||
border-color: #cbd5e1 !important;
|
||||
box-shadow: none !important;
|
||||
opacity: 0.65 !important;
|
||||
filter: grayscale(1) !important;
|
||||
cursor: pointer !important;
|
||||
}
|
||||
|
||||
.qr-toggle-btn.transfer-btn-disabled svg {
|
||||
stroke: #94a3b8 !important;
|
||||
}
|
||||
|
||||
.pwa-nav-item.transfer-nav-disabled {
|
||||
opacity: 0.45 !important;
|
||||
filter: grayscale(1) !important;
|
||||
color: #94a3b8 !important;
|
||||
}
|
||||
|
||||
.pwa-nav-item.transfer-nav-disabled svg {
|
||||
stroke: #94a3b8 !important;
|
||||
}
|
||||
|
||||
+40
-28
@@ -787,25 +787,34 @@
|
||||
<span style="font-size: 0.7rem; color: #166534; background: #dcfce7; font-weight: 800; padding: 3px 8px; border-radius: 6px;">Inmediato</span>
|
||||
</div>
|
||||
|
||||
<label style="display: block; font-size: 0.8rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
Monto a recargar en colones:
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 12px;">
|
||||
<div>
|
||||
<label for="inputParentSinpeMonto" style="display: block; font-size: 0.78rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
Monto a recargar (₡):
|
||||
</label>
|
||||
<div style="position: relative; margin-bottom: 8px;">
|
||||
<span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #166534; font-size: 1.15rem;">₡</span>
|
||||
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputParentSinpeMonto" placeholder="Ej: 3000" style="width: 100%; padding: 11px 12px 11px 32px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.2rem; font-weight: 900; color: #166534; background: white; box-sizing: border-box;">
|
||||
<div style="position: relative;">
|
||||
<span style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #166534; font-size: 1.05rem;">₡</span>
|
||||
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputParentSinpeMonto" placeholder="Ej: 3000" style="width: 100%; padding: 10px 10px 10px 28px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.05rem; font-weight: 800; color: #166534; background: white; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="inputParentSinpeComprobante" style="display: block; font-size: 0.78rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
N° Comprobante SINPE:
|
||||
</label>
|
||||
<input type="text" id="inputParentSinpeComprobante" placeholder="Ej: 894321" style="width: 100%; padding: 10px 12px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.05rem; font-weight: 800; color: #166534; background: white; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 12px;">
|
||||
<button type="button" onclick="setParentSinpePreset(1000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡1.000</button>
|
||||
<button type="button" onclick="setParentSinpePreset(2000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡2.000</button>
|
||||
<button type="button" onclick="setParentSinpePreset(5000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡5.000</button>
|
||||
<button type="button" onclick="setParentSinpePreset(10000)" class="stock-btn-quick" style="border-color: #86efac; color: #166534;">₡10.000</button>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="executeParentSinpeRecharge()" style="width: 100%; padding: 13px; background: linear-gradient(135deg, #16a34a, #15803d); color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 0.95rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 10px rgba(22, 163, 74, 0.3);">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>
|
||||
<span>Aplicar Recarga de Saldo</span>
|
||||
<button type="button" id="btnParentValidarSinpe" onclick="executeParentSinpeRecharge()" style="width: 100%; padding: 13px; background: linear-gradient(135deg, #16a34a, #15803d); color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 0.95rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 10px rgba(22, 163, 74, 0.3);">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
|
||||
<span>Validar SINPE</span>
|
||||
</button>
|
||||
|
||||
<!-- LISTA DE SOLICITUDES SINPE PENDIENTES DEL HIJO -->
|
||||
<div id="parentSinpePendingBox" style="margin-top: 14px; border-top: 1px dashed #86efac; padding-top: 10px; display: none;">
|
||||
<div style="font-size: 0.76rem; font-weight: 800; color: #166534; margin-bottom: 6px;">Estado de Recargas Recientes:</div>
|
||||
<div id="parentSinpePendingList" style="display: flex; flex-direction: column; gap: 6px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- CONFIGURACIÓN DE LÍMITE DIARIO -->
|
||||
@@ -991,7 +1000,7 @@
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M7 7h.01"/><path d="M17 7h.01"/><path d="M7 17h.01"/><path d="M17 17h.01"/></svg>
|
||||
<span id="qrBtnText">Mi QR</span>
|
||||
</button>
|
||||
<button class="qr-toggle-btn" style="background: rgba(16, 185, 129, 0.25); border-color: rgba(52, 211, 153, 0.4);" onclick="openTransferModal()">
|
||||
<button id="btnCardTransfer" class="qr-toggle-btn" style="background: rgba(16, 185, 129, 0.25); border-color: rgba(52, 211, 153, 0.4);" onclick="openTransferModal()">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
|
||||
<span id="transferBtnText">Transferir</span>
|
||||
</button>
|
||||
@@ -1144,23 +1153,26 @@
|
||||
<span style="font-size: 0.7rem; color: #166534; background: #dcfce7; font-weight: 800; padding: 2px 8px; border-radius: 6px;">Acreditación Inmediata</span>
|
||||
</div>
|
||||
|
||||
<label style="display: block; font-size: 0.78rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
Escribe el monto a recargar:
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px;">
|
||||
<div>
|
||||
<label for="inputCustomSinpe" style="display: block; font-size: 0.76rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
Monto a recargar (₡):
|
||||
</label>
|
||||
<div style="position: relative; margin-bottom: 8px;">
|
||||
<span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #166534; font-size: 1.1rem;">₡</span>
|
||||
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputCustomSinpe" placeholder="Ej: 3000" style="width: 100%; padding: 10px 10px 10px 30px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.15rem; font-weight: 900; color: #166534; background: white;">
|
||||
<div style="position: relative;">
|
||||
<span style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-weight: 900; color: #166534; font-size: 1.05rem;">₡</span>
|
||||
<input type="tel" inputmode="numeric" pattern="[0-9]*" id="inputCustomSinpe" placeholder="Ej: 3000" style="width: 100%; padding: 10px 10px 10px 28px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.05rem; font-weight: 800; color: #166534; background: white; box-sizing: border-box;">
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="inputCustomSinpeComprobante" style="display: block; font-size: 0.76rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
|
||||
N° Comprobante:
|
||||
</label>
|
||||
<input type="text" id="inputCustomSinpeComprobante" placeholder="Ej: 894321" style="width: 100%; padding: 10px 12px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 1.05rem; font-weight: 800; color: #166534; background: white; box-sizing: border-box;">
|
||||
</div>
|
||||
|
||||
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 10px;">
|
||||
<button type="button" onclick="setWrittenRechargeAmount(1000)" style="padding: 7px 4px; background: white; border: 1px solid #86efac; border-radius: 8px; font-weight: 800; font-size: 0.76rem; color: #166534; cursor: pointer;">₡1.000</button>
|
||||
<button type="button" onclick="setWrittenRechargeAmount(2000)" style="padding: 7px 4px; background: white; border: 1px solid #86efac; border-radius: 8px; font-weight: 800; font-size: 0.76rem; color: #166534; cursor: pointer;">₡2.000</button>
|
||||
<button type="button" onclick="setWrittenRechargeAmount(5000)" style="padding: 7px 4px; background: white; border: 1px solid #86efac; border-radius: 8px; font-weight: 800; font-size: 0.76rem; color: #166534; cursor: pointer;">₡5.000</button>
|
||||
<button type="button" onclick="setWrittenRechargeAmount(10000)" style="padding: 7px 4px; background: white; border: 1px solid #86efac; border-radius: 8px; font-weight: 800; font-size: 0.76rem; color: #166534; cursor: pointer;">₡10.000</button>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="customSinpeRecharge()" style="width: 100%; padding: 12px; background: linear-gradient(135deg, #16a34a, #15803d); color: white; border: none; border-radius: 10px; font-weight: 900; font-size: 0.95rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 10px rgba(22, 163, 74, 0.3);">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/></svg> Aplicar Recarga de Saldo
|
||||
<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="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Validar SINPE
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
+140
-32
@@ -555,6 +555,26 @@ function updateStudentUI() {
|
||||
}
|
||||
});
|
||||
|
||||
// Gray-out del botón Transferir cuando los padres lo desactivan
|
||||
const btnCardTransfer = document.getElementById('btnCardTransfer');
|
||||
const pwaNavTransfer = document.getElementById('pwaNavTransfer');
|
||||
const transferenciasHabilitadas = currentStudent.permitir_transferencias !== 0;
|
||||
|
||||
if (btnCardTransfer) {
|
||||
if (!transferenciasHabilitadas) {
|
||||
btnCardTransfer.classList.add('transfer-btn-disabled');
|
||||
} else {
|
||||
btnCardTransfer.classList.remove('transfer-btn-disabled');
|
||||
}
|
||||
}
|
||||
if (pwaNavTransfer) {
|
||||
if (!transferenciasHabilitadas) {
|
||||
pwaNavTransfer.classList.add('transfer-nav-disabled');
|
||||
} else {
|
||||
pwaNavTransfer.classList.remove('transfer-nav-disabled');
|
||||
}
|
||||
}
|
||||
|
||||
// Alergias
|
||||
const allergyBox = document.getElementById('allergyWarning');
|
||||
if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') {
|
||||
@@ -929,37 +949,38 @@ async function quickSinpeRecharge(monto) {
|
||||
}
|
||||
|
||||
async function customSinpeRecharge() {
|
||||
const input = document.getElementById('inputCustomSinpe');
|
||||
const val = parseInt(input.value, 10);
|
||||
if (!val || val <= 0) return alert('Por favor escribe un monto válido a recargar en colones.');
|
||||
await doSinpeRecharge(val);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
async function doSinpeRecharge(monto) {
|
||||
if (!currentStudent) return;
|
||||
const comprobante = `SINPE-${Math.floor(100000 + Math.random() * 900000)}`;
|
||||
const inputMonto = document.getElementById('inputCustomSinpe');
|
||||
const inputComp = document.getElementById('inputCustomSinpeComprobante');
|
||||
const val = parseInt(inputMonto ? inputMonto.value : 0, 10);
|
||||
const comp = inputComp ? inputComp.value.trim() : '';
|
||||
|
||||
if (!val || val <= 0) return alert('Por favor escribe un monto válido a recargar en colones.');
|
||||
if (!comp) return alert('Por favor escribe el número de comprobante SINPE.');
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/estudiantes/${currentStudent.id}/recarga`, {
|
||||
const res = await fetch('/api/sinpe/solicitar', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
monto,
|
||||
comprobante,
|
||||
descripcion: `Recarga SINPE Móvil desde portal de padres`
|
||||
estudiante_id: currentStudent.id,
|
||||
padre_usuario_id: currentUser && currentUser.rol === 'padre' ? currentUser.id : null,
|
||||
monto: val,
|
||||
comprobante: comp,
|
||||
notas: `Portal Parental Móvil para ${currentStudent.nombre_completo}`
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playSuccess();
|
||||
alert(`¡Recarga SINPE exitosa!\nSe acreditaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentStudent.nombre_completo}.\nComprobante: ${comprobante}`);
|
||||
alert(`¡Solicitud de Recarga Enviada!\n\nMonto: ₡${val.toLocaleString('es-CR')}\nComprobante: #${comp}\n\nLa soda verificará el depósito y el saldo se acreditará automáticamente.`);
|
||||
|
||||
await selectStudent(currentStudent.id);
|
||||
if (inputMonto) inputMonto.value = '';
|
||||
if (inputComp) inputComp.value = '';
|
||||
} catch (err) {
|
||||
alert(`Error en recarga: ${err.message}`);
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`Error al enviar solicitud SINPE: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1541,6 +1562,7 @@ async function onToggleAllowTransfer(checked) {
|
||||
body: JSON.stringify({ permitir_transferencias: checked ? 1 : 0 })
|
||||
});
|
||||
currentStudent.permitir_transferencias = checked ? 1 : 0;
|
||||
updateStudentUI();
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
} catch (e) {
|
||||
console.error('Error actualizando permiso de transferencias:', e);
|
||||
@@ -1660,6 +1682,17 @@ function initStudentSSE() {
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sse.addEventListener('solicitud_sinpe_procesada', (e) => {
|
||||
try {
|
||||
if (currentUser && currentUser.rol === 'padre') {
|
||||
if (currentParentChild) {
|
||||
loadParentSinpeRequests(currentParentChild.id);
|
||||
}
|
||||
loadParentDashboard();
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sse.addEventListener('transferencia_realizada', (e) => {
|
||||
try {
|
||||
const data = JSON.parse(e.data);
|
||||
@@ -1978,6 +2011,7 @@ function renderActiveChildDetails(child) {
|
||||
if (chkTransfer) chkTransfer.checked = child.permitir_transferencias !== 0;
|
||||
|
||||
loadActiveChildHistory(child.id);
|
||||
loadParentSinpeRequests(child.id);
|
||||
}
|
||||
|
||||
async function loadActiveChildHistory(studentId) {
|
||||
@@ -2015,48 +2049,118 @@ async function loadActiveChildHistory(studentId) {
|
||||
}
|
||||
}
|
||||
|
||||
function setParentSinpePreset(amt) {
|
||||
const input = document.getElementById('inputParentSinpeMonto');
|
||||
if (input) input.value = amt;
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
}
|
||||
|
||||
async function executeParentSinpeRecharge() {
|
||||
if (!currentParentChild) {
|
||||
alert('Selecciona primero al estudiante a quien deseas recargarle.');
|
||||
return;
|
||||
}
|
||||
const input = document.getElementById('inputParentSinpeMonto');
|
||||
const monto = parseInt(input ? input.value : 0, 10);
|
||||
const inputMonto = document.getElementById('inputParentSinpeMonto');
|
||||
const inputComp = document.getElementById('inputParentSinpeComprobante');
|
||||
const btn = document.getElementById('btnParentValidarSinpe');
|
||||
|
||||
const monto = parseInt(inputMonto ? inputMonto.value : 0, 10);
|
||||
const comprobante = inputComp ? inputComp.value.trim() : '';
|
||||
|
||||
if (isNaN(monto) || monto <= 0) {
|
||||
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
|
||||
if (inputMonto) inputMonto.focus();
|
||||
return;
|
||||
}
|
||||
if (!comprobante) {
|
||||
alert('Por favor ingresa el número de comprobante de la transferencia SINPE Móvil.');
|
||||
if (inputComp) inputComp.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/estudiantes/${currentParentChild.id}/recarga`, {
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<span>Verificando...</span>';
|
||||
}
|
||||
|
||||
const res = await fetch('/api/sinpe/solicitar', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
estudiante_id: currentParentChild.id,
|
||||
padre_usuario_id: currentUser ? currentUser.id : null,
|
||||
monto,
|
||||
comprobante: 'SINPE-PADRE',
|
||||
descripcion: `Recarga SINPE Móvil por Padre/Madre para ${currentParentChild.nombre_completo}`
|
||||
comprobante,
|
||||
notas: `Portal de Padres - ${currentUser ? currentUser.nombre : 'Encargado'}`
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
alert(`¡Recarga Exitosa!\nSe agregaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentParentChild.nombre_completo}.\nNuevo Saldo: ₡${data.saldo_nuevo.toLocaleString('es-CR')}`);
|
||||
alert(`¡Solicitud de Recarga Enviada!\n\nMonto: ₡${monto.toLocaleString('es-CR')}\nComprobante: #${comprobante}\n\nLa soda verificará el depósito y el saldo se acreditará automáticamente.`);
|
||||
|
||||
if (input) input.value = '';
|
||||
await loadParentDashboard();
|
||||
if (inputMonto) inputMonto.value = '';
|
||||
if (inputComp) inputComp.value = '';
|
||||
|
||||
await loadParentSinpeRequests(currentParentChild.id);
|
||||
} catch (err) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`Error al procesar recarga SINPE: ${err.message}`);
|
||||
alert(`Error al enviar solicitud SINPE: ${err.message}`);
|
||||
} finally {
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>Validar SINPE</span>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadParentSinpeRequests(studentId) {
|
||||
const box = document.getElementById('parentSinpePendingBox');
|
||||
const list = document.getElementById('parentSinpePendingList');
|
||||
if (!box || !list) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/sinpe/solicitudes/estudiante/${studentId}`);
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
const solicitudes = data.solicitudes || [];
|
||||
if (solicitudes.length === 0) {
|
||||
box.style.display = 'none';
|
||||
list.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
box.style.display = 'block';
|
||||
list.innerHTML = solicitudes.slice(0, 5).map(s => {
|
||||
const fecha = new Date(s.creado_en).toLocaleString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||
let badgeStyle = '';
|
||||
let badgeText = '';
|
||||
|
||||
if (s.estado === 'pendiente') {
|
||||
badgeStyle = 'background: #fef3c7; color: #b45309; border: 1px solid #fde68a;';
|
||||
badgeText = '⏳ Por Verificar';
|
||||
} else if (s.estado === 'aprobada') {
|
||||
badgeStyle = 'background: #dcfce7; color: #15803d; border: 1px solid #bbf7d0;';
|
||||
badgeText = '✅ Acreditado';
|
||||
} else {
|
||||
badgeStyle = 'background: #fee2e2; color: #b91c1c; border: 1px solid #fecaca;';
|
||||
badgeText = '❌ Rechazado';
|
||||
}
|
||||
|
||||
return `
|
||||
<div style="background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px 10px; display: flex; justify-content: space-between; align-items: center; font-size: 0.76rem;">
|
||||
<div>
|
||||
<div style="font-weight: 800; color: #0f172a;">₡${s.monto_colones.toLocaleString('es-CR')} <span style="font-weight: 500; color: #64748b;">(Comp: #${s.comprobante_sinpe})</span></div>
|
||||
<div style="font-size: 0.68rem; color: #94a3b8;">${fecha}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span style="font-size: 0.7rem; font-weight: 800; padding: 3px 8px; border-radius: 6px; ${badgeStyle}">${badgeText}</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
} catch (err) {
|
||||
console.error('Error cargando solicitudes SINPE:', err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function setParentLimitPreset(amt) {
|
||||
const input = document.getElementById('inputParentCustomLimit');
|
||||
@@ -2117,6 +2221,10 @@ async function onToggleParentTransfer(checked) {
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
currentParentChild.permitir_transferencias = checked ? 1 : 0;
|
||||
if (currentStudent && currentStudent.id === currentParentChild.id) {
|
||||
currentStudent.permitir_transferencias = checked ? 1 : 0;
|
||||
updateStudentUI();
|
||||
}
|
||||
if (window.sounds) window.sounds.playTap();
|
||||
} catch (err) {
|
||||
alert(`No se pudo actualizar permiso de transferencia: ${err.message}`);
|
||||
|
||||
@@ -78,6 +78,7 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
checkPosHttpsEnvironment();
|
||||
await loadCatalog();
|
||||
await loadPreOrders();
|
||||
await loadSinpeRequests();
|
||||
// La cámara se activa bajo demanda al cobrar o identificar, NO al entrar
|
||||
initSSE();
|
||||
initPistolScanner();
|
||||
@@ -1150,12 +1151,18 @@ function switchPosTab(tab) {
|
||||
currentTab = tab;
|
||||
document.getElementById('tabBtnMostrador').classList.toggle('active', tab === 'mostrador');
|
||||
document.getElementById('tabBtnPreordenes').classList.toggle('active', tab === 'preordenes');
|
||||
const tabSinpe = document.getElementById('tabBtnSinpe');
|
||||
if (tabSinpe) tabSinpe.classList.toggle('active', tab === 'sinpe');
|
||||
|
||||
document.getElementById('viewPosMostrador').style.display = tab === 'mostrador' ? 'block' : 'none';
|
||||
document.getElementById('viewPosPreordenes').style.display = tab === 'preordenes' ? 'block' : 'none';
|
||||
const viewSinpe = document.getElementById('viewPosSinpe');
|
||||
if (viewSinpe) viewSinpe.style.display = tab === 'sinpe' ? 'block' : 'none';
|
||||
|
||||
if (tab === 'preordenes') {
|
||||
loadPreOrders();
|
||||
} else if (tab === 'sinpe') {
|
||||
loadSinpeRequests();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1337,4 +1344,152 @@ function initSSE() {
|
||||
}
|
||||
} catch (err) {}
|
||||
});
|
||||
|
||||
sseSource.addEventListener('solicitud_sinpe_nueva', (e) => {
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
loadSinpeRequests();
|
||||
});
|
||||
|
||||
sseSource.addEventListener('solicitud_sinpe_procesada', () => {
|
||||
loadSinpeRequests();
|
||||
});
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// RECARGAS SINPE EN POS
|
||||
// ==========================================
|
||||
|
||||
async function loadSinpeRequests() {
|
||||
const list = document.getElementById('sinpeRequestsList');
|
||||
const badge = document.getElementById('badgeSinpeCount');
|
||||
if (!list) return;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/sinpe/solicitudes?estado=pendiente');
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
const solicitudes = data.solicitudes || [];
|
||||
|
||||
if (badge) {
|
||||
if (solicitudes.length > 0) {
|
||||
badge.textContent = solicitudes.length;
|
||||
badge.style.display = 'inline-block';
|
||||
} else {
|
||||
badge.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
if (solicitudes.length === 0) {
|
||||
list.innerHTML = `
|
||||
<div style="background: white; border: 1.5px dashed #cbd5e1; border-radius: 14px; padding: 48px 20px; text-align: center; color: #64748b;">
|
||||
<div style="font-size: 2.5rem; margin-bottom: 8px;">✨</div>
|
||||
<strong style="color: #0f172a; font-size: 1.05rem; display: block; margin-bottom: 4px;">No hay recargas SINPE pendientes</strong>
|
||||
<p style="font-size: 0.85rem; margin: 0; color: #94a3b8;">Todas las recargas reportadas por los padres han sido procesadas.</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = solicitudes.map(s => {
|
||||
const fecha = new Date(s.creado_en).toLocaleString('es-CR', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
|
||||
return `
|
||||
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 16px; box-shadow: 0 2px 6px rgba(0,0,0,0.03); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 14px;">
|
||||
<div style="display: flex; align-items: center; gap: 12px; min-width: 240px;">
|
||||
<img src="${s.estudiante_foto || 'https://api.dicebear.com/7.x/bottts/svg?seed=' + s.estudiante_id}" style="width: 48px; height: 48px; border-radius: 12px; object-fit: cover; border: 1.5px solid #cbd5e1; background: #f8fafc;" alt="Foto">
|
||||
<div>
|
||||
<div style="font-weight: 800; font-size: 0.95rem; color: #0f172a;">${s.estudiante_nombre}</div>
|
||||
<div style="font-size: 0.76rem; color: #64748b;">
|
||||
${s.estudiante_grado || ''} ${s.estudiante_seccion ? '• Sec. ' + s.estudiante_seccion : ''}
|
||||
<span style="background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-weight: 700; color: #334155; margin-left: 4px;">Saldo actual: ₡${(s.estudiante_saldo || 0).toLocaleString('es-CR')}</span>
|
||||
</div>
|
||||
<div style="font-size: 0.72rem; color: #94a3b8; margin-top: 3px;">
|
||||
Reportado: ${fecha}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; flex-direction: column; align-items: flex-end; min-width: 140px;">
|
||||
<div style="font-size: 1.25rem; font-weight: 900; color: #16a34a;">
|
||||
+₡${s.monto_colones.toLocaleString('es-CR')}
|
||||
</div>
|
||||
<div style="font-size: 0.8rem; font-weight: 800; color: #1e293b; background: #f8fafc; border: 1px solid #e2e8f0; padding: 3px 8px; border-radius: 6px; margin-top: 2px;">
|
||||
Comp: <span style="font-family: monospace; color: #0284c7;">#${s.comprobante_sinpe}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
|
||||
<button onclick="procesarSinpePos(${s.id}, 'aprobar')" style="padding: 10px 16px; background: linear-gradient(135deg, #16a34a, #15803d); color: white; border: none; border-radius: 10px; font-weight: 800; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(22, 163, 74, 0.25);">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
|
||||
<span>Aprobar y Acreditar</span>
|
||||
</button>
|
||||
<button onclick="procesarSinpePos(${s.id}, 'rechazar')" style="padding: 10px 14px; background: #fff1f2; color: #e11d48; border: 1px solid #fecdd3; border-radius: 10px; font-weight: 800; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; gap: 6px;">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
<span>Rechazar</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
} catch (err) {
|
||||
console.error('Error cargando solicitudes SINPE:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function procesarSinpePos(solicitudId, accion) {
|
||||
if (accion === 'aprobar') {
|
||||
const ok = confirm('¿Confirmas que verificaste el comprobante y el dinero ya ingresó a la cuenta bancaria de la soda?');
|
||||
if (!ok) return;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/sinpe/procesar', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
solicitud_id: solicitudId,
|
||||
accion: 'aprobar',
|
||||
usuario_id: null
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
if (window.sounds) window.sounds.playCoin();
|
||||
alert(`¡Recarga Aprobada!\nSe acreditaron ₡${data.resultado.monto.toLocaleString('es-CR')} al estudiante ${data.resultado.estudiante_nombre}.\nNuevo saldo: ₡${data.resultado.saldo_nuevo.toLocaleString('es-CR')}.`);
|
||||
loadSinpeRequests();
|
||||
} catch (err) {
|
||||
if (window.sounds) window.sounds.playError();
|
||||
alert(`Error al aprobar recarga: ${err.message}`);
|
||||
}
|
||||
} else if (accion === 'rechazar') {
|
||||
const motivo = prompt('Motivo del rechazo de la recarga:', 'Comprobante no coincide o fondos no recibidos');
|
||||
if (motivo === null) return; // cancelado por usuario
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/sinpe/procesar', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
solicitud_id: solicitudId,
|
||||
accion: 'rechazar',
|
||||
motivo: motivo || 'Rechazado por la soda',
|
||||
usuario_id: null
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error);
|
||||
|
||||
alert('La solicitud de recarga ha sido rechazada.');
|
||||
loadSinpeRequests();
|
||||
} catch (err) {
|
||||
alert(`Error al rechazar recarga: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,9 @@
|
||||
<button class="pos-tab-btn" id="tabBtnPreordenes" onclick="switchPosTab('preordenes')">
|
||||
<span>📦</span> Fila Rápida Pre-Órdenes <span id="badgePreordenesCount" style="background: #ef4444; color: white; padding: 2px 7px; border-radius: 10px; font-size: 0.75rem;">0</span>
|
||||
</button>
|
||||
<button class="pos-tab-btn" id="tabBtnSinpe" onclick="switchPosTab('sinpe')">
|
||||
<span>📱</span> Recargas SINPE <span id="badgeSinpeCount" style="background: #10b981; color: white; padding: 2px 7px; border-radius: 10px; font-size: 0.75rem; display: none;">0</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- VISTA 1: CATÁLOGO TÁCTIL DE PRODUCTOS (MOSTRADOR) -->
|
||||
@@ -171,6 +174,29 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- VISTA 3: RECARGAS SINPE PENDIENTES DE VERIFICACIÓN -->
|
||||
<div id="viewPosSinpe" style="display: none;">
|
||||
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 14px 18px; margin-bottom: 14px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.04);">
|
||||
<div>
|
||||
<div style="display: flex; align-items: center; gap: 6px;">
|
||||
<span style="font-size: 1.1rem;">📱</span>
|
||||
<strong style="color: #0f172a; font-size: 0.95rem;">Recargas SINPE por Verificar</strong>
|
||||
</div>
|
||||
<p style="font-size: 0.78rem; color: #64748b; margin: 3px 0 0 0;">Verifica que el dinero ingresó a la cuenta bancaria de la soda antes de aprobar la recarga.</p>
|
||||
</div>
|
||||
<div>
|
||||
<button onclick="loadSinpeRequests()" class="btn-saas btn-saas-outline" style="height: 36px; padding: 0 12px;">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M3 21v-5h5"/></svg>
|
||||
<span>Refrescar</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="sinpeRequestsList" style="display: flex; flex-direction: column; gap: 12px;">
|
||||
<!-- Lista de solicitudes SINPE pendientes -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- BARRA FLOTANTE DE ACCESO RÁPIDO A CAJA EN MÓVIL -->
|
||||
<div id="posFloatingCheckoutBar" class="pos-floating-checkout-bar" onclick="switchPosMobileView('checkout')" style="display: none;">
|
||||
<div style="display: flex; align-items: center; gap: 10px;">
|
||||
|
||||
+128
-1
@@ -272,6 +272,24 @@ function initDatabase() {
|
||||
`);
|
||||
} catch (e) {}
|
||||
|
||||
// 11. Solicitudes de Recarga SINPE Móvil
|
||||
try {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS solicitudes_recarga_sinpe (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
estudiante_id INTEGER NOT NULL REFERENCES estudiantes(id) ON DELETE CASCADE,
|
||||
padre_usuario_id INTEGER,
|
||||
monto_colones INTEGER NOT NULL,
|
||||
comprobante_sinpe TEXT NOT NULL,
|
||||
estado TEXT DEFAULT 'pendiente',
|
||||
notas TEXT,
|
||||
aprobado_por_usuario_id INTEGER,
|
||||
creado_en DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
procesado_en DATETIME
|
||||
);
|
||||
`);
|
||||
} catch (e) {}
|
||||
|
||||
seedInitialData();
|
||||
seedUsuarios();
|
||||
seedDisenosTarjetas();
|
||||
@@ -1006,6 +1024,111 @@ function revertirTransaccionSaldoTransaction({ transaccionId, usuarioId, usuario
|
||||
return transaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* Crea una nueva solicitud de recarga por SINPE Móvil enviada por un padre
|
||||
*/
|
||||
function crearSolicitudRecargaSinpe({ estudianteId, padreUsuarioId, monto, comprobante, notas }) {
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO solicitudes_recarga_sinpe (estudiante_id, padre_usuario_id, monto_colones, comprobante_sinpe, estado, notas)
|
||||
VALUES (?, ?, ?, ?, 'pendiente', ?)
|
||||
`);
|
||||
const res = insert.run(estudianteId, padreUsuarioId || null, parseInt(monto, 10), String(comprobante).trim(), notas || '');
|
||||
return {
|
||||
id: res.lastInsertRowid,
|
||||
estudiante_id: estudianteId,
|
||||
monto_colones: parseInt(monto, 10),
|
||||
comprobante_sinpe: String(comprobante).trim(),
|
||||
estado: 'pendiente'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene las solicitudes de recarga SINPE (con datos del estudiante)
|
||||
*/
|
||||
function obtenerSolicitudesRecargaSinpe(filtroEstado = 'pendiente') {
|
||||
let sql = `
|
||||
SELECT s.*,
|
||||
e.nombre_completo as estudiante_nombre,
|
||||
e.grado as estudiante_grado,
|
||||
e.seccion as estudiante_seccion,
|
||||
e.foto_url as estudiante_foto,
|
||||
e.saldo_colones as estudiante_saldo
|
||||
FROM solicitudes_recarga_sinpe s
|
||||
JOIN estudiantes e ON e.id = s.estudiante_id
|
||||
`;
|
||||
if (filtroEstado && filtroEstado !== 'todas') {
|
||||
sql += ` WHERE s.estado = ? ORDER BY s.creado_en DESC`;
|
||||
return db.prepare(sql).all(filtroEstado);
|
||||
} else {
|
||||
sql += ` ORDER BY s.creado_en DESC`;
|
||||
return db.prepare(sql).all();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene las solicitudes de recarga de un estudiante específico (para el portal de padres)
|
||||
*/
|
||||
function obtenerSolicitudesRecargaPorEstudiante(estudianteId) {
|
||||
return db.prepare(`
|
||||
SELECT * FROM solicitudes_recarga_sinpe
|
||||
WHERE estudiante_id = ?
|
||||
ORDER BY creado_en DESC
|
||||
LIMIT 10
|
||||
`).all(estudianteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesa (aprueba o rechaza) una solicitud de recarga SINPE
|
||||
*/
|
||||
function procesarSolicitudRecargaSinpe({ solicitudId, accion, usuarioId, motivo }) {
|
||||
const transaction = db.transaction(() => {
|
||||
const sol = db.prepare('SELECT * FROM solicitudes_recarga_sinpe WHERE id = ?').get(solicitudId);
|
||||
if (!sol) throw new Error('Solicitud de recarga no encontrada');
|
||||
if (sol.estado !== 'pendiente') throw new Error(`Esta solicitud ya fue ${sol.estado}`);
|
||||
|
||||
if (accion === 'aprobar') {
|
||||
const resultadoSaldo = recargaSaldoTransaction({
|
||||
estudianteId: sol.estudiante_id,
|
||||
monto: sol.monto_colones,
|
||||
comprobanteSinpe: sol.comprobante_sinpe,
|
||||
descripcion: `Recarga SINPE aprobada en soda (Comprobante #${sol.comprobante_sinpe})`
|
||||
});
|
||||
|
||||
db.prepare(`
|
||||
UPDATE solicitudes_recarga_sinpe
|
||||
SET estado = 'aprobada', aprobado_por_usuario_id = ?, procesado_en = CURRENT_TIMESTAMP, notas = ?
|
||||
WHERE id = ?
|
||||
`).run(usuarioId || null, motivo || 'Aprobada por la soda', solicitudId);
|
||||
|
||||
return {
|
||||
solicitud_id: solicitudId,
|
||||
estado: 'aprobada',
|
||||
estudiante_id: sol.estudiante_id,
|
||||
monto: sol.monto_colones,
|
||||
saldo_nuevo: resultadoSaldo.saldo_nuevo,
|
||||
estudiante_nombre: resultadoSaldo.nombre
|
||||
};
|
||||
} else if (accion === 'rechazar') {
|
||||
db.prepare(`
|
||||
UPDATE solicitudes_recarga_sinpe
|
||||
SET estado = 'rechazada', aprobado_por_usuario_id = ?, procesado_en = CURRENT_TIMESTAMP, notas = ?
|
||||
WHERE id = ?
|
||||
`).run(usuarioId || null, motivo || 'Comprobante no verificado en cuenta', solicitudId);
|
||||
|
||||
return {
|
||||
solicitud_id: solicitudId,
|
||||
estado: 'rechazada',
|
||||
estudiante_id: sol.estudiante_id,
|
||||
monto: sol.monto_colones
|
||||
};
|
||||
} else {
|
||||
throw new Error('Acción no válida (usar aprobar o rechazar)');
|
||||
}
|
||||
});
|
||||
|
||||
return transaction();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
db,
|
||||
initDatabase,
|
||||
@@ -1013,5 +1136,9 @@ module.exports = {
|
||||
recargaSaldoTransaction,
|
||||
crearOrdenCompleta,
|
||||
transferenciaP2PTransaction,
|
||||
revertirTransaccionSaldoTransaction
|
||||
revertirTransaccionSaldoTransaction,
|
||||
crearSolicitudRecargaSinpe,
|
||||
obtenerSolicitudesRecargaSinpe,
|
||||
obtenerSolicitudesRecargaPorEstudiante,
|
||||
procesarSolicitudRecargaSinpe
|
||||
};
|
||||
|
||||
+110
-1
@@ -10,7 +10,19 @@ try {
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const QRCode = require('qrcode');
|
||||
const { db, initDatabase, debitoCompraTransaction, recargaSaldoTransaction, crearOrdenCompleta, transferenciaP2PTransaction, revertirTransaccionSaldoTransaction } = require('./db');
|
||||
const {
|
||||
db,
|
||||
initDatabase,
|
||||
debitoCompraTransaction,
|
||||
recargaSaldoTransaction,
|
||||
crearOrdenCompleta,
|
||||
transferenciaP2PTransaction,
|
||||
revertirTransaccionSaldoTransaction,
|
||||
crearSolicitudRecargaSinpe,
|
||||
obtenerSolicitudesRecargaSinpe,
|
||||
obtenerSolicitudesRecargaPorEstudiante,
|
||||
procesarSolicitudRecargaSinpe
|
||||
} = require('./db');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3030;
|
||||
@@ -1459,6 +1471,103 @@ app.post('/api/estudiantes/:id/recarga', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// SOLICITUDES DE RECARGA SINPE MÓVIL (PORTAL PADRES & SODA)
|
||||
// ==========================================
|
||||
|
||||
// 1. Crear solicitud de recarga (enviada por el padre)
|
||||
app.post('/api/sinpe/solicitar', (req, res) => {
|
||||
try {
|
||||
const { estudiante_id, padre_usuario_id, monto, comprobante, notas } = req.body;
|
||||
if (!estudiante_id) return res.status(400).json({ error: 'Estudiante no especificado' });
|
||||
const montoNum = parseInt(monto, 10);
|
||||
if (isNaN(montoNum) || montoNum <= 0) {
|
||||
return res.status(400).json({ error: 'Ingresa un monto válido mayor a ₡0' });
|
||||
}
|
||||
const cleanComp = String(comprobante || '').trim();
|
||||
if (!cleanComp) {
|
||||
return res.status(400).json({ error: 'Debes ingresar el número de comprobante SINPE' });
|
||||
}
|
||||
|
||||
const nuevaSol = crearSolicitudRecargaSinpe({
|
||||
estudianteId: parseInt(estudiante_id, 10),
|
||||
padreUsuarioId: padre_usuario_id ? parseInt(padre_usuario_id, 10) : null,
|
||||
monto: montoNum,
|
||||
comprobante: cleanComp,
|
||||
notas
|
||||
});
|
||||
|
||||
const estudiante = db.prepare('SELECT nombre_completo, grado, seccion, foto_url FROM estudiantes WHERE id = ?').get(estudiante_id);
|
||||
|
||||
const payloadNotificacion = {
|
||||
...nuevaSol,
|
||||
estudiante_nombre: estudiante ? estudiante.nombre_completo : 'Estudiante',
|
||||
estudiante_grado: estudiante ? estudiante.grado : '',
|
||||
estudiante_seccion: estudiante ? estudiante.seccion : '',
|
||||
estudiante_foto: estudiante ? estudiante.foto_url : ''
|
||||
};
|
||||
|
||||
broadcastEvent('solicitud_sinpe_nueva', payloadNotificacion);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
mensaje: 'Solicitud de recarga enviada. La soda verificará el comprobante en breve.',
|
||||
solicitud: payloadNotificacion
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Listar solicitudes (para la soda/admin)
|
||||
app.get('/api/sinpe/solicitudes', (req, res) => {
|
||||
try {
|
||||
const estado = req.query.estado || 'pendiente';
|
||||
const solicitudes = obtenerSolicitudesRecargaSinpe(estado);
|
||||
res.json({ success: true, solicitudes });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Listar solicitudes por estudiante (para el portal de padres)
|
||||
app.get('/api/sinpe/solicitudes/estudiante/:id', (req, res) => {
|
||||
try {
|
||||
const solicitudes = obtenerSolicitudesRecargaPorEstudiante(parseInt(req.params.id, 10));
|
||||
res.json({ success: true, solicitudes });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 4. Procesar (aprobar o rechazar) solicitud de recarga desde la soda
|
||||
app.post('/api/sinpe/procesar', (req, res) => {
|
||||
try {
|
||||
const { solicitud_id, accion, usuario_id, motivo } = req.body;
|
||||
if (!solicitud_id || !accion) {
|
||||
return res.status(400).json({ error: 'solicitud_id y accion son obligatorios' });
|
||||
}
|
||||
|
||||
const resultado = procesarSolicitudRecargaSinpe({
|
||||
solicitudId: parseInt(solicitud_id, 10),
|
||||
accion,
|
||||
usuarioId: usuario_id ? parseInt(usuario_id, 10) : null,
|
||||
motivo
|
||||
});
|
||||
|
||||
if (resultado.estado === 'aprobada') {
|
||||
broadcastEvent('recarga_exitosa', resultado);
|
||||
broadcastEvent('estudiante_actualizado', { id: resultado.estudiante_id, saldo_colones: resultado.saldo_nuevo });
|
||||
broadcastEvent('saldo_actualizado', { id: resultado.estudiante_id, saldo_colones: resultado.saldo_nuevo });
|
||||
}
|
||||
broadcastEvent('solicitud_sinpe_procesada', resultado);
|
||||
|
||||
res.json({ success: true, resultado });
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Actualizar configuración parental (Límite diario, restricciones y transferencias P2P)
|
||||
app.put('/api/estudiantes/:id/limite', (req, res) => {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user