feat(sinpe): modal de validación en tiempo real con animación, sondeo de 18s y cero alertas nativas

This commit is contained in:
unknown
2026-10-06 23:51:17 -06:00
parent e1bc94fc5a
commit 440e0f4edb
3 changed files with 800 additions and 46 deletions
+238
View File
@@ -4578,3 +4578,241 @@ body.dark-mode .parent-subview-back-btn:hover {
color: #38bdf8;
border-color: #38bdf8;
}
/* ========================================================
MODAL DE VALIDACIÓN Y ESTADO SINPE EN TIEMPO REAL
======================================================== */
.modal-sinpe-backdrop {
z-index: 9999 !important;
}
.modal-sinpe-card {
max-width: 420px !important;
width: 92% !important;
border-radius: 24px !important;
padding: 26px 20px !important;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.45) !important;
position: relative !important;
text-align: center !important;
overflow: hidden !important;
}
.modal-sinpe-close-btn {
position: absolute;
top: 14px;
right: 14px;
background: rgba(100, 116, 139, 0.12);
border: none;
width: 32px;
height: 32px;
border-radius: 50%;
font-size: 1rem;
font-weight: 700;
color: #64748b;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
z-index: 10;
}
.modal-sinpe-close-btn:hover {
background: rgba(100, 116, 139, 0.25);
color: #0f172a;
}
.sinpe-spinner-container {
position: relative;
width: 84px;
height: 84px;
margin: 0 auto 12px auto;
display: flex;
align-items: center;
justify-content: center;
}
.sinpe-pulse-ring {
position: absolute;
inset: -6px;
border-radius: 50%;
border: 3px solid #86efac;
opacity: 0.8;
animation: sinpePulseRing 2s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
}
@keyframes sinpePulseRing {
0% { transform: scale(0.85); opacity: 0.9; }
50% { transform: scale(1.18); opacity: 0.3; }
100% { transform: scale(1.35); opacity: 0; }
}
.sinpe-icon-badge {
width: 76px;
height: 76px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto;
position: relative;
z-index: 2;
}
.sinpe-icon-badge.loading {
background: #f0fdf4;
border: 2px solid #86efac;
}
.sinpe-icon-badge.success {
background: #dcfce7;
border: 2.5px solid #86efac;
animation: sinpePopIn 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.sinpe-icon-badge.pending {
background: #fef3c7;
border: 2.5px solid #fde68a;
animation: sinpePopIn 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.sinpe-icon-badge.error {
background: #fee2e2;
border: 2.5px solid #fca5a5;
animation: sinpePopIn 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.sinpe-spin-svg {
animation: sinpeSpin 1.1s linear infinite;
}
@keyframes sinpeSpin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes sinpePopIn {
0% { transform: scale(0.6); opacity: 0; }
100% { transform: scale(1); opacity: 1; }
}
.sinpe-progress-track {
width: 100%;
height: 8px;
background: #e2e8f0;
border-radius: 99px;
overflow: hidden;
margin-top: 14px;
}
.sinpe-progress-bar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, #16a34a, #22c55e);
border-radius: 99px;
transition: width 0.15s linear;
}
.sinpe-info-summary {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 10px 14px;
margin-top: 14px;
text-align: left;
}
.sinpe-card-receipt {
background: #f0fdf4;
border: 1.5px solid #86efac;
border-radius: 16px;
padding: 14px 16px;
margin: 14px 0 16px 0;
text-align: left;
}
.sinpe-info-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.82rem;
margin-bottom: 5px;
color: #334155;
}
.sinpe-info-row:last-child {
margin-bottom: 0;
}
.btn-sinpe-action {
width: 100%;
padding: 13px 18px;
border-radius: 12px;
font-weight: 800;
font-size: 0.95rem;
cursor: pointer;
border: none;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
transition: transform 0.15s, opacity 0.15s;
}
.btn-sinpe-action:hover {
transform: translateY(-1px);
opacity: 0.95;
}
.btn-sinpe-action:active {
transform: translateY(1px);
}
.btn-sinpe-success {
background: linear-gradient(135deg, #16a34a, #15803d);
color: white;
box-shadow: 0 4px 14px rgba(22, 163, 74, 0.35);
}
.btn-sinpe-pending {
background: linear-gradient(135deg, #d97706, #b45309);
color: white;
box-shadow: 0 4px 14px rgba(217, 119, 6, 0.35);
}
.btn-sinpe-error {
background: linear-gradient(135deg, #dc2626, #b91c1c);
color: white;
box-shadow: 0 4px 14px rgba(220, 38, 38, 0.35);
}
body.dark-mode .modal-sinpe-card {
background: #0f172a !important;
color: #f8fafc !important;
border: 1px solid #334155 !important;
}
body.dark-mode .modal-sinpe-close-btn {
background: rgba(255, 255, 255, 0.1);
color: #94a3b8;
}
body.dark-mode .modal-sinpe-close-btn:hover {
background: rgba(255, 255, 255, 0.2);
color: #f8fafc;
}
body.dark-mode .sinpe-info-summary {
background: #1e293b;
border-color: #334155;
}
body.dark-mode .sinpe-info-row {
color: #cbd5e1;
}
body.dark-mode .sinpe-card-receipt {
background: #064e3b;
border-color: #059669;
}
+201 -17
View File
@@ -12,7 +12,7 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="SiboPay">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="/css/styles.css?v=10.0">
<link rel="stylesheet" href="/css/styles.css?v=10.1">
<style>
/* Transiciones suaves */
.fade-enter { animation: fadeIn 0.2s ease-in-out; }
@@ -1034,28 +1034,66 @@
<span style="font-size: 0.7rem; color: #166534; background: #dcfce7; font-weight: 800; padding: 3px 8px; border-radius: 6px;">Inmediato</span>
</div>
<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 (₡):
<!-- 1. Monto a Recargar -->
<div style="margin-bottom: 12px;">
<label for="inputParentSinpeMonto" style="display: block; font-size: 0.80rem; font-weight: 800; color: #166534; margin-bottom: 4px;">
1. Monto a recargar (₡):
</label>
<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;">
<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="inputParentSinpeMonto" placeholder="Ej: 3000" style="width: 100%; padding: 10px 12px 10px 30px; border-radius: 10px; border: 1.8px solid #86efac; font-size: 1.1rem; font-weight: 800; color: #166534; background: white; box-sizing: border-box; outline: none;">
</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;">
<!-- Montos sugeridos rápidos -->
<div style="display: flex; gap: 6px; margin-top: 7px; flex-wrap: wrap;">
<button type="button" onclick="setParentSinpeMonto(1000)" style="background: white; border: 1px solid #86efac; color: #166534; font-size: 0.74rem; font-weight: 700; padding: 4px 9px; border-radius: 8px; cursor: pointer;">₡1.000</button>
<button type="button" onclick="setParentSinpeMonto(2000)" style="background: white; border: 1px solid #86efac; color: #166534; font-size: 0.74rem; font-weight: 700; padding: 4px 9px; border-radius: 8px; cursor: pointer;">₡2.000</button>
<button type="button" onclick="setParentSinpeMonto(3000)" style="background: white; border: 1px solid #86efac; color: #166534; font-size: 0.74rem; font-weight: 700; padding: 4px 9px; border-radius: 8px; cursor: pointer;">₡3.000</button>
<button type="button" onclick="setParentSinpeMonto(5000)" style="background: white; border: 1px solid #86efac; color: #166534; font-size: 0.74rem; font-weight: 700; padding: 4px 9px; border-radius: 8px; cursor: pointer;">₡5.000</button>
<button type="button" onclick="setParentSinpeMonto(10000)" style="background: white; border: 1px solid #86efac; color: #166534; font-size: 0.74rem; font-weight: 700; padding: 4px 9px; border-radius: 8px; cursor: pointer;">₡10.000</button>
</div>
</div>
<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>
<!-- 2. Caja de Código de Detalle Obligatorio -->
<div style="background: #ffffff; border: 2px dashed #16a34a; border-radius: 12px; padding: 12px; margin-bottom: 12px; text-align: center; box-shadow: 0 2px 6px rgba(22, 163, 74, 0.06);">
<div style="font-size: 0.74rem; font-weight: 800; color: #15803d; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 3px;">
2. Código Obligatorio en el Detalle
</div>
<p style="font-size: 0.72rem; color: #475569; margin: 0 0 8px 0; line-height: 1.3;">
En la app de tu banco, coloca este código en el campo <strong>"Detalle"</strong> o <strong>"Motivo"</strong>:
</p>
<div style="display: flex; align-items: center; justify-content: center; gap: 8px; background: #f0fdf4; border: 1.5px solid #86efac; border-radius: 10px; padding: 8px 12px; margin-bottom: 6px;">
<span id="parentSinpeCodigoDisplay" style="font-family: 'Courier New', Courier, monospace; font-size: 1.45rem; font-weight: 900; color: #166534; letter-spacing: 1.5px; user-select: all;">SIBO-CARGANDO</span>
<button type="button" id="btnCopiarCodigoSinpe" onclick="copiarCodigoSinpe()" style="background: #16a34a; color: white; border: none; padding: 7px 12px; border-radius: 8px; font-weight: 800; font-size: 0.80rem; cursor: pointer; display: flex; align-items: center; gap: 4px; box-shadow: 0 2px 5px rgba(22, 163, 74, 0.25);">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
<span id="lblCopiarCodigoSinpe">Copiar código</span>
</button>
</div>
<div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.68rem; color: #64748b; padding: 0 2px;">
<span>Válido pegado, con guión o minúsculas.</span>
<button type="button" onclick="obtenerNuevoCodigoSinpe()" style="background: none; border: none; color: #0284c7; font-weight: 700; cursor: pointer; text-decoration: underline; font-size: 0.68rem; padding: 0;">
🔄 Cambiar código
</button>
</div>
</div>
<!-- 3. Comprobante Opcional -->
<div style="margin-bottom: 12px;">
<label for="inputParentSinpeComprobante" style="display: block; font-size: 0.76rem; font-weight: 800; color: #166534; margin-bottom: 3px;">
3. N° de Comprobante bancario <span style="font-size: 0.68rem; font-weight: 600; color: #64748b;">(Opcional)</span>:
</label>
<input type="text" id="inputParentSinpeComprobante" placeholder="Ej: 894321 (Opcional si pusiste el código en el detalle)" style="width: 100%; padding: 9px 11px; border-radius: 10px; border: 1.5px solid #86efac; font-size: 0.95rem; font-weight: 700; color: #166534; background: white; box-sizing: border-box;">
</div>
<!-- Botón de Validar SINPE -->
<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.98rem; 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="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" 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 id="btnParentValidarSinpeText">Validar SINPE</span>
</button>
<!-- Banner de estado dinámico -->
<div id="parentSinpeStatusMsg" style="display: none; margin-top: 10px; padding: 10px 12px; border-radius: 10px; font-size: 0.80rem; line-height: 1.4;"></div>
<!-- LISTA DE SOLICITUDES SINPE PENDIENTES DEL HIJO -->
<div id="parentSinpePendingBox" style="margin-top: 14px; border-top: 1px dashed #86efac; padding-top: 10px; display: none;">
@@ -2356,6 +2394,152 @@
</div>
</div>
<!-- ======================================================== -->
<!-- MODAL DE VALIDACIÓN Y ESTADO SINPE EN TIEMPO REAL -->
<!-- ======================================================== -->
<div class="modal-qr-backdrop modal-sinpe-backdrop" id="modalSinpeValidacion" style="display: none;" onclick="handleSinpeBackdropClick(event)">
<div class="modal-qr-card modal-sinpe-card" onclick="event.stopPropagation()">
<button type="button" class="modal-sinpe-close-btn" id="modalSinpeBtnCloseX" onclick="closeSinpeModal()" style="display: none;" title="Cerrar">✕</button>
<!-- 1. ESTADO: CARGANDO / VALIDANDO SINPE (10-20s con barra y animación) -->
<div id="modalSinpeStateLoading" style="display: none;">
<div class="sinpe-spinner-container">
<div class="sinpe-pulse-ring"></div>
<div class="sinpe-icon-badge loading">
<svg class="sinpe-spin-svg" width="38" height="38" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="#dcfce7" stroke-width="3"/>
<path d="M12 2a10 10 0 0 1 10 10" stroke="#16a34a" stroke-width="3" stroke-linecap="round"/>
</svg>
</div>
</div>
<h3 style="margin: 14px 0 4px 0; font-size: 1.25rem; font-weight: 900; color: var(--text-main);">Validando SINPE</h3>
<p id="modalSinpeLoadingSubtext" style="font-size: 0.85rem; color: #64748b; margin: 0 0 14px 0; line-height: 1.35;">
Consultando confirmación bancaria en tiempo real...
</p>
<!-- Barra de Progreso y Cuenta Regresiva de 18s -->
<div class="sinpe-progress-track">
<div class="sinpe-progress-bar" id="modalSinpeProgressBar"></div>
</div>
<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 6px; font-size: 0.72rem; color: #64748b; font-weight: 700;">
<span id="modalSinpeStepText">Buscando comprobante bancario...</span>
<span id="modalSinpeTimerText" style="color: #16a34a; font-weight: 900; font-family: monospace; font-size: 0.82rem;">18s</span>
</div>
<!-- Resumen de la Operación -->
<div class="sinpe-info-summary">
<div class="sinpe-info-row">
<span>Estudiante:</span>
<strong id="modalSinpeSummaryChild">-</strong>
</div>
<div class="sinpe-info-row">
<span>Monto a validar:</span>
<strong id="modalSinpeSummaryMonto" style="color: #16a34a; font-size: 0.96rem;">₡0</strong>
</div>
<div class="sinpe-info-row">
<span>Código de detalle:</span>
<strong id="modalSinpeSummaryCodigo" style="font-family: monospace; letter-spacing: 0.5px; color: #15803d;">-</strong>
</div>
</div>
<div style="font-size: 0.73rem; color: #64748b; margin-top: 14px; line-height: 1.4; background: #f8fafc; padding: 9px 12px; border-radius: 10px; border: 1px solid #e2e8f0; text-align: left;">
<span style="font-weight: 800; color: #334155;">⏳ Espere un momento, por favor:</span> Los bancos emiten el comprobante digital entre 10 y 20 segundos después de realizar el envío.
</div>
</div>
<!-- 2. ESTADO: ÉXITO / VALIDADO -->
<div id="modalSinpeStateSuccess" style="display: none;">
<div class="sinpe-icon-badge success">
<svg width="42" height="42" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2.8" 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>
</div>
<h3 style="margin: 14px 0 4px 0; font-size: 1.25rem; font-weight: 900; color: #15803d;">¡Pago Verificado con Éxito!</h3>
<p style="font-size: 0.84rem; color: #64748b; margin: 0 0 12px 0;">
El dinero fue acreditado automáticamente al monedero.
</p>
<div class="sinpe-card-receipt">
<div style="font-size: 0.72rem; text-transform: uppercase; color: #166534; font-weight: 800; letter-spacing: 0.5px; margin-bottom: 2px;">Monto Acreditado</div>
<div id="modalSinpeSuccessMonto" style="font-size: 1.8rem; font-weight: 900; color: #15803d; margin-bottom: 10px;">₡0</div>
<div class="sinpe-info-row">
<span>Estudiante:</span>
<strong id="modalSinpeSuccessChild">-</strong>
</div>
<div class="sinpe-info-row">
<span>Banco emisor:</span>
<strong id="modalSinpeSuccessBanco">Banco</strong>
</div>
<div class="sinpe-info-row">
<span>Comprobante:</span>
<strong id="modalSinpeSuccessComp" style="font-family: monospace;">-</strong>
</div>
<div class="sinpe-info-row" style="border-top: 1px dashed #86efac; padding-top: 8px; margin-top: 6px;">
<span style="font-weight: 800; color: #166534;">Nuevo Saldo Disponible:</span>
<strong id="modalSinpeSuccessNuevoSaldo" style="color: #15803d; font-size: 1.05rem;">₡0</strong>
</div>
</div>
<button type="button" class="btn-sinpe-action btn-sinpe-success" onclick="closeSinpeModal()">
<span>Aceptar y Continuar</span>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
<!-- 3. ESTADO: PENDIENTE DE REVISIÓN COMERCIO (Timeout / sin notificación bancaria) -->
<div id="modalSinpeStatePending" style="display: none;">
<div class="sinpe-icon-badge pending">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#d97706" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<polyline points="12 6 12 12 16 14"/>
</svg>
</div>
<h3 style="margin: 14px 0 4px 0; font-size: 1.25rem; font-weight: 900; color: #b45309;">Solicitud en Revisión</h3>
<p style="font-size: 0.85rem; color: #475569; margin: 0 0 14px 0; line-height: 1.45;">
Aún no ingresó la confirmación de tu banco. Tu solicitud de recarga por <strong>₡<span id="modalSinpePendingMonto">0</span></strong> quedó registrada para que el comercio la valide.
</p>
<div style="background: #fffbeb; border: 1.5px solid #fde68a; border-radius: 12px; padding: 12px; margin-bottom: 16px; text-align: left; font-size: 0.78rem; color: #92400e; line-height: 1.45;">
<div style="font-weight: 800; display: flex; align-items: center; gap: 5px; margin-bottom: 4px;">
<span>⚡ Acreditación Automática:</span>
</div>
Si la notificación del banco entra en los próximos minutos, el sistema la acreditará de forma automática sin que tengas que hacer nada más.
</div>
<button type="button" class="btn-sinpe-action btn-sinpe-pending" onclick="closeSinpeModal()">
<span>Entendido</span>
</button>
</div>
<!-- 4. ESTADO: ERROR / INVÁLIDO / REPETIDO -->
<div id="modalSinpeStateError" style="display: none;">
<div class="sinpe-icon-badge error">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="12"/>
<line x1="12" y1="16" x2="12.01" y2="16"/>
</svg>
</div>
<h3 id="modalSinpeErrorTitle" style="margin: 14px 0 4px 0; font-size: 1.22rem; font-weight: 900; color: #b91c1c;">No se pudo validar</h3>
<p id="modalSinpeErrorMessage" style="font-size: 0.86rem; color: #475569; margin: 0 0 16px 0; line-height: 1.45;">
Ocurrió un inconveniente al validar la recarga.
</p>
<button type="button" class="btn-sinpe-action btn-sinpe-error" onclick="closeSinpeModal()">
<span>Entendido</span>
</button>
</div>
</div>
</div>
<!-- BARRA DE NAVEGACIÓN INFERIOR PWA (MÓVILES) -->
<nav class="pwa-bottom-nav" id="pwaBottomNav" style="display: none;">
<button class="pwa-nav-item active" id="pwaNavMenu" onclick="pwaNavigateTo('menu')">
@@ -2383,6 +2567,6 @@
<script src="/js/sounds.js?v=9.6"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/food-icons.js?v=1.1"></script>
<script src="/js/app.js?v=10.2"></script>
<script src="/js/app.js?v=10.3"></script>
</body>
</html>
+351 -19
View File
@@ -2546,6 +2546,7 @@ function openParentSubView(viewKey) {
}
if (viewKey === 'sinpe' && currentParentChild) {
obtenerNuevoCodigoSinpe();
loadParentSinpeRequests(currentParentChild.id);
} else if (viewKey === 'historial' && currentParentChild) {
loadActiveChildHistory(currentParentChild.id);
@@ -2684,63 +2685,392 @@ async function loadActiveChildHistory(studentId) {
}
}
let currentSinpeCode = '';
function setParentSinpeMonto(monto) {
const input = document.getElementById('inputParentSinpeMonto');
if (input) {
input.value = monto;
input.focus();
}
if (window.sounds) window.sounds.playTap();
}
async function obtenerNuevoCodigoSinpe() {
const display = document.getElementById('parentSinpeCodigoDisplay');
const statusMsg = document.getElementById('parentSinpeStatusMsg');
if (statusMsg) statusMsg.style.display = 'none';
try {
const studentId = currentParentChild ? currentParentChild.id : null;
const res = await fetch('/api/sinpe/generar-codigo', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ estudiante_id: studentId })
});
const data = await res.json();
if (data.success && data.codigo) {
currentSinpeCode = data.codigo;
if (display) display.textContent = data.codigo;
if (data.telefono_sinpe) {
const telEl = document.getElementById('parentSinpeNumero');
if (telEl) telEl.textContent = data.telefono_sinpe;
}
if (data.titular_sinpe) {
const titEl = document.getElementById('parentSinpeTitular');
if (titEl) titEl.textContent = data.titular_sinpe;
}
if (data.escuela_nombre) {
const escEl = document.getElementById('parentSinpeEscuelaNombre');
if (escEl) escEl.textContent = data.escuela_nombre;
}
}
} catch (err) {
console.error('Error generando código SINPE:', err);
if (!currentSinpeCode && display) {
currentSinpeCode = 'SIBO-' + Math.random().toString(36).substring(2, 6).toUpperCase();
display.textContent = currentSinpeCode;
}
}
}
function copiarCodigoSinpe() {
const code = currentSinpeCode || (document.getElementById('parentSinpeCodigoDisplay')?.textContent || '').trim();
if (!code || code.includes('CARGANDO')) return;
const btn = document.getElementById('btnCopiarCodigoSinpe');
const lbl = document.getElementById('lblCopiarCodigoSinpe');
const onCopiado = () => {
if (window.sounds) window.sounds.playTap();
if (lbl) lbl.textContent = '¡Copiado! ✓';
if (btn) btn.style.background = '#059669';
setTimeout(() => {
if (lbl) lbl.textContent = 'Copiar código';
if (btn) btn.style.background = '#16a34a';
}, 2200);
};
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(code).then(onCopiado).catch(() => {
fallbackCopyText(code, onCopiado);
});
} else {
fallbackCopyText(code, onCopiado);
}
}
function fallbackCopyText(text, cb) {
try {
const tempInput = document.createElement('input');
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
if (cb) cb();
} catch (e) {
console.warn('No se pudo copiar automáticamente:', e);
}
}
// Control del Modal de Validación SINPE Móvil
let sinpeProgressInterval = null;
let sinpeIsPolling = false;
function showSinpeModal(state, data = {}) {
const modal = document.getElementById('modalSinpeValidacion');
if (!modal) return;
const stateLoading = document.getElementById('modalSinpeStateLoading');
const stateSuccess = document.getElementById('modalSinpeStateSuccess');
const statePending = document.getElementById('modalSinpeStatePending');
const stateError = document.getElementById('modalSinpeStateError');
const btnCloseX = document.getElementById('modalSinpeBtnCloseX');
if (stateLoading) stateLoading.style.display = 'none';
if (stateSuccess) stateSuccess.style.display = 'none';
if (statePending) statePending.style.display = 'none';
if (stateError) stateError.style.display = 'none';
if (state === 'loading') {
if (stateLoading) stateLoading.style.display = 'block';
if (btnCloseX) btnCloseX.style.display = 'none'; // No permitir cerrar en sondeo crítico
const sumChild = document.getElementById('modalSinpeSummaryChild');
const sumMonto = document.getElementById('modalSinpeSummaryMonto');
const sumCod = document.getElementById('modalSinpeSummaryCodigo');
const stepText = document.getElementById('modalSinpeStepText');
const timerText = document.getElementById('modalSinpeTimerText');
const bar = document.getElementById('modalSinpeProgressBar');
if (sumChild) sumChild.textContent = data.studentName || '-';
if (sumMonto) sumMonto.textContent = `₡${(data.monto || 0).toLocaleString('es-CR')}`;
if (sumCod) sumCod.textContent = data.codigo || '-';
if (stepText) stepText.textContent = 'Buscando comprobante bancario...';
if (timerText) timerText.textContent = '18s';
if (bar) bar.style.width = '0%';
} else if (state === 'success') {
if (stateSuccess) stateSuccess.style.display = 'block';
if (btnCloseX) btnCloseX.style.display = 'flex';
const sMonto = document.getElementById('modalSinpeSuccessMonto');
const sChild = document.getElementById('modalSinpeSuccessChild');
const sBanco = document.getElementById('modalSinpeSuccessBanco');
const sComp = document.getElementById('modalSinpeSuccessComp');
const sNuevo = document.getElementById('modalSinpeSuccessNuevoSaldo');
if (sMonto) sMonto.textContent = `₡${(data.monto || 0).toLocaleString('es-CR')}`;
if (sChild) sChild.textContent = data.studentName || '-';
if (sBanco) sBanco.textContent = data.banco || 'Bancario';
if (sComp) sComp.textContent = data.comprobante || data.codigo || '-';
if (sNuevo) sNuevo.textContent = `₡${(data.nuevoSaldo || 0).toLocaleString('es-CR')}`;
} else if (state === 'pending') {
if (statePending) statePending.style.display = 'block';
if (btnCloseX) btnCloseX.style.display = 'flex';
const pMonto = document.getElementById('modalSinpePendingMonto');
if (pMonto) pMonto.textContent = (data.monto || 0).toLocaleString('es-CR');
} else if (state === 'error') {
if (stateError) stateError.style.display = 'block';
if (btnCloseX) btnCloseX.style.display = 'flex';
const eTitle = document.getElementById('modalSinpeErrorTitle');
const eMsg = document.getElementById('modalSinpeErrorMessage');
if (eTitle) eTitle.textContent = data.title || 'No se pudo validar';
if (eMsg) eMsg.textContent = data.message || 'Ocurrió un error al procesar el SINPE.';
}
modal.style.display = 'flex';
}
function closeSinpeModal() {
if (sinpeIsPolling) {
sinpeIsPolling = false;
clearInterval(sinpeProgressInterval);
}
const modal = document.getElementById('modalSinpeValidacion');
if (modal) modal.style.display = 'none';
}
function handleSinpeBackdropClick(event) {
// Si está validando activamente, no cerramos por clic accidental en el fondo
if (sinpeIsPolling) return;
closeSinpeModal();
}
async function executeParentSinpeRecharge() {
if (!currentParentChild) {
alert('Selecciona primero al estudiante a quien deseas recargarle.');
showSinpeModal('error', {
title: 'Estudiante no seleccionado',
message: 'Por favor, selecciona primero al estudiante a quien deseas realizarle la recarga.'
});
return;
}
const inputMonto = document.getElementById('inputParentSinpeMonto');
const inputComp = document.getElementById('inputParentSinpeComprobante');
const btn = document.getElementById('btnParentValidarSinpe');
const statusMsg = document.getElementById('parentSinpeStatusMsg');
const monto = parseInt(inputMonto ? inputMonto.value : 0, 10);
const comprobante = inputComp ? inputComp.value.trim() : '';
const codigo = currentSinpeCode || (document.getElementById('parentSinpeCodigoDisplay')?.textContent || '').trim();
if (isNaN(monto) || monto <= 0) {
alert('Ingresa un monto válido mayor a ₡0 para recargar.');
showSinpeModal('error', {
title: 'Monto requerido',
message: 'Ingresa un monto válido mayor a ₡0 para procesar tu recarga SINPE.'
});
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 {
if (statusMsg) statusMsg.style.display = 'none';
if (btn) {
btn.disabled = true;
btn.innerHTML = '<span>Verificando...</span>';
btn.innerHTML = `
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="animation: sinpeSpin 1s linear infinite;"><circle cx="12" cy="12" r="10" stroke-opacity="0.25"/><path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round"/></svg>
<span>Validando SINPE...</span>
`;
}
const res = await fetch('/api/sinpe/solicitar', {
// Abrir modal con estado LOADING (sin alertas intrusivas)
showSinpeModal('loading', {
studentName: currentParentChild.nombre_completo,
monto: monto,
codigo: codigo
});
const totalDurationMs = 18000; // 18 segundos de sondeo visual
const pollIntervalMs = 3000; // Consulta cada 3 segundos
const startTime = Date.now();
sinpeIsPolling = true;
const bar = document.getElementById('modalSinpeProgressBar');
const timerText = document.getElementById('modalSinpeTimerText');
const stepText = document.getElementById('modalSinpeStepText');
clearInterval(sinpeProgressInterval);
sinpeProgressInterval = setInterval(() => {
if (!sinpeIsPolling) {
clearInterval(sinpeProgressInterval);
return;
}
const elapsed = Date.now() - startTime;
const progress = Math.min(100, Math.round((elapsed / totalDurationMs) * 100));
const remainingSecs = Math.max(0, Math.ceil((totalDurationMs - elapsed) / 1000));
if (bar) bar.style.width = `${progress}%`;
if (timerText) timerText.textContent = `${remainingSecs}s`;
if (stepText) {
if (elapsed < 4500) {
stepText.textContent = 'Buscando comprobante bancario...';
} else if (elapsed < 9000) {
stepText.textContent = 'Sondeando transferencias SINPE entrantes...';
} else if (elapsed < 13500) {
stepText.textContent = 'Esperando confirmación digital del banco...';
} else {
stepText.textContent = 'Verificación bancaria final...';
}
}
}, 100);
try {
let verifiedData = null;
let definitiveError = null;
const maxIntentos = 6;
for (let intento = 1; intento <= maxIntentos; intento++) {
if (!sinpeIsPolling) break;
try {
const res = await fetch('/api/sinpe/validar', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
estudiante_id: currentParentChild.id,
padre_usuario_id: currentUser ? currentUser.id : null,
monto,
comprobante,
notas: `Portal de Padres - ${currentUser ? currentUser.nombre : 'Encargado'}`
codigo,
comprobante: comprobante || null
})
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
const data = await res.json();
// 1. Pago Verificado con éxito
if (data.verificado && data.success) {
verifiedData = data;
break;
}
// 2. Error definitivo (ej. comprobante repetido o monto inválido)
if (data.error && !data.retry) {
definitiveError = data;
break;
}
} catch (pollErr) {
console.warn(`[SINPE Polling intento ${intento}]`, pollErr);
}
if (intento < maxIntentos && sinpeIsPolling) {
await new Promise(r => setTimeout(r, pollIntervalMs));
}
}
sinpeIsPolling = false;
clearInterval(sinpeProgressInterval);
// ============================================
// CASO 1: VERIFICADO CON ÉXITO
// ============================================
if (verifiedData && verifiedData.verificado) {
if (window.sounds) window.sounds.playCoin();
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.`);
const nuevoSaldo = typeof verifiedData.saldo_nuevo === 'number'
? verifiedData.saldo_nuevo
: (currentParentChild.saldo_colones + monto);
currentParentChild.saldo_colones = nuevoSaldo;
renderActiveChildDetails(currentParentChild);
if (inputMonto) inputMonto.value = '';
if (inputComp) inputComp.value = '';
showSinpeModal('success', {
studentName: currentParentChild.nombre_completo,
monto: monto,
banco: verifiedData.banco || 'Bancario',
comprobante: verifiedData.comprobante || verifiedData.codigo || codigo,
codigo: codigo,
nuevoSaldo: nuevoSaldo
});
await loadParentSinpeRequests(currentParentChild.id);
} catch (err) {
obtenerNuevoCodigoSinpe();
return;
}
// ============================================
// CASO 2: ERROR DEFINITIVO (REPETIDO O INVÁLIDO)
// ============================================
if (definitiveError) {
if (window.sounds) window.sounds.playError();
alert(`Error al enviar solicitud SINPE: ${err.message}`);
showSinpeModal('error', {
title: 'Comprobante no válido',
message: definitiveError.message || definitiveError.error || 'El comprobante ya fue utilizado o los datos no corresponden a la transferencia.'
});
return;
}
// ============================================
// CASO 3: BANCO AÚN NO RESPONDIÓ (REGISTRO AUTOMÁTICO PARA REVISIÓN)
// ============================================
if (window.sounds) window.sounds.playTap();
try {
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: comprobante || `SINPE-${codigo}`,
codigo_detalle: codigo,
notas: `Portal de Padres - Código: ${codigo}`
})
});
} catch (solErr) {
console.warn('Error al registrar solicitud:', solErr);
}
if (inputMonto) inputMonto.value = '';
if (inputComp) inputComp.value = '';
showSinpeModal('pending', {
studentName: currentParentChild.nombre_completo,
monto: monto,
codigo: codigo
});
await loadParentSinpeRequests(currentParentChild.id);
obtenerNuevoCodigoSinpe();
} catch (err) {
sinpeIsPolling = false;
clearInterval(sinpeProgressInterval);
if (window.sounds) window.sounds.playError();
showSinpeModal('error', {
title: 'Error de conexión',
message: `No se pudo conectar con el servidor: ${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>`;
btn.innerHTML = `
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" 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 id="btnParentValidarSinpeText">Validar SINPE</span>
`;
}
}
}
@@ -2779,10 +3109,12 @@ async function loadParentSinpeRequests(studentId) {
badgeText = '❌ Rechazado';
}
const refLabel = s.codigo_detalle ? `Cód: ${s.codigo_detalle}` : `Comp: #${s.comprobante_sinpe}`;
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-weight: 800; color: #0f172a;">₡${s.monto_colones.toLocaleString('es-CR')} <span style="font-weight: 600; color: #166534; font-family: monospace;">(${refLabel})</span></div>
<div style="font-size: 0.68rem; color: #94a3b8;">${fecha}</div>
</div>
<div>