feat: sincronización avanzada SIU por código ASIG, perfil con foto/nombre de Moodle y refinamiento visual violeta
This commit is contained in:
@@ -6,6 +6,10 @@ const routes: Routes = [
|
|||||||
path: 'home',
|
path: 'home',
|
||||||
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
|
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'perfil',
|
||||||
|
loadChildren: () => import('./perfil/perfil.module').then( m => m.PerfilPageModule)
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
redirectTo: 'home',
|
redirectTo: 'home',
|
||||||
|
|||||||
@@ -12,7 +12,12 @@
|
|||||||
<!-- Loading State -->
|
<!-- Loading State -->
|
||||||
<div class="state-container" *ngIf="state === 'loading'">
|
<div class="state-container" *ngIf="state === 'loading'">
|
||||||
<ion-spinner name="crescent" color="primary"></ion-spinner>
|
<ion-spinner name="crescent" color="primary"></ion-spinner>
|
||||||
<p class="loading-text">Conectando con el campus y generando credencial...</p>
|
<div class="loading-wrapper ion-text-center">
|
||||||
|
<p class="loading-text">{{ loadingStatus }}</p>
|
||||||
|
<p class="loading-subtext" style="font-size: 0.8rem; color: var(--ion-color-medium); margin-top: 5px;">
|
||||||
|
Por favor no cierres la aplicación
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Error State -->
|
<!-- Error State -->
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { CommonModule } from '@angular/common';
|
|||||||
import { IonicModule, ModalController, ToastController } from '@ionic/angular';
|
import { IonicModule, ModalController, ToastController } from '@ionic/angular';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { CredencialService } from '../../services/credencial.service';
|
import { CredencialService } from '../../services/credencial.service';
|
||||||
|
import { AuthService } from '../../services/auth.service';
|
||||||
import { ScreenBrightness } from '@capacitor-community/screen-brightness';
|
import { ScreenBrightness } from '@capacitor-community/screen-brightness';
|
||||||
|
|
||||||
type CredencialState = 'loading' | 'login' | 'success' | 'error';
|
type CredencialState = 'loading' | 'login' | 'success' | 'error';
|
||||||
@@ -18,6 +19,7 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
state: CredencialState = 'loading';
|
state: CredencialState = 'loading';
|
||||||
errorMessage: string = '';
|
errorMessage: string = '';
|
||||||
|
loadingStatus: string = 'Iniciando...';
|
||||||
|
|
||||||
dni: string = '';
|
dni: string = '';
|
||||||
password: string = '';
|
password: string = '';
|
||||||
@@ -29,6 +31,7 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
constructor(
|
constructor(
|
||||||
private modalCtrl: ModalController,
|
private modalCtrl: ModalController,
|
||||||
private credencialService: CredencialService,
|
private credencialService: CredencialService,
|
||||||
|
private authService: AuthService,
|
||||||
private toastCtrl: ToastController
|
private toastCtrl: ToastController
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
@@ -45,12 +48,13 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
ngOnDestroy() {
|
ngOnDestroy() {
|
||||||
if (this.originalBrightness !== null) {
|
if (this.originalBrightness !== null) {
|
||||||
ScreenBrightness.setBrightness({ brightness: this.originalBrightness }).catch(() => {});
|
ScreenBrightness.setBrightness({ brightness: this.originalBrightness }).catch(() => { });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async checkExistingCredential() {
|
async checkExistingCredential() {
|
||||||
this.state = 'loading';
|
this.state = 'loading';
|
||||||
|
this.loadingStatus = 'Comprobando caché...';
|
||||||
try {
|
try {
|
||||||
// 1. Try to load cached image first for instant load
|
// 1. Try to load cached image first for instant load
|
||||||
const cachedImg = await this.credencialService.getCachedImage();
|
const cachedImg = await this.credencialService.getCachedImage();
|
||||||
@@ -59,14 +63,14 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
this.state = 'success';
|
this.state = 'success';
|
||||||
|
|
||||||
// Even if we show cache, load credentials to fields in background in case they want to update
|
// Even if we show cache, load credentials to fields in background in case they want to update
|
||||||
const stored = await this.credencialService.getStoredCredentials();
|
const stored = await this.authService.getMoodleCredentials();
|
||||||
this.dni = stored.dni || '';
|
this.dni = stored.dni || '';
|
||||||
this.password = stored.pass || '';
|
this.password = stored.pass || '';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. If no cached image, check for credentials to auto-login
|
// 2. If no cached image, check for credentials to auto-login
|
||||||
const stored = await this.credencialService.getStoredCredentials();
|
const stored = await this.authService.getMoodleCredentials();
|
||||||
if (stored.dni && stored.pass) {
|
if (stored.dni && stored.pass) {
|
||||||
this.dni = stored.dni;
|
this.dni = stored.dni;
|
||||||
this.password = stored.pass;
|
this.password = stored.pass;
|
||||||
@@ -86,7 +90,11 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.state = 'loading';
|
this.state = 'loading';
|
||||||
try {
|
try {
|
||||||
this.credentialImage = await this.credencialService.generateCredential(this.dni, this.password);
|
this.credentialImage = await this.credencialService.generateCredential(
|
||||||
|
this.dni,
|
||||||
|
this.password,
|
||||||
|
(status) => { this.loadingStatus = status; }
|
||||||
|
);
|
||||||
this.state = 'success';
|
this.state = 'success';
|
||||||
|
|
||||||
if (forceUpdate) {
|
if (forceUpdate) {
|
||||||
@@ -105,7 +113,7 @@ export class CredencialModalComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async logout() {
|
async logout() {
|
||||||
await this.credencialService.clearAll();
|
await this.authService.logoutMoodle();
|
||||||
this.dni = '';
|
this.dni = '';
|
||||||
this.password = '';
|
this.password = '';
|
||||||
this.credentialImage = '';
|
this.credentialImage = '';
|
||||||
|
|||||||
+13
-54
@@ -1,15 +1,17 @@
|
|||||||
<ion-header [translucent]="true">
|
<ion-header [translucent]="true">
|
||||||
<ion-toolbar color="secondary">
|
<ion-toolbar color="secondary">
|
||||||
<div class="header-content">
|
<div class="header-content">
|
||||||
<img src="assets/logo_unicaba_mini.png" class="header-logo" alt="UNICABA Logo" (click)="openCredencial()"
|
<img src="assets/logo_unicaba_mini.png" class="header-logo" alt="UNICABA Logo">
|
||||||
style="cursor: pointer;" title="Ver Credencial Digital">
|
|
||||||
<ion-title class="ion-text-center">
|
<ion-title class="ion-text-center">
|
||||||
Cartelera de Aulas
|
UNICABA
|
||||||
</ion-title>
|
</ion-title>
|
||||||
<ion-buttons slot="end">
|
<ion-buttons slot="end">
|
||||||
<ion-button *ngIf="viewMode === 'favoritos'" (click)="importarRespaldoManual()" title="Importar Respaldo">
|
<ion-button *ngIf="viewMode === 'favoritos'" (click)="importarRespaldoManual()" title="Importar Respaldo">
|
||||||
<ion-icon slot="icon-only" name="cloud-download-outline"></ion-icon>
|
<ion-icon slot="icon-only" name="cloud-download-outline"></ion-icon>
|
||||||
</ion-button>
|
</ion-button>
|
||||||
|
<ion-button (click)="goToPerfil()" title="Mi Perfil">
|
||||||
|
<ion-icon slot="icon-only" name="person-circle-outline"></ion-icon>
|
||||||
|
</ion-button>
|
||||||
<ion-button (click)="isInfoModalOpen = true">
|
<ion-button (click)="isInfoModalOpen = true">
|
||||||
<ion-icon slot="icon-only" name="information-circle-outline"></ion-icon>
|
<ion-icon slot="icon-only" name="information-circle-outline"></ion-icon>
|
||||||
</ion-button>
|
</ion-button>
|
||||||
@@ -207,12 +209,10 @@
|
|||||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
|
||||||
<span class="selector-title" style="margin: 0;">Plan de Estudios / Recorrido</span>
|
<span class="selector-title" style="margin: 0;">Plan de Estudios / Recorrido</span>
|
||||||
<div style="display: flex; gap: 8px;">
|
<div style="display: flex; gap: 8px;">
|
||||||
<ion-button fill="outline" color="primary" size="small" (click)="forzarRespaldo()" style="margin: 0;" title="Guardar Manualmente" class="header-btn">
|
<ion-button fill="outline" color="primary" size="small" (click)="forzarRespaldo()" style="margin: 0;"
|
||||||
|
title="Guardar Manualmente" class="header-btn">
|
||||||
<ion-icon name="save-outline" slot="icon-only"></ion-icon>
|
<ion-icon name="save-outline" slot="icon-only"></ion-icon>
|
||||||
</ion-button>
|
</ion-button>
|
||||||
<ion-button fill="outline" [color]="siuMaterias && siuMaterias.length > 0 ? 'success' : 'tertiary'" size="small" (click)="openSiuModal()" style="margin: 0;" title="Conectar con SIU Guaraní" class="header-btn">
|
|
||||||
<ion-icon name="school-outline" slot="icon-only"></ion-icon>
|
|
||||||
</ion-button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p class="selector-desc">Selecciona tu carrera para guardar tu avance y ver el recorrido sugerido, toca materias
|
<p class="selector-desc">Selecciona tu carrera para guardar tu avance y ver el recorrido sugerido, toca materias
|
||||||
@@ -244,7 +244,8 @@
|
|||||||
[class.encurso]="isEnCurso(row.c1.name)" [class.optativa-cell]="row.c1.isOptativa"
|
[class.encurso]="isEnCurso(row.c1.name)" [class.optativa-cell]="row.c1.isOptativa"
|
||||||
(click)="handleCellClick(row.c1)">
|
(click)="handleCellClick(row.c1)">
|
||||||
<span class="m-name">{{ abreviarMateria(row.c1.name) }}</span>
|
<span class="m-name">{{ abreviarMateria(row.c1.name) }}</span>
|
||||||
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c1.name) as siuMat" [ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c1.name) as siuMat"
|
||||||
|
[ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
||||||
{{ getSiuBadgeText(siuMat) }}
|
{{ getSiuBadgeText(siuMat) }}
|
||||||
</ion-badge>
|
</ion-badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -254,7 +255,8 @@
|
|||||||
[class.encurso]="isEnCurso(row.c2.name)" [class.optativa-cell]="row.c2.isOptativa"
|
[class.encurso]="isEnCurso(row.c2.name)" [class.optativa-cell]="row.c2.isOptativa"
|
||||||
(click)="handleCellClick(row.c2)">
|
(click)="handleCellClick(row.c2)">
|
||||||
<span class="m-name">{{ abreviarMateria(row.c2.name) }}</span>
|
<span class="m-name">{{ abreviarMateria(row.c2.name) }}</span>
|
||||||
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c2.name) as siuMat" [ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c2.name) as siuMat"
|
||||||
|
[ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
||||||
{{ getSiuBadgeText(siuMat) }}
|
{{ getSiuBadgeText(siuMat) }}
|
||||||
</ion-badge>
|
</ion-badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -264,7 +266,8 @@
|
|||||||
[class.encurso]="isEnCurso(row.c3.name)" [class.optativa-cell]="row.c3.isOptativa"
|
[class.encurso]="isEnCurso(row.c3.name)" [class.optativa-cell]="row.c3.isOptativa"
|
||||||
(click)="handleCellClick(row.c3)">
|
(click)="handleCellClick(row.c3)">
|
||||||
<span class="m-name">{{ abreviarMateria(row.c3.name) }}</span>
|
<span class="m-name">{{ abreviarMateria(row.c3.name) }}</span>
|
||||||
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c3.name) as siuMat" [ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
<ion-badge *ngIf="getSiuMateriaParaCelda(row.c3.name) as siuMat"
|
||||||
|
[ngClass]="'custom-badge-' + getNotaColor(siuMat.nota)" class="siu-cell-badge">
|
||||||
{{ getSiuBadgeText(siuMat) }}
|
{{ getSiuBadgeText(siuMat) }}
|
||||||
</ion-badge>
|
</ion-badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -276,50 +279,6 @@
|
|||||||
<!-- The SIU Guaraní list at the bottom was removed per user request -->
|
<!-- The SIU Guaraní list at the bottom was removed per user request -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Modal SIU Guaraní (Login) -->
|
|
||||||
<ion-modal [isOpen]="isSiuModalOpen" (didDismiss)="closeSiuModal()" class="siu-login-modal" initialBreakpoint="0.8" [breakpoints]="[0, 0.8, 1]">
|
|
||||||
<ng-template>
|
|
||||||
<ion-header class="ion-no-border">
|
|
||||||
<ion-toolbar color="primary">
|
|
||||||
<ion-title>Conectar con SIU</ion-title>
|
|
||||||
<ion-buttons slot="end">
|
|
||||||
<ion-button (click)="closeSiuModal()" [disabled]="siuLoading">Cerrar</ion-button>
|
|
||||||
</ion-buttons>
|
|
||||||
</ion-toolbar>
|
|
||||||
</ion-header>
|
|
||||||
<ion-content class="ion-padding siu-login-content">
|
|
||||||
<div class="ion-text-center siu-logo-container ion-margin-bottom">
|
|
||||||
<ion-icon name="school" color="primary" style="font-size: 64px;"></ion-icon>
|
|
||||||
<h2 style="margin-top: 10px;">Historia Académica</h2>
|
|
||||||
<p style="color: var(--ion-color-medium);">Ingresá para traer tu recorrido y notas automáticamente a la app.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ion-list class="ion-margin-bottom siu-form-list" lines="full">
|
|
||||||
<ion-item>
|
|
||||||
<ion-icon name="person-outline" slot="start" color="medium"></ion-icon>
|
|
||||||
<ion-input type="text" placeholder="DNI (Sin puntos)" [(ngModel)]="siuDni" [disabled]="siuLoading" clearInput required></ion-input>
|
|
||||||
</ion-item>
|
|
||||||
<ion-item>
|
|
||||||
<ion-icon name="lock-closed-outline" slot="start" color="medium"></ion-icon>
|
|
||||||
<ion-input type="password" placeholder="Contraseña de SIU" [(ngModel)]="siuPass" [disabled]="siuLoading" clearOnEdit="false" required></ion-input>
|
|
||||||
</ion-item>
|
|
||||||
</ion-list>
|
|
||||||
|
|
||||||
<div class="siu-info ion-margin-bottom" style="font-size: 0.85rem; color: var(--ion-color-medium); background: rgba(var(--ion-color-primary-rgb), 0.1); padding: 12px; border-radius: 8px; border-left: 4px solid var(--ion-color-primary);">
|
|
||||||
<p style="margin-top: 0;"><ion-icon name="shield-checkmark-outline"></ion-icon> Privacidad Zero-Trust: Las credenciales no se envían a ningún servidor nuestro. La app se conecta directo con el portal localmente desde tu teléfono.</p>
|
|
||||||
<p style="margin-bottom: 0;"><ion-icon name="alert-circle-outline"></ion-icon> Al conectar, se importará tu última situación curricular.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ion-button expand="block" color="primary" class="ion-margin-top" (click)="sincronizarSiu()" [disabled]="siuLoading || !siuDni || !siuPass">
|
|
||||||
<ng-container *ngIf="!siuLoading">
|
|
||||||
<ion-icon name="log-in-outline" slot="start"></ion-icon>
|
|
||||||
Conectar y Sincronizar
|
|
||||||
</ng-container>
|
|
||||||
<ion-spinner *ngIf="siuLoading" name="crescent"></ion-spinner>
|
|
||||||
</ion-button>
|
|
||||||
</ion-content>
|
|
||||||
</ng-template>
|
|
||||||
</ion-modal>
|
|
||||||
|
|
||||||
</ion-content>
|
</ion-content>
|
||||||
|
|
||||||
|
|||||||
+108
-81
@@ -1,5 +1,5 @@
|
|||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import { ToastController, ModalController, AlertController, ActionSheetController, IonicSafeString } from '@ionic/angular';
|
import { ToastController, ModalController, AlertController, ActionSheetController, NavController } from '@ionic/angular';
|
||||||
|
|
||||||
import { DataService, ClaseHorario, EventoAcademico } from '../services/data';
|
import { DataService, ClaseHorario, EventoAcademico } from '../services/data';
|
||||||
import { Preferences } from '@capacitor/preferences';
|
import { Preferences } from '@capacitor/preferences';
|
||||||
@@ -14,6 +14,7 @@ import { EventosService } from '../services/eventos.service';
|
|||||||
import { EventoModalComponent } from '../components/evento-modal/evento-modal.component';
|
import { EventoModalComponent } from '../components/evento-modal/evento-modal.component';
|
||||||
import { AgendaModalComponent } from '../components/agenda-modal/agenda-modal.component';
|
import { AgendaModalComponent } from '../components/agenda-modal/agenda-modal.component';
|
||||||
import { SiuService } from '../services/siu-guarani.service';
|
import { SiuService } from '../services/siu-guarani.service';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
|
||||||
|
|
||||||
export interface ProximaClaseInfo {
|
export interface ProximaClaseInfo {
|
||||||
@@ -67,13 +68,9 @@ export class HomePage implements OnInit {
|
|||||||
|
|
||||||
carreraSeleccionada: string = 'tecnologias';
|
carreraSeleccionada: string = 'tecnologias';
|
||||||
|
|
||||||
// SIU Guaraní State
|
// SIU Guaraní State (Datos persistidos)
|
||||||
siuMaterias: any[] = [];
|
siuMaterias: any[] = [];
|
||||||
siuLastSync: string | null = null;
|
siuLastSync: string | null = null;
|
||||||
isSiuModalOpen: boolean = false;
|
|
||||||
siuLoading: boolean = false;
|
|
||||||
siuDni: string = '';
|
|
||||||
siuPass: string = '';
|
|
||||||
|
|
||||||
|
|
||||||
// Mapa de días en español al getDay() de JS (0=Dom)
|
// Mapa de días en español al getDay() de JS (0=Dom)
|
||||||
@@ -91,7 +88,9 @@ export class HomePage implements OnInit {
|
|||||||
private localStorageService: LocalStorageService,
|
private localStorageService: LocalStorageService,
|
||||||
private actionSheetCtrl: ActionSheetController,
|
private actionSheetCtrl: ActionSheetController,
|
||||||
private eventosService: EventosService,
|
private eventosService: EventosService,
|
||||||
private siuService: SiuService
|
private siuService: SiuService,
|
||||||
|
private authService: AuthService,
|
||||||
|
private navCtrl: NavController
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
|
|
||||||
@@ -108,6 +107,30 @@ export class HomePage implements OnInit {
|
|||||||
this.loadInitialData();
|
this.loadInitialData();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async ionViewWillEnter() {
|
||||||
|
// Recargamos datos de progreso por si volvimos desde Perfil
|
||||||
|
const userData = await this.localStorageService.loadData();
|
||||||
|
if (userData) {
|
||||||
|
this.siuMaterias = userData.siuMaterias || [];
|
||||||
|
this.siuLastSync = userData.siuLastSync || null;
|
||||||
|
this.aprobadas = userData.aprobadas || [];
|
||||||
|
this.encurso = userData.encurso || [];
|
||||||
|
this.favoritos = userData.favoritos || [];
|
||||||
|
this.optativasSeleccionadas = userData.optativas || [];
|
||||||
|
|
||||||
|
// Crucial: Recargar los eventos al objeto local
|
||||||
|
this.eventos = await this.eventosService.loadEventos();
|
||||||
|
|
||||||
|
// Disparamos la lógica de auto-completar para mapear optativas y estados académicos
|
||||||
|
if (this.siuMaterias.length > 0) {
|
||||||
|
await this.autoCompletarDesdeSiu();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.filterHorarios();
|
||||||
|
this.actualizarProximaClase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async loadInitialData() {
|
async loadInitialData() {
|
||||||
// 0. Sincronizar permisos secuencialmente al iniciar la app para evitar que un popup de Android anule a otro
|
// 0. Sincronizar permisos secuencialmente al iniciar la app para evitar que un popup de Android anule a otro
|
||||||
try {
|
try {
|
||||||
@@ -133,7 +156,7 @@ export class HomePage implements OnInit {
|
|||||||
|
|
||||||
// Auto-completar desde SIU si hay datos previamente cacheados
|
// Auto-completar desde SIU si hay datos previamente cacheados
|
||||||
if (this.siuMaterias.length > 0) {
|
if (this.siuMaterias.length > 0) {
|
||||||
this.autoCompletarDesdeSiu();
|
await this.autoCompletarDesdeSiu();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sincronizar eventos cargados desde el CSV con el servicio de eventos
|
// Sincronizar eventos cargados desde el CSV con el servicio de eventos
|
||||||
@@ -484,15 +507,6 @@ export class HomePage implements OnInit {
|
|||||||
if (isFav) {
|
if (isFav) {
|
||||||
this.favoritos = this.favoritos.filter(id => id !== item.codigo);
|
this.favoritos = this.favoritos.filter(id => id !== item.codigo);
|
||||||
} else {
|
} else {
|
||||||
if (this.favoritos.length >= 5) {
|
|
||||||
const toast = await this.toastCtrl.create({
|
|
||||||
message: 'Puedes seleccionar un máximo de 5 materias favoritas',
|
|
||||||
duration: 3000,
|
|
||||||
color: 'warning'
|
|
||||||
});
|
|
||||||
toast.present();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.favoritos.push(item.codigo);
|
this.favoritos.push(item.codigo);
|
||||||
}
|
}
|
||||||
await Preferences.set({ key: 'favoritos', value: JSON.stringify(this.favoritos) });
|
await Preferences.set({ key: 'favoritos', value: JSON.stringify(this.favoritos) });
|
||||||
@@ -567,13 +581,6 @@ export class HomePage implements OnInit {
|
|||||||
window.open(url, '_system');
|
window.open(url, '_system');
|
||||||
}
|
}
|
||||||
|
|
||||||
async openCredencial() {
|
|
||||||
const modal = await this.modalCtrl.create({
|
|
||||||
component: CredencialModalComponent
|
|
||||||
});
|
|
||||||
|
|
||||||
await modal.present();
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Hitos Académicos (Agenda) ---
|
// --- Hitos Académicos (Agenda) ---
|
||||||
|
|
||||||
@@ -1005,56 +1012,8 @@ export class HomePage implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- SIU Guaraní ---
|
goToPerfil() {
|
||||||
|
this.navCtrl.navigateForward('/perfil');
|
||||||
openSiuModal() {
|
|
||||||
this.isSiuModalOpen = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
closeSiuModal() {
|
|
||||||
this.isSiuModalOpen = false;
|
|
||||||
this.siuDni = '';
|
|
||||||
this.siuPass = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
async sincronizarSiu() {
|
|
||||||
if (!this.siuDni || !this.siuPass) {
|
|
||||||
const toast = await this.toastCtrl.create({
|
|
||||||
message: 'Por favor, ingresá DNI y Contraseña para conectar',
|
|
||||||
duration: 2500,
|
|
||||||
color: 'warning'
|
|
||||||
});
|
|
||||||
toast.present();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.siuLoading = true;
|
|
||||||
try {
|
|
||||||
const materias = await this.siuService.getAcademicHistory(this.siuDni, this.siuPass);
|
|
||||||
this.siuMaterias = materias;
|
|
||||||
this.siuLastSync = new Date().toISOString();
|
|
||||||
|
|
||||||
this.autoCompletarDesdeSiu();
|
|
||||||
this.guardarProgreso();
|
|
||||||
|
|
||||||
const toast = await this.toastCtrl.create({
|
|
||||||
message: 'Historial del SIU cargado con éxito!',
|
|
||||||
duration: 3000,
|
|
||||||
color: 'success'
|
|
||||||
});
|
|
||||||
toast.present();
|
|
||||||
this.closeSiuModal();
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
const toast = await this.toastCtrl.create({
|
|
||||||
message: 'Error al conectar con SIU. Comprobá tus datos o intentá más tarde.',
|
|
||||||
duration: 4000,
|
|
||||||
color: 'danger'
|
|
||||||
});
|
|
||||||
toast.present();
|
|
||||||
} finally {
|
|
||||||
this.siuLoading = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getNotaColor(nota: string): string {
|
getNotaColor(nota: string): string {
|
||||||
@@ -1084,7 +1043,17 @@ export class HomePage implements OnInit {
|
|||||||
const siuN = this.normalizeText(siuName);
|
const siuN = this.normalizeText(siuName);
|
||||||
const appN = this.normalizeText(this.getCleanSubjectName(appName));
|
const appN = this.normalizeText(this.getCleanSubjectName(appName));
|
||||||
if (!siuN || !appN) return false;
|
if (!siuN || !appN) return false;
|
||||||
return siuN === appN || appN.includes(siuN) || siuN.includes(appN);
|
|
||||||
|
// Prioridad 1: Coincidencia Exacta
|
||||||
|
if (siuN === appN) return true;
|
||||||
|
|
||||||
|
// Prioridad 2: Si una contiene a la otra PERO con un margen de seguridad (nombres largos)
|
||||||
|
// Evita que "Programación" coincida con "Programación de Vanguardia" si no son lo mismo
|
||||||
|
if (siuN.length > 8 && appN.length > 8) {
|
||||||
|
if (siuN.includes(appN) || appN.includes(siuN)) return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
getSiuMateriaParaCelda(materiaNombre: string): any {
|
getSiuMateriaParaCelda(materiaNombre: string): any {
|
||||||
@@ -1146,25 +1115,41 @@ export class HomePage implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
determinarEstadoSiu(nota: string, origen: string): 'aprobada' | 'encurso' | null {
|
determinarEstadoSiu(nota: string, origen: string): 'aprobada' | 'regular' | 'encurso' | null {
|
||||||
const n = parseInt(nota, 10);
|
const n = parseInt(nota, 10);
|
||||||
const lowerNota = (nota || '').toLowerCase();
|
const lowerNota = (nota || '').toLowerCase();
|
||||||
const lowerOrigen = (origen || '').toLowerCase();
|
const lowerOrigen = (origen || '').toLowerCase();
|
||||||
|
|
||||||
// Si la nota es numérica y es mayor o igual a 4, está aprobada
|
// 1. Aprobada (Nota >= 4 o texto explícito)
|
||||||
if (!isNaN(n) && n >= 4) return 'aprobada';
|
if (!isNaN(n) && n >= 4) return 'aprobada';
|
||||||
if (lowerNota.includes('aprobado') || lowerNota.includes('promocionado') || lowerNota.includes('equivalencia')) return 'aprobada';
|
if (lowerNota.includes('aprobado') || lowerNota.includes('promocionado') || lowerNota.includes('equivalencia')) return 'aprobada';
|
||||||
if (lowerOrigen.includes('aprobado') || lowerOrigen.includes('promocionado')) return 'aprobada';
|
if (lowerOrigen.includes('aprobado') || lowerOrigen.includes('promocionado')) return 'aprobada';
|
||||||
|
|
||||||
// Si no está aprobada, pero cursa regular o está anotado
|
// 2. En Curso (Actualidad)
|
||||||
if (lowerOrigen.includes('en curso') || lowerNota.includes('en curso') || lowerOrigen.includes('regular')) return 'encurso';
|
if (lowerOrigen.includes('en curso') || lowerNota.includes('en curso')) return 'encurso';
|
||||||
|
|
||||||
|
// 3. Regular (Cursada terminada sin final)
|
||||||
|
if (lowerOrigen.includes('regular') || lowerNota.includes('regular')) return 'regular';
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
autoCompletarDesdeSiu() {
|
async autoCompletarDesdeSiu() {
|
||||||
let changed = false;
|
let changed = false;
|
||||||
|
|
||||||
|
// 0. Obtener Credenciales y Datos Detallados de Inscripción
|
||||||
|
const creds = await this.authService.getSiuCredentials();
|
||||||
|
let inscripcionesSiu: any[] = [];
|
||||||
|
|
||||||
|
if (creds.dni && creds.pass) {
|
||||||
|
try {
|
||||||
|
inscripcionesSiu = await this.siuService.getInscripcionesActivas(creds.dni, creds.pass);
|
||||||
|
console.log('Inscripciones activas SIU:', inscripcionesSiu);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('No se pudieron obtener inscripciones activas:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Primero, pre-mapear optativas huérfanas
|
// Primero, pre-mapear optativas huérfanas
|
||||||
const newlyMapped = this.autoAsignarOptativasSiu();
|
const newlyMapped = this.autoAsignarOptativasSiu();
|
||||||
if (newlyMapped) changed = true;
|
if (newlyMapped) changed = true;
|
||||||
@@ -1184,12 +1169,54 @@ export class HomePage implements OnInit {
|
|||||||
this.aprobadas = [...this.aprobadas, appName];
|
this.aprobadas = [...this.aprobadas, appName];
|
||||||
this.encurso = this.encurso.filter(x => x !== appName);
|
this.encurso = this.encurso.filter(x => x !== appName);
|
||||||
changed = true;
|
changed = true;
|
||||||
} else if (estadoSiu === 'encurso' && !this.aprobadas.includes(appName) && !this.encurso.includes(appName)) {
|
} else if ((estadoSiu === 'encurso' || estadoSiu === 'regular') && !this.aprobadas.includes(appName) && !this.encurso.includes(appName)) {
|
||||||
this.encurso = [...this.encurso, appName];
|
this.encurso = [...this.encurso, appName];
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- FAVORITOS: Sincronización Inteligente ---
|
||||||
|
if (this.horarios && this.horarios.length > 0) {
|
||||||
|
// Prioridad 1: Por Código Exacto (Desde la página de Inscripción / Cursada)
|
||||||
|
if (inscripcionesSiu.length > 0) {
|
||||||
|
for (const insc of inscripcionesSiu) {
|
||||||
|
// Buscamos en nuestra cartelera si existe este código ASIG
|
||||||
|
const matchHorarios = this.horarios.filter(h => h.codigo === insc.codigo);
|
||||||
|
for (const h of matchHorarios) {
|
||||||
|
if (!this.favoritos.includes(h.codigo)) {
|
||||||
|
this.favoritos = [...this.favoritos, h.codigo];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prioridad 2: Por Nombre (Caso de fallback o si no hay códigos en la cartelera todavía)
|
||||||
|
if (this.siuMaterias && this.siuMaterias.length > 0) {
|
||||||
|
const enCursoEnSiu = this.siuMaterias.filter(m => this.determinarEstadoSiu(m.nota, m.origen) === 'encurso');
|
||||||
|
for (const siuMat of enCursoEnSiu) {
|
||||||
|
// Si ya la tenemos por código, omitimos el sync por nombre para evitar duplicados erroneos
|
||||||
|
const yaEnFavs = this.horarios.some(h => this.favoritos.includes(h.codigo) && this.matcheaSiu(siuMat.nombre, h.asignatura));
|
||||||
|
if (yaEnFavs) continue;
|
||||||
|
|
||||||
|
const matchHorarios = this.horarios.filter(h => this.matcheaSiu(siuMat.nombre, h.asignatura));
|
||||||
|
for (const h of matchHorarios) {
|
||||||
|
if (!this.favoritos.includes(h.codigo)) {
|
||||||
|
this.favoritos = [...this.favoritos, h.codigo];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
|
// Actualizamos preferencias específicamente para favoritos
|
||||||
|
await Preferences.set({ key: 'favoritos', value: JSON.stringify(this.favoritos) });
|
||||||
|
this.filterHorarios();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (changed) this.guardarProgreso();
|
if (changed) this.guardarProgreso();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { NgModule } from '@angular/core';
|
||||||
|
import { Routes, RouterModule } from '@angular/router';
|
||||||
|
import { PerfilPage } from './perfil.page';
|
||||||
|
|
||||||
|
const routes: Routes = [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
component: PerfilPage
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
@NgModule({
|
||||||
|
imports: [RouterModule.forChild(routes)],
|
||||||
|
exports: [RouterModule],
|
||||||
|
})
|
||||||
|
export class PerfilPageRoutingModule {}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { NgModule } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { IonicModule } from '@ionic/angular';
|
||||||
|
import { PerfilPageRoutingModule } from './perfil-routing.module';
|
||||||
|
import { PerfilPage } from './perfil.page';
|
||||||
|
|
||||||
|
@NgModule({
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
FormsModule,
|
||||||
|
IonicModule,
|
||||||
|
PerfilPageRoutingModule
|
||||||
|
],
|
||||||
|
declarations: [PerfilPage]
|
||||||
|
})
|
||||||
|
export class PerfilPageModule {}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
<ion-header [translucent]="true" class="ion-no-border">
|
||||||
|
<ion-toolbar color="secondary">
|
||||||
|
<ion-buttons slot="start">
|
||||||
|
<ion-back-button defaultHref="/home"></ion-back-button>
|
||||||
|
</ion-buttons>
|
||||||
|
<ion-title>Configuración de Perfil</ion-title>
|
||||||
|
</ion-toolbar>
|
||||||
|
</ion-header>
|
||||||
|
|
||||||
|
<ion-content [fullscreen]="true" color="light">
|
||||||
|
<div class="profile-header-gradient">
|
||||||
|
<div class="user-avatar-container">
|
||||||
|
<div class="avatar-circle">
|
||||||
|
<img *ngIf="authState?.userPhoto" [src]="authState?.userPhoto" class="user-photo-profile" />
|
||||||
|
<ion-icon *ngIf="!authState?.userPhoto" name="person-circle-outline"></ion-icon>
|
||||||
|
</div>
|
||||||
|
<h2 *ngIf="authState?.userName">{{ authState?.userName }}</h2>
|
||||||
|
<h2 *ngIf="!authState?.userName">Gestión de Cuentas</h2>
|
||||||
|
<p>Unificá tus credenciales de SIU y Campus</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="content-container">
|
||||||
|
<!-- SIU Guaraní Card -->
|
||||||
|
<ion-card class="auth-card" [class.connected]="authState?.siuConnected">
|
||||||
|
<ion-card-header>
|
||||||
|
<div class="card-title-row">
|
||||||
|
<ion-icon name="school" color="primary" class="service-icon"></ion-icon>
|
||||||
|
<ion-card-title>SIU Guaraní</ion-card-title>
|
||||||
|
<ion-badge *ngIf="authState?.siuConnected" color="primary" class="status-badge">Conectado</ion-badge>
|
||||||
|
<ion-badge *ngIf="!authState?.siuConnected" color="medium" class="status-badge">Sin Vincular</ion-badge>
|
||||||
|
</div>
|
||||||
|
<ion-card-subtitle>Historia Académica y Cartelera Personalizada</ion-card-subtitle>
|
||||||
|
</ion-card-header>
|
||||||
|
|
||||||
|
<ion-card-content *ngIf="!authState?.siuConnected">
|
||||||
|
<p class="auth-desc">Conectá con el SIU para traer tu historial y que la app auto-favoritee tus materias en curso.</p>
|
||||||
|
<ion-list lines="inset" class="auth-form">
|
||||||
|
<ion-item>
|
||||||
|
<ion-icon name="person-outline" slot="start" color="medium"></ion-icon>
|
||||||
|
<ion-input type="text" placeholder="DNI (Sin puntos)" [(ngModel)]="siuDni" clearInput></ion-input>
|
||||||
|
</ion-item>
|
||||||
|
<ion-item>
|
||||||
|
<ion-icon name="lock-closed-outline" slot="start" color="medium"></ion-icon>
|
||||||
|
<ion-input [type]="showSiuPass ? 'text' : 'password'" placeholder="Contraseña de SIU" [(ngModel)]="siuPass"></ion-input>
|
||||||
|
<ion-button slot="end" fill="clear" (click)="showSiuPass = !showSiuPass" color="medium">
|
||||||
|
<ion-icon [name]="showSiuPass ? 'eye-off-outline' : 'eye-outline'"></ion-icon>
|
||||||
|
</ion-button>
|
||||||
|
</ion-item>
|
||||||
|
</ion-list>
|
||||||
|
<ion-button expand="block" (click)="loginSiu()" class="ion-margin-top btn-connect">
|
||||||
|
<ion-icon name="log-in-outline" slot="start"></ion-icon>
|
||||||
|
Sincronizar SIU
|
||||||
|
</ion-button>
|
||||||
|
<p class="error-text" *ngIf="authState?.siuError">{{ authState?.siuError }}</p>
|
||||||
|
</ion-card-content>
|
||||||
|
|
||||||
|
<ion-card-content *ngIf="authState?.siuConnected">
|
||||||
|
<div class="connected-info">
|
||||||
|
<ion-icon name="checkmark-circle" color="primary"></ion-icon>
|
||||||
|
<div class="text">
|
||||||
|
<strong>Cuenta Vinculada</strong>
|
||||||
|
<span>DNI: {{ siuDni }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<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
|
||||||
|
</ion-button>
|
||||||
|
</ion-card-content>
|
||||||
|
</ion-card>
|
||||||
|
|
||||||
|
<!-- Campus UNICABA (Moodle) Card -->
|
||||||
|
<ion-card class="auth-card" [class.connected]="authState?.moodleConnected">
|
||||||
|
<ion-card-header>
|
||||||
|
<div class="card-title-row">
|
||||||
|
<ion-icon name="book" color="secondary" class="service-icon"></ion-icon>
|
||||||
|
<ion-card-title>Campus UNICABA</ion-card-title>
|
||||||
|
<ion-badge *ngIf="authState?.moodleConnected" color="primary" class="status-badge">Conectado</ion-badge>
|
||||||
|
<ion-badge *ngIf="!authState?.moodleConnected" color="medium" class="status-badge">Sin Vincular</ion-badge>
|
||||||
|
</div>
|
||||||
|
<ion-card-subtitle>Credencial Digital y Aulas Virtuales</ion-card-subtitle>
|
||||||
|
</ion-card-header>
|
||||||
|
|
||||||
|
<ion-card-content *ngIf="!authState?.moodleConnected">
|
||||||
|
<p class="auth-desc">Vinculá tu cuenta del campus para generar tu credencial digital offline y habilitar alertas de actividades.</p>
|
||||||
|
<ion-list lines="inset" class="auth-form">
|
||||||
|
<ion-item>
|
||||||
|
<ion-icon name="person-outline" slot="start" color="medium"></ion-icon>
|
||||||
|
<ion-input type="text" placeholder="DNI de Campus" [(ngModel)]="moodleDni" clearInput></ion-input>
|
||||||
|
</ion-item>
|
||||||
|
<ion-item>
|
||||||
|
<ion-icon name="lock-closed-outline" slot="start" color="medium"></ion-icon>
|
||||||
|
<ion-input [type]="showMoodlePass ? 'text' : 'password'" placeholder="Contraseña de Campus" [(ngModel)]="moodlePass"></ion-input>
|
||||||
|
<ion-button slot="end" fill="clear" (click)="showMoodlePass = !showMoodlePass" color="medium">
|
||||||
|
<ion-icon [name]="showMoodlePass ? 'eye-off-outline' : 'eye-outline'"></ion-icon>
|
||||||
|
</ion-button>
|
||||||
|
</ion-item>
|
||||||
|
</ion-list>
|
||||||
|
<ion-button expand="block" color="secondary" (click)="loginMoodle()" class="ion-margin-top btn-connect">
|
||||||
|
<ion-icon name="card-outline" slot="start"></ion-icon>
|
||||||
|
Vincular Credencial
|
||||||
|
</ion-button>
|
||||||
|
<p class="error-text" *ngIf="authState?.moodleError">{{ authState?.moodleError }}</p>
|
||||||
|
</ion-card-content>
|
||||||
|
|
||||||
|
<ion-card-content *ngIf="authState?.moodleConnected">
|
||||||
|
<div class="connected-info">
|
||||||
|
<ion-icon name="checkmark-circle" color="secondary"></ion-icon>
|
||||||
|
<div class="text">
|
||||||
|
<strong>Cuenta Vinculada</strong>
|
||||||
|
<span>DNI: {{ moodleDni }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ion-button expand="block" fill="clear" color="danger" (click)="logoutMoodle()" class="btn-logout">
|
||||||
|
<ion-icon name="log-out-outline" slot="start"></ion-icon>
|
||||||
|
Cerrar sesión Campus
|
||||||
|
</ion-button>
|
||||||
|
</ion-card-content>
|
||||||
|
</ion-card>
|
||||||
|
|
||||||
|
<div class="security-info ion-padding">
|
||||||
|
<ion-icon name="shield-checkmark" color="medium"></ion-icon>
|
||||||
|
<p>Tus credenciales se almacenan de forma segura y local en tu dispositivo. No son enviadas a servidores externos ajenos a la universidad.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ion-content>
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
.profile-header-gradient {
|
||||||
|
background: linear-gradient(135deg, var(--ion-color-secondary) 0%, var(--ion-color-primary) 100%);
|
||||||
|
padding: 40px 20px 60px 20px;
|
||||||
|
text-align: center;
|
||||||
|
color: white;
|
||||||
|
border-bottom-left-radius: 40px;
|
||||||
|
border-bottom-right-radius: 40px;
|
||||||
|
box-shadow: 0 10px 30px rgba(var(--ion-color-primary-rgb), 0.3);
|
||||||
|
|
||||||
|
.user-avatar-container {
|
||||||
|
.avatar-circle {
|
||||||
|
width: 80px;
|
||||||
|
height: 80px;
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border-radius: 50%;
|
||||||
|
margin: 0 auto 15px auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||||
|
overflow: hidden;
|
||||||
|
|
||||||
|
ion-icon {
|
||||||
|
font-size: 50px;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-photo-profile {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 5px 0 0 0;
|
||||||
|
opacity: 0.9;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-container {
|
||||||
|
margin-top: -30px;
|
||||||
|
padding: 0 16px 20px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card {
|
||||||
|
border-radius: 20px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
|
||||||
|
border: 1px solid rgba(0, 0, 0, 0.03);
|
||||||
|
overflow: hidden;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
|
||||||
|
&.connected {
|
||||||
|
border-left: 6px solid var(--ion-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
ion-card-header {
|
||||||
|
padding-bottom: 5px;
|
||||||
|
|
||||||
|
.card-title-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
|
||||||
|
.service-icon {
|
||||||
|
font-size: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
ion-card-title {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-badge {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ion-card-subtitle {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-desc {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--ion-color-medium);
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-form {
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
|
||||||
|
ion-item {
|
||||||
|
--padding-start: 10px;
|
||||||
|
--inner-padding-end: 10px;
|
||||||
|
--border-radius: 12px;
|
||||||
|
background: var(--ion-color-light);
|
||||||
|
margin-bottom: 8px;
|
||||||
|
--border-color: rgba(0, 0, 0, 0.05);
|
||||||
|
|
||||||
|
ion-icon {
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-connect {
|
||||||
|
margin-top: 20px;
|
||||||
|
--border-radius: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
height: 48px;
|
||||||
|
box-shadow: 0 4px 15px rgba(var(--ion-color-primary-rgb), 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.connected-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 15px;
|
||||||
|
background: rgba(var(--ion-color-primary-rgb), 0.1);
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 15px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
|
||||||
|
ion-icon {
|
||||||
|
font-size: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
strong {
|
||||||
|
font-size: 1rem;
|
||||||
|
color: var(--ion-color-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
span {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--ion-color-medium);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-logout {
|
||||||
|
--color: var(--ion-color-danger);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-text {
|
||||||
|
color: var(--ion-color-danger);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-top: 10px;
|
||||||
|
font-weight: 500;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.security-info {
|
||||||
|
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;
|
||||||
|
line-height: 1.4;
|
||||||
|
max-width: 250px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||||
|
import { ToastController, LoadingController, AlertController, NavController } from '@ionic/angular';
|
||||||
|
import { AuthService, AuthState } from '../services/auth.service';
|
||||||
|
import { SiuService } from '../services/siu-guarani.service';
|
||||||
|
import { CredencialService } from '../services/credencial.service';
|
||||||
|
import { LocalStorageService, AppData } from '../services/local-storage.service';
|
||||||
|
import { Subscription } from 'rxjs';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-perfil',
|
||||||
|
templateUrl: './perfil.page.html',
|
||||||
|
styleUrls: ['./perfil.page.scss'],
|
||||||
|
standalone: false
|
||||||
|
})
|
||||||
|
export class PerfilPage implements OnInit, OnDestroy {
|
||||||
|
authState: AuthState | null = null;
|
||||||
|
private authSub: Subscription | null = null;
|
||||||
|
|
||||||
|
// Form states
|
||||||
|
siuDni: string = '';
|
||||||
|
siuPass: string = '';
|
||||||
|
showSiuPass: boolean = false;
|
||||||
|
|
||||||
|
moodleDni: string = '';
|
||||||
|
moodlePass: string = '';
|
||||||
|
showMoodlePass: boolean = false;
|
||||||
|
|
||||||
|
loading: boolean = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private authService: AuthService,
|
||||||
|
private siuService: SiuService,
|
||||||
|
private credencialService: CredencialService,
|
||||||
|
private localStorageService: LocalStorageService,
|
||||||
|
private toastCtrl: ToastController,
|
||||||
|
private loadingCtrl: LoadingController,
|
||||||
|
private alertCtrl: AlertController,
|
||||||
|
private navCtrl: NavController
|
||||||
|
) { }
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
this.authSub = this.authService.authState$.subscribe(state => {
|
||||||
|
this.authState = state;
|
||||||
|
// Pre-fill DNI if already connected
|
||||||
|
if (state.siuConnected && !this.siuDni) this.siuDni = state.siuDni || '';
|
||||||
|
if (state.moodleConnected && !this.moodleDni) this.moodleDni = state.moodleDni || '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy() {
|
||||||
|
if (this.authSub) this.authSub.unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
async loginSiu() {
|
||||||
|
if (!this.siuDni || !this.siuPass) {
|
||||||
|
this.showToast('Por favor, ingresá DNI y Contraseña', 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loader = await this.loadingCtrl.create({ message: 'Validando con SIU Guaraní...' });
|
||||||
|
await loader.present();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const materias = await this.siuService.getAcademicHistory(this.siuDni, this.siuPass);
|
||||||
|
await this.authService.saveSiuCredentials(this.siuDni, this.siuPass);
|
||||||
|
|
||||||
|
// Persistir datos en LocalStorage para que Home los vea
|
||||||
|
const currentData = await this.localStorageService.loadData() || this.getDefaultData();
|
||||||
|
currentData.siuMaterias = materias;
|
||||||
|
currentData.siuLastSync = new Date().toISOString();
|
||||||
|
|
||||||
|
// Aplicar auto-favoritos (opcional, pero recomendado para consistencia)
|
||||||
|
// Nota: Aquí se podría llamar a una versión compartida de autoCompletarDesdeSiu
|
||||||
|
// Por ahora guardamos para que Home lo procese al volver
|
||||||
|
await this.localStorageService.saveData(currentData);
|
||||||
|
|
||||||
|
this.showToast('¡SIU Guaraní conectado y sincronizado!', 'success');
|
||||||
|
this.siuPass = '';
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(e);
|
||||||
|
this.authService.setSiuError(e.message || 'Error de conexión');
|
||||||
|
this.showToast('Error al conectar con SIU: ' + (e.message || 'Credenciales inválidas'), 'danger');
|
||||||
|
} finally {
|
||||||
|
await loader.dismiss();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async logoutSiu() {
|
||||||
|
const alert = await this.alertCtrl.create({
|
||||||
|
header: 'Cerrar Sesión en SIU',
|
||||||
|
message: '¿Estás seguro de que deseas desconectar tu cuenta de SIU Guaraní? Se borrarán tus credenciales guardadas.',
|
||||||
|
buttons: [
|
||||||
|
{ text: 'Cancelar', role: 'cancel' },
|
||||||
|
{
|
||||||
|
text: 'Cerrar Sesión',
|
||||||
|
role: 'destructive',
|
||||||
|
handler: () => {
|
||||||
|
this.authService.logoutSiu();
|
||||||
|
this.siuDni = '';
|
||||||
|
this.siuPass = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
await alert.present();
|
||||||
|
}
|
||||||
|
|
||||||
|
async loginMoodle() {
|
||||||
|
if (!this.moodleDni || !this.moodlePass) {
|
||||||
|
this.showToast('Por favor, ingresá DNI y Contraseña (Campus)', 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loader = await this.loadingCtrl.create({ message: 'Validando con Campus UNICABA...' });
|
||||||
|
await loader.present();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Validar y generar credencial (descarga PDF)
|
||||||
|
await this.credencialService.generateCredential(this.moodleDni, this.moodlePass);
|
||||||
|
|
||||||
|
// 2. Obtener Perfil (Nombre y Foto)
|
||||||
|
const profile = await this.credencialService.getUserProfile(this.moodleDni, this.moodlePass);
|
||||||
|
await this.authService.saveUserProfile(profile.name, profile.photo);
|
||||||
|
|
||||||
|
// 3. Guardar credenciales de acceso
|
||||||
|
await this.authService.saveMoodleCredentials(this.moodleDni, this.moodlePass);
|
||||||
|
|
||||||
|
this.showToast('¡Perfil sincronizado y Campus conectado!', 'success');
|
||||||
|
this.moodlePass = '';
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(e);
|
||||||
|
this.authService.setMoodleError(e.message || 'Error de conexión');
|
||||||
|
this.showToast('Error al conectar con Campus: ' + (e.message || 'Credenciales inválidas'), 'danger');
|
||||||
|
} finally {
|
||||||
|
await loader.dismiss();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async logoutMoodle() {
|
||||||
|
const alert = await this.alertCtrl.create({
|
||||||
|
header: 'Cerrar Sesión en Campus',
|
||||||
|
message: '¿Estás seguro de que deseas desconectar tu cuenta del Campus? Se borrará tu credencial digital cacheada.',
|
||||||
|
buttons: [
|
||||||
|
{ text: 'Cancelar', role: 'cancel' },
|
||||||
|
{
|
||||||
|
text: 'Cerrar Sesión',
|
||||||
|
role: 'destructive',
|
||||||
|
handler: () => {
|
||||||
|
this.authService.logoutMoodle();
|
||||||
|
this.moodleDni = '';
|
||||||
|
this.moodlePass = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
await alert.present();
|
||||||
|
}
|
||||||
|
|
||||||
|
goBack() {
|
||||||
|
this.navCtrl.back();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showToast(message: string, color: 'success' | 'warning' | 'danger') {
|
||||||
|
const toast = await this.toastCtrl.create({
|
||||||
|
message,
|
||||||
|
duration: 3000,
|
||||||
|
color,
|
||||||
|
position: 'bottom'
|
||||||
|
});
|
||||||
|
await toast.present();
|
||||||
|
}
|
||||||
|
|
||||||
|
private getDefaultData(): AppData {
|
||||||
|
return {
|
||||||
|
favoritos: [],
|
||||||
|
eventos: [],
|
||||||
|
aprobadas: [],
|
||||||
|
encurso: [],
|
||||||
|
optativas: [],
|
||||||
|
siuMaterias: [],
|
||||||
|
siuLastSync: null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { Preferences } from '@capacitor/preferences';
|
||||||
|
import { BehaviorSubject } from 'rxjs';
|
||||||
|
|
||||||
|
export interface AuthState {
|
||||||
|
siuConnected: boolean;
|
||||||
|
moodleConnected: boolean;
|
||||||
|
siuDni: string | null;
|
||||||
|
moodleDni: string | null;
|
||||||
|
siuError: string | null;
|
||||||
|
moodleError: string | null;
|
||||||
|
userName: string | null;
|
||||||
|
userPhoto: string | null; // Base64
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class AuthService {
|
||||||
|
private readonly PREF_SIU_DNI = 'auth_siu_dni';
|
||||||
|
private readonly PREF_SIU_PASS = 'auth_siu_pass';
|
||||||
|
private readonly PREF_MOODLE_DNI = 'auth_moodle_dni';
|
||||||
|
private readonly PREF_MOODLE_PASS = 'auth_moodle_pass';
|
||||||
|
private readonly PREF_USER_NAME = 'auth_user_name';
|
||||||
|
private readonly PREF_USER_PHOTO = 'auth_user_photo';
|
||||||
|
|
||||||
|
private authState = new BehaviorSubject<AuthState>({
|
||||||
|
siuConnected: false,
|
||||||
|
moodleConnected: false,
|
||||||
|
siuDni: null,
|
||||||
|
moodleDni: null,
|
||||||
|
siuError: null,
|
||||||
|
moodleError: null,
|
||||||
|
userName: null,
|
||||||
|
userPhoto: null
|
||||||
|
});
|
||||||
|
|
||||||
|
public authState$ = this.authState.asObservable();
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.initialLoad();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async initialLoad() {
|
||||||
|
const siuDni = await Preferences.get({ key: this.PREF_SIU_DNI });
|
||||||
|
const siuPass = await Preferences.get({ key: this.PREF_SIU_PASS });
|
||||||
|
const moodleDni = await Preferences.get({ key: this.PREF_MOODLE_DNI });
|
||||||
|
const moodlePass = await Preferences.get({ key: this.PREF_MOODLE_PASS });
|
||||||
|
const userName = await Preferences.get({ key: this.PREF_USER_NAME });
|
||||||
|
const userPhoto = await Preferences.get({ key: this.PREF_USER_PHOTO });
|
||||||
|
|
||||||
|
this.authState.next({
|
||||||
|
...this.authState.value,
|
||||||
|
siuConnected: !!(siuDni.value && siuPass.value),
|
||||||
|
moodleConnected: !!(moodleDni.value && moodlePass.value),
|
||||||
|
siuDni: siuDni.value,
|
||||||
|
moodleDni: moodleDni.value,
|
||||||
|
userName: userName.value,
|
||||||
|
userPhoto: userPhoto.value
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSiuCredentials() {
|
||||||
|
const dni = await Preferences.get({ key: this.PREF_SIU_DNI });
|
||||||
|
const pass = await Preferences.get({ key: this.PREF_SIU_PASS });
|
||||||
|
return { dni: dni.value, pass: pass.value };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMoodleCredentials() {
|
||||||
|
const dni = await Preferences.get({ key: this.PREF_MOODLE_DNI });
|
||||||
|
const pass = await Preferences.get({ key: this.PREF_MOODLE_PASS });
|
||||||
|
return { dni: dni.value, pass: pass.value };
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveSiuCredentials(dni: string, pass: string) {
|
||||||
|
await Preferences.set({ key: this.PREF_SIU_DNI, value: dni });
|
||||||
|
await Preferences.set({ key: this.PREF_SIU_PASS, value: pass });
|
||||||
|
this.updateState({ siuConnected: true, siuDni: dni, siuError: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveMoodleCredentials(dni: string, pass: string) {
|
||||||
|
await Preferences.set({ key: this.PREF_MOODLE_DNI, value: dni });
|
||||||
|
await Preferences.set({ key: this.PREF_MOODLE_PASS, value: pass });
|
||||||
|
this.updateState({ moodleConnected: true, moodleDni: dni, moodleError: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveUserProfile(name: string, photo: string | null) {
|
||||||
|
if (name) await Preferences.set({ key: this.PREF_USER_NAME, value: name });
|
||||||
|
if (photo) await Preferences.set({ key: this.PREF_USER_PHOTO, value: photo });
|
||||||
|
this.updateState({ userName: name, userPhoto: photo });
|
||||||
|
}
|
||||||
|
|
||||||
|
async logoutSiu() {
|
||||||
|
await Preferences.remove({ key: this.PREF_SIU_DNI });
|
||||||
|
await Preferences.remove({ key: this.PREF_SIU_PASS });
|
||||||
|
this.updateState({ siuConnected: false, siuDni: null, siuError: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
async logoutMoodle() {
|
||||||
|
await Preferences.remove({ key: this.PREF_MOODLE_DNI });
|
||||||
|
await Preferences.remove({ key: this.PREF_MOODLE_PASS });
|
||||||
|
// Al cerrar sesión de moodle, también deberíamos pensar si borramos la imagen de la credencial
|
||||||
|
await Preferences.remove({ key: 'credencial_base64' });
|
||||||
|
await Preferences.remove({ key: this.PREF_USER_NAME });
|
||||||
|
await Preferences.remove({ key: this.PREF_USER_PHOTO });
|
||||||
|
this.updateState({ moodleConnected: false, moodleDni: null, moodleError: null, userName: null, userPhoto: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
setSiuError(error: string | null) {
|
||||||
|
this.updateState({ siuError: error });
|
||||||
|
}
|
||||||
|
|
||||||
|
setMoodleError(error: string | null) {
|
||||||
|
this.updateState({ moodleError: error });
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateState(partial: Partial<AuthState>) {
|
||||||
|
this.authState.next({ ...this.authState.value, ...partial });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
import { Preferences } from '@capacitor/preferences';
|
import { Preferences } from '@capacitor/preferences';
|
||||||
import * as pdfjsLib from 'pdfjs-dist';
|
import * as pdfjsLib from 'pdfjs-dist';
|
||||||
|
|
||||||
@@ -15,85 +16,37 @@ export class CredencialService {
|
|||||||
private readonly LOGIN_URL = 'https://campus.udelaciudad.edu.ar/login/index.php';
|
private readonly LOGIN_URL = 'https://campus.udelaciudad.edu.ar/login/index.php';
|
||||||
private readonly CREDENTIAL_URL = 'https://campus.udelaciudad.edu.ar/mod/customcert/view.php?id=209134&downloadown=1';
|
private readonly CREDENTIAL_URL = 'https://campus.udelaciudad.edu.ar/mod/customcert/view.php?id=209134&downloadown=1';
|
||||||
|
|
||||||
private readonly PREF_DNI = 'credencial_dni';
|
|
||||||
private readonly PREF_PASS = 'credencial_pass';
|
|
||||||
private readonly PREF_IMAGE = 'credencial_base64';
|
private readonly PREF_IMAGE = 'credencial_base64';
|
||||||
|
|
||||||
constructor() {}
|
constructor(private authService: AuthService) {}
|
||||||
|
|
||||||
async getStoredCredentials() {
|
|
||||||
const dni = await Preferences.get({ key: this.PREF_DNI });
|
|
||||||
const pass = await Preferences.get({ key: this.PREF_PASS });
|
|
||||||
return { dni: dni.value, pass: pass.value };
|
|
||||||
}
|
|
||||||
|
|
||||||
async saveCredentials(dni: string, pass: string) {
|
|
||||||
await Preferences.set({ key: this.PREF_DNI, value: dni });
|
|
||||||
await Preferences.set({ key: this.PREF_PASS, value: pass });
|
|
||||||
}
|
|
||||||
|
|
||||||
async getCachedImage() {
|
async getCachedImage() {
|
||||||
const img = await Preferences.get({ key: this.PREF_IMAGE });
|
const img = await Preferences.get({ key: this.PREF_IMAGE });
|
||||||
return img.value;
|
return img.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
async clearAll() {
|
async clearCache() {
|
||||||
await Preferences.remove({ key: this.PREF_DNI });
|
|
||||||
await Preferences.remove({ key: this.PREF_PASS });
|
|
||||||
await Preferences.remove({ key: this.PREF_IMAGE });
|
await Preferences.remove({ key: this.PREF_IMAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes the full flow: Login -> Scrape Token -> Submit Login -> Download PDF -> Render Base64
|
* Executes the full flow: Login -> Scrape Token -> Submit Login -> Download PDF -> Render Base64
|
||||||
*/
|
*/
|
||||||
async generateCredential(dni: string, pass: string): Promise<string> {
|
/**
|
||||||
|
* Executes the full flow: Login -> Scrape Token -> Submit Login -> Download PDF -> Render Base64
|
||||||
|
*/
|
||||||
|
async generateCredential(dni: string, pass: string, onStatusChange?: (status: string) => void): Promise<string> {
|
||||||
try {
|
try {
|
||||||
// 1. Initial GET to fetch the login page and token
|
if (onStatusChange) onStatusChange('Conectando con el campus...');
|
||||||
const initialGet: HttpResponse = await CapacitorHttp.get({
|
|
||||||
url: this.LOGIN_URL,
|
|
||||||
headers: {
|
|
||||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Simple DOM parsing to extract logintoken
|
await this.loginMoodle(dni, pass);
|
||||||
const parser = new DOMParser();
|
|
||||||
const doc = parser.parseFromString(initialGet.data, 'text/html');
|
|
||||||
const tokenInput = doc.querySelector('input[name="logintoken"]') as HTMLInputElement;
|
|
||||||
|
|
||||||
if (!tokenInput || !tokenInput.value) {
|
if (onStatusChange) onStatusChange('Descargando PDF...');
|
||||||
throw new Error('No se pudo obtener el token de seguridad del campus.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const loginToken = tokenInput.value;
|
|
||||||
|
|
||||||
// 2. POST to login
|
|
||||||
// CapacitorHttp handles cookies internally, so the session cookie is saved.
|
|
||||||
// Send form urlencoded
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
params.append('username', dni);
|
|
||||||
params.append('password', pass);
|
|
||||||
params.append('logintoken', loginToken);
|
|
||||||
|
|
||||||
const loginPost: HttpResponse = await CapacitorHttp.post({
|
|
||||||
url: this.LOGIN_URL,
|
|
||||||
data: params.toString(),
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
|
||||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verify if login was successful
|
|
||||||
if (loginPost.data && loginPost.data.includes('loginerrormessage')) {
|
|
||||||
throw new Error('DNI o Clave incorrectos en el Campus.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Download the PDF
|
// 3. Download the PDF
|
||||||
// We need it as base64 from the native layer to reconstruct the buffer
|
|
||||||
const pdfRes: HttpResponse = await CapacitorHttp.get({
|
const pdfRes: HttpResponse = await CapacitorHttp.get({
|
||||||
url: this.CREDENTIAL_URL,
|
url: this.CREDENTIAL_URL,
|
||||||
responseType: 'arraybuffer', // Capacitor Http will return base64 string for arraybuffer
|
responseType: 'arraybuffer',
|
||||||
headers: {
|
headers: {
|
||||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||||
}
|
}
|
||||||
@@ -104,27 +57,109 @@ export class CredencialService {
|
|||||||
throw new Error(`El campus no devolvió un PDF. Recibido: ${contentType}`);
|
throw new Error(`El campus no devolvió un PDF. Recibido: ${contentType}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Capacitor returns base64 string when responseType is arraybuffer or blob
|
|
||||||
const base64Pdf = pdfRes.data;
|
const base64Pdf = pdfRes.data;
|
||||||
|
|
||||||
// Convert base64 PDF to Uint8Array for pdf.js
|
|
||||||
const pdfData = this.base64ToUint8Array(base64Pdf);
|
const pdfData = this.base64ToUint8Array(base64Pdf);
|
||||||
|
|
||||||
|
if (onStatusChange) onStatusChange('Generando imagen de credencial (esto puede tardar unos segundos)...');
|
||||||
|
|
||||||
// 4. Render PDF to Base64 Image using pdf.js
|
// 4. Render PDF to Base64 Image using pdf.js
|
||||||
const imgBase64 = await this.renderPdfToBase64(pdfData);
|
const imgBase64 = await this.renderPdfToBase64(pdfData);
|
||||||
|
|
||||||
// Save to cache securely
|
// Save to cache securely
|
||||||
await Preferences.set({ key: this.PREF_IMAGE, value: imgBase64 });
|
await Preferences.set({ key: this.PREF_IMAGE, value: imgBase64 });
|
||||||
|
|
||||||
// Save credentials for future transparent updates
|
if (onStatusChange) onStatusChange('¡Listo!');
|
||||||
await this.saveCredentials(dni, pass);
|
|
||||||
|
|
||||||
return imgBase64;
|
return imgBase64;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
throw new Error(e.message || 'Error desconocido al generar la credencial.');
|
throw new Error(e.message || 'Error desconocido al generar la credencial.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getUserProfile(dni: string, pass: string): Promise<{name: string, photo: string | null}> {
|
||||||
|
try {
|
||||||
|
await this.loginMoodle(dni, pass);
|
||||||
|
|
||||||
|
const profileRes: HttpResponse = await CapacitorHttp.get({
|
||||||
|
url: 'https://campus.udelaciudad.edu.ar/user/profile.php',
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const parser = new DOMParser();
|
||||||
|
const doc = parser.parseFromString(profileRes.data, 'text/html');
|
||||||
|
|
||||||
|
// 1. Extraer Nombre
|
||||||
|
const nameTag = doc.querySelector('.card-profile h3');
|
||||||
|
const userName = nameTag ? nameTag.textContent?.trim() || '' : '';
|
||||||
|
|
||||||
|
// 2. Extraer Foto
|
||||||
|
const imgTag = doc.querySelector('.userpicture img') as HTMLImageElement;
|
||||||
|
let userPhotoBase64: string | null = null;
|
||||||
|
|
||||||
|
if (imgTag && imgTag.src) {
|
||||||
|
try {
|
||||||
|
// Descargar la imagen y convertir a base64
|
||||||
|
const photoRes: HttpResponse = await CapacitorHttp.get({
|
||||||
|
url: imgTag.src,
|
||||||
|
responseType: 'arraybuffer'
|
||||||
|
});
|
||||||
|
userPhotoBase64 = `data:image/jpeg;base64,${photoRes.data}`;
|
||||||
|
} catch (imgError) {
|
||||||
|
console.error('Error downloading profile photo:', imgError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { name: userName, photo: userPhotoBase64 };
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error fetching user profile:', e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loginMoodle(dni: string, pass: string): Promise<void> {
|
||||||
|
// 1. Initial GET to fetch the login page and token
|
||||||
|
const initialGet: HttpResponse = await CapacitorHttp.get({
|
||||||
|
url: this.LOGIN_URL,
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const parser = new DOMParser();
|
||||||
|
const doc = parser.parseFromString(initialGet.data, 'text/html');
|
||||||
|
const tokenInput = doc.querySelector('input[name="logintoken"]') as HTMLInputElement;
|
||||||
|
|
||||||
|
if (!tokenInput || !tokenInput.value) {
|
||||||
|
throw new Error('No se pudo obtener el token de seguridad del campus.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const loginToken = tokenInput.value;
|
||||||
|
|
||||||
|
// 2. POST to login
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.append('username', dni);
|
||||||
|
params.append('password', pass);
|
||||||
|
params.append('logintoken', loginToken);
|
||||||
|
|
||||||
|
const loginPost: HttpResponse = await CapacitorHttp.post({
|
||||||
|
url: this.LOGIN_URL,
|
||||||
|
data: params.toString(),
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify if login was successful
|
||||||
|
if (loginPost.data && (loginPost.data.includes('loginerrormessage') || loginPost.data.includes('Inicie sesión en su cuenta'))) {
|
||||||
|
// En algunos casos Moodle no tira loginerrormessage pero vuelve a la pág de login
|
||||||
|
if (!loginPost.data.includes('user/profile.php') && !loginPost.data.includes('my/')) {
|
||||||
|
throw new Error('DNI o Clave incorrectos en el Campus.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private base64ToUint8Array(base64: string): Uint8Array {
|
private base64ToUint8Array(base64: string): Uint8Array {
|
||||||
const raw = window.atob(base64);
|
const raw = window.atob(base64);
|
||||||
const rawLength = raw.length;
|
const rawLength = raw.length;
|
||||||
@@ -137,7 +172,9 @@ export class CredencialService {
|
|||||||
|
|
||||||
private async renderPdfToBase64(pdfData: Uint8Array): Promise<string> {
|
private async renderPdfToBase64(pdfData: Uint8Array): Promise<string> {
|
||||||
// Configure pdf.js to use the standard worker from local assets.
|
// Configure pdf.js to use the standard worker from local assets.
|
||||||
pdfjsLib.GlobalWorkerOptions.workerSrc = 'assets/pdf.worker.min.mjs';
|
// Use an absolute URL based on the origin to avoid "Failed to resolve module specifier" on Emulators/Android.
|
||||||
|
const workerUrl = new URL('assets/pdf.worker.min.mjs', window.location.origin).href;
|
||||||
|
pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;
|
||||||
|
|
||||||
const loadingTask = pdfjsLib.getDocument({ data: pdfData });
|
const loadingTask = pdfjsLib.getDocument({ data: pdfData });
|
||||||
const pdf = await loadingTask.promise;
|
const pdf = await loadingTask.promise;
|
||||||
|
|||||||
@@ -1,25 +1,15 @@
|
|||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
import { CapacitorHttp, HttpResponse } from '@capacitor/core';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class SiuService {
|
export class SiuService {
|
||||||
|
constructor(private authService: AuthService) {}
|
||||||
private readonly BASE_URL = 'https://siuuniciu.eastus2.cloudapp.azure.com/caba';
|
private readonly BASE_URL = 'https://siuuniciu.eastus2.cloudapp.azure.com/caba';
|
||||||
|
|
||||||
async getAcademicHistory(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
async getAcademicHistory(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
||||||
try {
|
try {
|
||||||
// 1. LOGIN POST
|
await this.loginSiu(dni, pass, carreraId);
|
||||||
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 (Simulando el GET que capturamos)
|
|
||||||
// Esto es lo que destrabó el cuello de botella
|
|
||||||
await CapacitorHttp.get({
|
|
||||||
url: `${this.BASE_URL}/acceso/cambiar_carrera?id=${carreraId}&op=inicio_alumno`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// 3. OBTENER PLAN DE ESTUDIO
|
// 3. OBTENER PLAN DE ESTUDIO
|
||||||
const resPlan: HttpResponse = await CapacitorHttp.get({
|
const resPlan: HttpResponse = await CapacitorHttp.get({
|
||||||
@@ -27,7 +17,6 @@ export class SiuService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 4. PARSEO DEL JSON EMBEBIDO
|
// 4. PARSEO DEL JSON EMBEBIDO
|
||||||
// Buscamos el bloque on_arrival que contiene "info_plan"
|
|
||||||
const rawHtml = resPlan.data;
|
const rawHtml = resPlan.data;
|
||||||
const regex = /on_arrival\((\{.*?"id":"info_plan".*?\})\);/s;
|
const regex = /on_arrival\((\{.*?"id":"info_plan".*?\})\);/s;
|
||||||
const match = rawHtml.match(regex);
|
const match = rawHtml.match(regex);
|
||||||
@@ -40,11 +29,73 @@ export class SiuService {
|
|||||||
|
|
||||||
throw new Error('No se encontró el bloque de materias');
|
throw new Error('No se encontró el bloque de materias');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error SIU:', error);
|
console.error('Error SIU Academic History:', error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getInscripcionesActivas(dni: string, pass: string, carreraId: string = '30'): Promise<any[]> {
|
||||||
|
try {
|
||||||
|
await this.loginSiu(dni, pass, carreraId);
|
||||||
|
|
||||||
|
// OBTENER PÁGINA DE CURSADA
|
||||||
|
const resCursada: HttpResponse = await CapacitorHttp.get({
|
||||||
|
url: `${this.BASE_URL}/cursada`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const rawHtml = resCursada.data;
|
||||||
|
|
||||||
|
// Buscamos el bloque on_arrival que contiene "info_materia" (donde están las inscripciones)
|
||||||
|
const regex = /on_arrival\((\{.*?"id":"info_materia".*?\})\);/s;
|
||||||
|
const match = rawHtml.match(regex);
|
||||||
|
|
||||||
|
if (match && match[1]) {
|
||||||
|
const jsonData = JSON.parse(match[1]);
|
||||||
|
const contentHtml = jsonData.content;
|
||||||
|
return this.parseInscripcionesActivasHtml(contentHtml);
|
||||||
|
}
|
||||||
|
|
||||||
|
return []; // Quizás no tiene inscripciones activas
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error SIU Active Inscriptions:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loginSiu(dni: string, pass: string, carreraId: string): Promise<void> {
|
||||||
|
// 1. LOGIN POST
|
||||||
|
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
|
||||||
|
await CapacitorHttp.get({
|
||||||
|
url: `${this.BASE_URL}/acceso/cambiar_carrera?id=${carreraId}&op=inicio_alumno`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseInscripcionesActivasHtml(html: string): any[] {
|
||||||
|
const parser = new DOMParser();
|
||||||
|
const doc = parser.parseFromString(html, 'text/html');
|
||||||
|
// Buscamos los elementos que contienen los nombres de las materias (según el HTML del usuario)
|
||||||
|
const rows = Array.from(doc.querySelectorAll('.js-mis-inscripciones td'));
|
||||||
|
|
||||||
|
return rows.map(td => {
|
||||||
|
const text = td.textContent?.trim() || '';
|
||||||
|
// Formato esperado: "Nombre Materia - ASIG00125"
|
||||||
|
const parts = text.split(' - ');
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
const codigo = parts[parts.length - 1].trim();
|
||||||
|
const nombre = parts.slice(0, -1).join(' - ').trim();
|
||||||
|
return { nombre, codigo };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}).filter(item => item !== null);
|
||||||
|
}
|
||||||
|
|
||||||
private parseHtmlSubjects(html: string): any[] {
|
private parseHtmlSubjects(html: string): any[] {
|
||||||
const parser = new DOMParser();
|
const parser = new DOMParser();
|
||||||
const doc = parser.parseFromString(html, 'text/html');
|
const doc = parser.parseFromString(html, 'text/html');
|
||||||
|
|||||||
Reference in New Issue
Block a user