Add Beneficios
This commit is contained in:
@@ -10,6 +10,9 @@
|
||||
<ion-segment-button value="manual">
|
||||
<ion-label>Manual</ion-label>
|
||||
</ion-segment-button>
|
||||
<ion-segment-button value="benefits">
|
||||
<ion-label>Beneficios</ion-label>
|
||||
</ion-segment-button>
|
||||
<ion-segment-button value="privacy">
|
||||
<ion-label>Privacidad</ion-label>
|
||||
</ion-segment-button>
|
||||
@@ -30,9 +33,11 @@
|
||||
<div class="info-body">
|
||||
<section>
|
||||
<h3>1. Mi Cartelera (Horarios y Aulas)</h3>
|
||||
<p>Visualizá todas las materias organizadas por día. Usá la barra de búsqueda para filtrar rápido por nombre, aula o código.</p>
|
||||
<p>Visualizá todas las materias organizadas por día. Usá la barra de búsqueda para filtrar rápido por nombre,
|
||||
aula o código.</p>
|
||||
<ul>
|
||||
<li><strong>Favoritos:</strong> Toca la estrella ⭐ para activar notificaciones automáticas y recordatorios 30 min antes de clase.</li>
|
||||
<li><strong>Favoritos:</strong> Toca la estrella ⭐ para activar notificaciones automáticas y recordatorios 30
|
||||
min antes de clase.</li>
|
||||
<li><strong>Sincronización:</strong> Desliza hacia abajo para traer los últimos datos oficiales.</li>
|
||||
</ul>
|
||||
</section>
|
||||
@@ -41,24 +46,29 @@
|
||||
<h3>2. Mi Carrera (Seguimiento)</h3>
|
||||
<p>Accedé desde el botón inferior para ver tu plan de estudios.</p>
|
||||
<ul>
|
||||
<li><strong>Estados:</strong> Marcá materias como <em>Aprobadas</em> (Fucsia) o <em>En Curso</em> (Celeste).</li>
|
||||
<li><strong>Optativas:</strong> Elegí tus materias directamente desde el selector para completar tu progreso.</li>
|
||||
<li><strong>Estados:</strong> Marcá materias como <em>Aprobadas</em> (Fucsia) o <em>En Curso</em> (Celeste).
|
||||
</li>
|
||||
<li><strong>Optativas:</strong> Elegí tus materias directamente desde el selector para completar tu progreso.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>3. Agenda y Exámenes</h3>
|
||||
<p>En el menú de cada materia (`...`) podés agendar <strong>Parciales, Finales o TPs</strong>. Verás insignias de colores avisándote la proximidad.</p>
|
||||
<p>En el menú de cada materia (`...`) podés agendar <strong>Parciales, Finales o TPs</strong>. Verás insignias
|
||||
de colores avisándote la proximidad.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>4. Credencial Digital QR</h3>
|
||||
<p>Tocá el logo arriba a la izquierda para abrir tu credencial. La app subirá el brillo automáticamente para facilitar el escaneo.</p>
|
||||
<p>Tocá el logo arriba a la izquierda para abrir tu credencial. La app subirá el brillo automáticamente para
|
||||
facilitar el escaneo.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>5. Mantené tus datos seguros</h3>
|
||||
<p>Usa <strong>Perfil > Guardar Respaldo</strong> para exportar un archivo CSV. Si cambias de teléfono, podés restaurarlo desde el mismo lugar.</p>
|
||||
<p>Usa <strong>Perfil > Guardar Respaldo</strong> para exportar un archivo CSV. Si cambias de teléfono, podés
|
||||
restaurarlo desde el mismo lugar.</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
@@ -73,10 +83,12 @@
|
||||
|
||||
<div class="info-body">
|
||||
<h3>Sin Intermediarios</h3>
|
||||
<p>Aulas UNICABA no tiene servidores propios. Cada vez que sincronizás la cartelera o tu credencial, la conexión viaja directo de tu teléfono al servidor de la Universidad.</p>
|
||||
<p>Aulas UNICABA no tiene servidores propios. Cada vez que sincronizás la cartelera o tu credencial, la conexión
|
||||
viaja directo de tu teléfono al servidor de la Universidad.</p>
|
||||
|
||||
<h3>Tratamiento de Credenciales</h3>
|
||||
<p>Tus claves de Moodle o SIU Guaraní se guardan de forma encriptada en el almacenamiento seguro de tu dispositivo. Nunca salen de tu teléfono hacia terceros.</p>
|
||||
<p>Tus claves de Moodle o SIU Guaraní se guardan de forma encriptada en el almacenamiento seguro de tu
|
||||
dispositivo. Nunca salen de tu teléfono hacia terceros.</p>
|
||||
|
||||
<h3>Analíticas y Rastreos</h3>
|
||||
<p>No usamos Google Analytics ni SDKs de seguimiento. No hay publicidad. Cero telemetría invasiva.</p>
|
||||
@@ -87,4 +99,56 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</ion-content>
|
||||
<!-- VISTA: BENEFICIOS -->
|
||||
<div *ngIf="selectedSegment === 'benefits'" class="fade-in">
|
||||
<div class="logo-container ion-text-center">
|
||||
<ion-icon name="gift-outline" size="large" color="tertiary"></ion-icon>
|
||||
<h2>Guía de Beneficios</h2>
|
||||
<p class="subtitle">Aprovechá tu formación en UNICABA</p>
|
||||
</div>
|
||||
|
||||
<div class="info-body">
|
||||
<section class="benefit-section">
|
||||
<div class="benefit-header">
|
||||
<ion-icon name="bus" color="primary"></ion-icon>
|
||||
<h3>1. SOY Estudiante (Transporte)</h3>
|
||||
</div>
|
||||
<p>Obtené descuentos en pasajes de micro a todo el país a través del portal de <b>Central de Pasajes</b>.</p>
|
||||
<div class="steps-box">
|
||||
<h4>¿Cómo activarlo?</h4>
|
||||
<ol>
|
||||
<li>Entra a <b>Perfil</b> y generá tu <b>Certificado de Alumno Regular</b>.</li>
|
||||
<li>Ingresá a <a href="https://soyestudiante.com.ar/" target="_blank">soyestudiante.com.ar</a>.</li>
|
||||
<li>Subí el PDF que guardaste en tu teléfono.</li>
|
||||
<li>¡Listo! Tu DNI quedará habilitado para descuentos automáticos.</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="benefit-section">
|
||||
<div class="benefit-header">
|
||||
<ion-icon name="logo-google" color="danger"></ion-icon>
|
||||
<h3>2. Google Students (IA y Nube)</h3>
|
||||
</div>
|
||||
<p>Cargando la <b>Constancia de Alumno Regular</b> con tu cuenta personal te da acceso a herramientas
|
||||
profesionales.
|
||||
</p>
|
||||
<div class="steps-box">
|
||||
<h4>Beneficios incluidos:</h4>
|
||||
<ul>
|
||||
<li><strong>Google Gemini PRO:</strong> Bonificación por un año de IA avanzada.</li>
|
||||
<li><strong>Google Drive:</strong> Almacenamiento ampliado (hasta 1TB según vigencia).</li>
|
||||
<li><strong>Meet Premium:</strong> Reuniones sin límite de tiempo y grabación directa.</li>
|
||||
</ul>
|
||||
<p><small>* Para validar, usá tu mail institucional y subí el certificado si se solicita comprobante de
|
||||
cursada.</small></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="footer-info ion-text-center">
|
||||
<p><small>Los beneficios son gestionados por terceros y sujetos a sus términos y condiciones.</small></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</ion-content>
|
||||
@@ -70,6 +70,10 @@
|
||||
<span>DNI: {{ siuDni }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<ion-button expand="block" fill="outline" color="primary" (click)="generateCertificate()" class="btn-cert">
|
||||
<ion-icon name="document-text-outline" slot="start"></ion-icon>
|
||||
Certificado de Alumno Regular
|
||||
</ion-button>
|
||||
<ion-button expand="block" fill="clear" color="danger" (click)="logoutSiu()" class="btn-logout">
|
||||
<ion-icon name="log-out-outline" slot="start"></ion-icon>
|
||||
Cerrar sesión SIU
|
||||
@@ -167,6 +171,39 @@
|
||||
</ion-card-content>
|
||||
</ion-card>
|
||||
|
||||
<!-- Beneficios del Estudiante -->
|
||||
<div class="section-header ion-padding-horizontal">
|
||||
<h3>Beneficios del Estudiante</h3>
|
||||
<p>Aprovechá convenios exclusivos por ser parte de UNICABA.</p>
|
||||
</div>
|
||||
|
||||
<ion-row class="benefits-row">
|
||||
<ion-col size="6">
|
||||
<ion-card class="benefit-card" (click)="showBenefitDetail('soy')">
|
||||
<div class="benefit-icon-container soy">
|
||||
<ion-icon name="school-outline"></ion-icon>
|
||||
</div>
|
||||
<ion-card-content>
|
||||
<h4>SOY Estudiante</h4>
|
||||
<p>Descuentos en pasajes de micro.</p>
|
||||
<ion-badge color="success">Activo</ion-badge>
|
||||
</ion-card-content>
|
||||
</ion-card>
|
||||
</ion-col>
|
||||
<ion-col size="6">
|
||||
<ion-card class="benefit-card" (click)="showBenefitDetail('google')">
|
||||
<div class="benefit-icon-container google">
|
||||
<ion-icon name="logo-google" color="primary"></ion-icon>
|
||||
</div>
|
||||
<ion-card-content>
|
||||
<h4>Google Students</h4>
|
||||
<p>Gemini PRO & Drive 1TB.</p>
|
||||
<ion-badge color="tertiary">Bonificado</ion-badge>
|
||||
</ion-card-content>
|
||||
</ion-card>
|
||||
</ion-col>
|
||||
</ion-row>
|
||||
|
||||
|
||||
<div class="security-info ion-padding">
|
||||
<ion-icon name="lock-closed" color="medium"></ion-icon>
|
||||
|
||||
@@ -189,65 +189,100 @@
|
||||
}
|
||||
}
|
||||
|
||||
.info-section-container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
|
||||
|
||||
.section-title {
|
||||
.btn-cert {
|
||||
margin-top: 12px;
|
||||
--border-radius: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-top: 24px;
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
font-size: 1.1rem;
|
||||
color: var(--ion-color-dark);
|
||||
margin: 0 0 15px 0;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.5;
|
||||
color: var(--ion-color-medium);
|
||||
margin-bottom: 15px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
|
||||
ion-icon {
|
||||
font-size: 1.4rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
strong {
|
||||
color: var(--ion-color-dark);
|
||||
}
|
||||
}
|
||||
|
||||
.version-info {
|
||||
margin-top: 20px;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.05);
|
||||
padding-top: 15px;
|
||||
color: var(--ion-color-medium);
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: var(--ion-color-danger);
|
||||
font-size: 0.85rem;
|
||||
margin-top: 10px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
.benefits-row {
|
||||
padding: 0 8px;
|
||||
margin-top: -8px;
|
||||
}
|
||||
|
||||
.benefit-card {
|
||||
margin: 8px;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100% - 16px);
|
||||
transition: transform 0.2s;
|
||||
overflow: hidden;
|
||||
|
||||
&:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
.benefit-icon-container {
|
||||
height: 80px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&.soy {
|
||||
background: linear-gradient(135deg, #f0f7ff 0%, #e0e7ff 100%);
|
||||
ion-icon { font-size: 40px; color: #1a73e8; }
|
||||
}
|
||||
|
||||
&.google {
|
||||
background: linear-gradient(135deg, #fff5f5 0%, #ffe0e0 100%);
|
||||
ion-icon { font-size: 40px; }
|
||||
}
|
||||
}
|
||||
|
||||
ion-card-content {
|
||||
padding: 12px;
|
||||
text-align: center;
|
||||
|
||||
h4 {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
color: var(--ion-color-dark);
|
||||
}
|
||||
p {
|
||||
margin: 6px 0;
|
||||
font-size: 0.75rem;
|
||||
color: var(--ion-color-medium);
|
||||
line-height: 1.2;
|
||||
}
|
||||
ion-badge {
|
||||
font-size: 0.65rem;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.security-info {
|
||||
margin-top: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
gap: 10px;
|
||||
opacity: 0.7;
|
||||
|
||||
ion-icon {
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 0.8rem;
|
||||
margin: 0;
|
||||
@@ -255,3 +290,20 @@
|
||||
max-width: 280px;
|
||||
}
|
||||
}
|
||||
|
||||
:host ::ng-deep .benefit-alert {
|
||||
.alert-message {
|
||||
text-align: left;
|
||||
}
|
||||
.benefit-modal-content {
|
||||
b { color: var(--ion-color-primary); }
|
||||
ol {
|
||||
padding-left: 20px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
li {
|
||||
margin-bottom: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,6 +168,50 @@ export class PerfilPage implements OnInit, OnDestroy {
|
||||
await alert.present();
|
||||
}
|
||||
|
||||
// --- AUTOMATIZACIÓN DE CERTIFICADOS ---
|
||||
|
||||
async generateCertificate() {
|
||||
const creds = await this.authService.getSiuCredentials();
|
||||
if (!creds.dni || !creds.pass) {
|
||||
this.showToast('Debe estar conectado al SIU para generar el certificado', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const loader = await this.loadingCtrl.create({
|
||||
message: 'Gestionando Certificado en SIU Guaraní...<br><small>Esto puede demorar unos segundos</small>',
|
||||
spinner: 'crescent'
|
||||
});
|
||||
await loader.present();
|
||||
|
||||
try {
|
||||
const result = await this.siuService.downloadCertificate(creds.dni, creds.pass);
|
||||
await this.siuService.saveAndOpenFile(result.base64, result.filename);
|
||||
|
||||
this.showToast('¡Certificado generado y abierto!', 'success');
|
||||
await Haptics.impact({ style: ImpactStyle.Heavy }).catch(() => { });
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
const alert = await this.alertCtrl.create({
|
||||
header: 'Error de Certificado',
|
||||
message: `No se pudo automatizar la descarga: ${e.message || 'Error desconocido'}. Por favor, intentalo más tarde o desde el SIU web.`,
|
||||
buttons: ['Entendido']
|
||||
});
|
||||
await alert.present();
|
||||
} finally {
|
||||
await loader.dismiss();
|
||||
}
|
||||
}
|
||||
|
||||
async showBenefitDetail(type: 'soy' | 'google') {
|
||||
const modal = await this.modalCtrl.create({
|
||||
component: InfoModalComponent,
|
||||
componentProps: {
|
||||
selectedSegment: 'benefits'
|
||||
}
|
||||
});
|
||||
await modal.present();
|
||||
}
|
||||
|
||||
// --- NUEVAS FUNCIONES CONSOLIDADAS ---
|
||||
|
||||
async openInfo() {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
||||
import { Filesystem, Directory } from '@capacitor/filesystem';
|
||||
import { FileOpener } from '@capacitor-community/file-opener';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
@@ -9,7 +11,8 @@ export class SiuService {
|
||||
|
||||
async getAcademicHistory(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
||||
try {
|
||||
await this.loginSiu(dni, pass, carreraId);
|
||||
await this.authenticateSiu(dni, pass);
|
||||
await this.selectCareer(carreraId);
|
||||
|
||||
// 3. OBTENER PLAN DE ESTUDIO
|
||||
const resPlan: HttpResponse = await CapacitorHttp.get({
|
||||
@@ -36,7 +39,8 @@ export class SiuService {
|
||||
|
||||
async getInscripcionesActivas(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
||||
try {
|
||||
await this.loginSiu(dni, pass, carreraId);
|
||||
await this.authenticateSiu(dni, pass);
|
||||
await this.selectCareer(carreraId);
|
||||
|
||||
// OBTENER PÁGINA DE CURSADA
|
||||
const resCursada: HttpResponse = await CapacitorHttp.get({
|
||||
@@ -62,19 +66,189 @@ export class SiuService {
|
||||
}
|
||||
}
|
||||
|
||||
private async loginSiu(dni: string, pass: string, carreraId: string): Promise<void> {
|
||||
// 1. LOGIN POST
|
||||
private async authenticateSiu(dni: string, pass: string): Promise<void> {
|
||||
console.log('Autenticando en SIU...');
|
||||
const loginData = `usuario=${dni}&password=${pass}&login=Ingresar`;
|
||||
await CapacitorHttp.post({
|
||||
url: `${this.BASE_URL}/acceso?auth=form`,
|
||||
data: loginData,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
|
||||
});
|
||||
}
|
||||
|
||||
// 2. CAMBIO DE CARRERA
|
||||
private async selectCareer(carreraId: string): Promise<void> {
|
||||
console.log('Seleccionando carrera:', carreraId);
|
||||
await CapacitorHttp.get({
|
||||
url: `${this.BASE_URL}/acceso/cambiar_carrera?id=${carreraId}&op=inicio_alumno`,
|
||||
});
|
||||
// Hit inicio_alumno to ensure context is established
|
||||
await CapacitorHttp.get({
|
||||
url: `${this.BASE_URL}/inicio_alumno`,
|
||||
});
|
||||
}
|
||||
|
||||
private extractTobaContent(html: string, pageletId: string = 'pagelet'): string {
|
||||
const regexes = [
|
||||
/kernel\.renderer\.on_arrival\((\{.*?\})\);/gs,
|
||||
/on_arrival\((\{.*?\})\);/gs
|
||||
];
|
||||
|
||||
for (const regex of regexes) {
|
||||
let match;
|
||||
// Reset regex index for global searches
|
||||
regex.lastIndex = 0;
|
||||
while ((match = regex.exec(html)) !== null) {
|
||||
try {
|
||||
const jsonData = JSON.parse(match[1]);
|
||||
if (jsonData.id === pageletId || jsonData.info?.id === pageletId) {
|
||||
return jsonData.content || '';
|
||||
}
|
||||
} catch (e) { continue; }
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
async downloadCertificate(dni: string, pass: string): Promise<{ base64: string, filename: string }> {
|
||||
console.log('Iniciando descarga de certificado para:', dni);
|
||||
try {
|
||||
await this.authenticateSiu(dni, pass);
|
||||
await this.selectCareer('30');
|
||||
console.log('Login y selección de carrera (ID 30) listos');
|
||||
|
||||
// 1. VALIDAR SI EXISTE UNO VIGENTE (< 30 DÍAS)
|
||||
const resSolicitudes: HttpResponse = await CapacitorHttp.get({
|
||||
url: `${this.BASE_URL}/solicitudes`,
|
||||
});
|
||||
console.log('Página de solicitudes obtenida');
|
||||
|
||||
const contentHtmlSolicitudes = this.extractTobaContent(resSolicitudes.data, 'pagelet');
|
||||
if (contentHtmlSolicitudes) {
|
||||
const existingCert = this.findValidCertificate(contentHtmlSolicitudes);
|
||||
if (existingCert) {
|
||||
console.log('Certificado vigente encontrado:', existingCert.filename);
|
||||
return await this.downloadFile(existingCert.url, existingCert.filename);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. GENERAR NUEVA SOLICITUD (HEADLESS)
|
||||
console.log('No hay certificado vigente o no se pudo leer la tabla. Intentando generar uno nuevo...');
|
||||
const resGestion: HttpResponse = await CapacitorHttp.get({
|
||||
url: `${this.BASE_URL}/solicitudes/solicitud_gestion`,
|
||||
});
|
||||
|
||||
const contentHtmlGestion = this.extractTobaContent(resGestion.data, 'pagelet');
|
||||
if (!contentHtmlGestion) {
|
||||
console.error('HTML completo de gestión no contiene on_arrival de pagelet. Muestra:', resGestion.data.substring(0, 1000));
|
||||
throw new Error('No se pudo localizar el generador (content missing)');
|
||||
}
|
||||
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(contentHtmlGestion, 'text/html');
|
||||
const iframe = doc.querySelector('iframe#frameSolicitud') as HTMLIFrameElement;
|
||||
let iframeSrc = iframe?.getAttribute('src');
|
||||
|
||||
if (!iframeSrc) {
|
||||
throw new Error('No se pudo localizar el generador (iframe src missing)');
|
||||
}
|
||||
|
||||
console.log('Iframe localizado, src:', iframeSrc);
|
||||
|
||||
// Asegurar que la URL del iframe es completa
|
||||
if (!iframeSrc.startsWith('http')) {
|
||||
const baseUrlParsed = new URL(this.BASE_URL);
|
||||
iframeSrc = `${baseUrlParsed.origin}${iframeSrc.startsWith('/') ? '' : '/'}${iframeSrc}`;
|
||||
}
|
||||
|
||||
// Trigger the print event via URL parameters
|
||||
const printUrl = iframeSrc.includes('?')
|
||||
? `${iframeSrc}&toba_ei_notificar=imprimir`
|
||||
: `${iframeSrc}?toba_ei_notificar=imprimir`;
|
||||
|
||||
console.log('Solicitando generación de PDF:', printUrl);
|
||||
return await this.downloadFile(printUrl, `Certificado_Alumno_Regular_${new Date().getTime()}.pdf`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error detallado en SIU Certificate:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private findValidCertificate(html: string): { url: string, filename: string } | null {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
const rows = Array.from(doc.querySelectorAll('tr'));
|
||||
|
||||
for (const row of rows) {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
if (cells.length >= 3) {
|
||||
const tipo = cells[0].textContent?.trim().toLowerCase() || '';
|
||||
const presentarA = cells[2].textContent?.trim().toLowerCase() || '';
|
||||
|
||||
// Identificar constancia de alumno regular
|
||||
if (tipo.includes('alumno regular')) {
|
||||
const fechaStr = cells[1].textContent?.trim() || '';
|
||||
console.log(`Revisando: ${tipo} | Para: ${presentarA} | Fecha: ${fechaStr}`);
|
||||
|
||||
if (this.isWithin30Days(fechaStr)) {
|
||||
// El usuario indico que si dice "Quien corresponda" o similares (como "Google LLC") sirve.
|
||||
// Solo descartamos si es para un destinatario muy especifico que no sea el solicitado.
|
||||
const downloadLink = row.querySelector('a.descargar_cert, a[href*="descargar_comprobante"]') as HTMLAnchorElement;
|
||||
if (downloadLink) {
|
||||
return {
|
||||
url: downloadLink.getAttribute('href') || '',
|
||||
filename: `Certificado_SIU_${presentarA.replace(/\s+/g, '_')}_${fechaStr.replace(/\//g, '-')}.pdf`
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private isWithin30Days(fechaStr: string): boolean {
|
||||
// Formato esperado: DD/MM/YYYY
|
||||
const parts = fechaStr.split('/');
|
||||
if (parts.length !== 3) return false;
|
||||
const date = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
|
||||
const diff = new Date().getTime() - date.getTime();
|
||||
const days = diff / (1000 * 60 * 60 * 24);
|
||||
return days < 30;
|
||||
}
|
||||
|
||||
private async downloadFile(url: string, filename: string): Promise<{ base64: string, filename: string }> {
|
||||
// Si la URL es relativa, completarla
|
||||
const fullUrl = url.startsWith('http') ? url : `${this.BASE_URL}/${url.startsWith('/') ? url.substring(1) : url}`;
|
||||
|
||||
const response: HttpResponse = await CapacitorHttp.get({
|
||||
url: fullUrl,
|
||||
responseType: 'blob'
|
||||
});
|
||||
|
||||
return {
|
||||
base64: response.data, // CapacitorHttp con responseType blob devuelve base64 string
|
||||
filename
|
||||
};
|
||||
}
|
||||
|
||||
async saveAndOpenFile(base64Data: string, filename: string): Promise<void> {
|
||||
try {
|
||||
const savedFile = await Filesystem.writeFile({
|
||||
path: `Certificados/${filename}`,
|
||||
data: base64Data,
|
||||
directory: Directory.Documents,
|
||||
recursive: true
|
||||
});
|
||||
|
||||
await FileOpener.open({
|
||||
filePath: savedFile.uri,
|
||||
contentType: 'application/pdf',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error saving or opening file:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private parseInscripcionesActivasHtml(html: string): any[] {
|
||||
|
||||
Reference in New Issue
Block a user