Feat: Diseño de flujo para el usuario

This commit is contained in:
Angel Capetillo Zavala
2026-09-24 11:18:24 -06:00
parent 473a269bed
commit 88ba59c669
13 changed files with 737 additions and 70 deletions
+281 -6
View File
@@ -3,6 +3,9 @@ import { provideRouter, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { App } from './app';
import { routes } from './app.routes';
import { InformationUploadDialog } from './information-upload-dialog';
import { MatDialogRef } from '@angular/material/dialog';
import { vi } from 'vitest';
describe('App', () => {
beforeEach(async () => {
@@ -72,7 +75,7 @@ describe('App', () => {
overlay.querySelector<HTMLButtonElement>('.source-card')!.click();
detectDialogChanges();
expect(continueButton.disabled).toBe(false);
continueButton.click();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
@@ -126,14 +129,38 @@ describe('App', () => {
continueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('h3')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.configuration-placeholder p')?.textContent).toContain(
'La confirmación de los archivos se implementará en la siguiente fase.',
expect(overlay.querySelector('h3')?.textContent).toContain('Archivos a procesar');
expect(overlay.querySelector('.upload-steps__item--complete')?.textContent).toContain('Fuente');
expect(overlay.querySelectorAll('.upload-steps__item--complete')[1]?.textContent).toContain('Configuración');
expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
'Revisa la información antes de iniciar el procesamiento.',
);
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain('Archivo');
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain('2');
expect(overlay.querySelectorAll('.confirmation-files .file-row')).toHaveLength(2);
expect(overlay.querySelector('.confirmation-files')?.textContent).not.toContain('pacientes.XLSX');
expect(overlay.querySelector('.confirmation-files')?.textContent).toContain('consultas.csv');
expect(overlay.querySelector('.confirmation-files')?.textContent).toContain('nuevo.json');
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain(
dialogComponent.formatFileSize(dialogComponent.totalFileSize()),
);
expect(overlay.querySelector('.confirmation-files .file-row__remove')).toBeNull();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.file-configuration .file-row')).toHaveLength(2);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.confirmation-files .file-row')).toHaveLength(2);
expect(overlay.querySelector('.confirmation-summary')?.textContent).toContain(
dialogComponent.formatFileSize(dialogComponent.totalFileSize()),
);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelectorAll('.file-row')).toHaveLength(2);
while (overlay.querySelector('.file-row__remove')) {
overlay.querySelector<HTMLButtonElement>('.file-row__remove')!.click();
detectDialogChanges();
@@ -152,7 +179,7 @@ describe('App', () => {
sqlContinueButton.click();
detectDialogChanges();
fixture.detectChanges();
expect(overlay.querySelector('h3')?.textContent).toContain('Conexión SQL');
expect(overlay.querySelector('input[formcontrolname="host"]')).not.toBeNull();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detectDialogChanges();
@@ -174,9 +201,257 @@ describe('App', () => {
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopenedOverlay.querySelector('.selected-files')).toBeNull();
expect(reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
const singleFile = new File(['{}'], 'solo.json', { type: 'application/json' });
const reopenedFileInput = reopenedOverlay.querySelector<HTMLInputElement>('input[type="file"]')!;
Object.defineProperty(reopenedFileInput, 'files', { configurable: true, value: [singleFile] });
reopenedFileInput.dispatchEvent(new Event('change', { bubbles: true }));
reopenedDialog.changeDetectorRef.detectChanges();
reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopenedOverlay.querySelector('.confirmation-summary')?.textContent).toContain('1');
expect(reopenedOverlay.querySelector('.confirmation-files')?.textContent).toContain('solo.json');
expect(reopenedOverlay.querySelector('.confirmation-files .file-row__remove')).toBeNull();
reopenedOverlay.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
expect(TestBed.inject(MatDialog).openDialogs).toHaveLength(0);
});
it('validates SQL configuration locally and keeps its values through navigation', async () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl('/');
await fixture.whenStable();
fixture.detectChanges();
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const dialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
const detect = () => dialog.changeDetectorRef.detectChanges();
const overlay = document.querySelector('.cdk-overlay-container')!;
const type = (selector: string, value: string) => {
const input = overlay.querySelector<HTMLInputElement>(selector)!;
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('blur', { bubbles: true }));
detect();
};
overlay.querySelectorAll<HTMLButtonElement>('.source-card')[1].click();
detect();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('.sql-config__hint')?.textContent).toContain(
'Ingresa los datos de la base de datos que deseas utilizar.',
);
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
const fillRequired = () => {
type('[formcontrolname="host"]', ' servidor.interno.local ');
type('[formcontrolname="database"]', ' datos ');
type('[formcontrolname="username"]', ' usuario ');
type('[formcontrolname="password"]', 'secreto');
};
fillRequired();
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(false);
type('[formcontrolname="port"]', '0');
expect(overlay.querySelector('.sql-config')?.textContent).toContain('El puerto debe estar entre 1 y 65535.');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
type('[formcontrolname="port"]', '65536');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(true);
type('[formcontrolname="port"]', '1433');
expect(overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')?.disabled).toBe(false);
const password = overlay.querySelector<HTMLInputElement>('[formcontrolname="password"]')!;
expect(password.type).toBe('password');
const showPassword = overlay.querySelector<HTMLButtonElement>('[aria-label="Mostrar contraseña"]')!;
expect(showPassword.getAttribute('aria-pressed')).toBe('false');
showPassword.focus();
expect(document.activeElement).toBe(showPassword);
showPassword.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
showPassword.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', bubbles: true }));
showPassword.click();
detect();
expect(password.type).toBe('text');
const hidePassword = overlay.querySelector<HTMLButtonElement>('[aria-label="Ocultar contraseña"]')!;
expect(hidePassword.getAttribute('aria-pressed')).toBe('true');
hidePassword.click();
detect();
expect(password.type).toBe('password');
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('.upload-dialog__description')?.textContent).toContain(
'Revisa la información antes de iniciar el procesamiento.',
);
expect(overlay.querySelector('.upload-steps__item--complete')?.textContent).toContain('Fuente');
expect(overlay.querySelectorAll('.upload-steps__item--complete')[1]?.textContent).toContain('Configuración');
expect(overlay.querySelector('.upload-steps__item--active')?.textContent).toContain('Confirmación');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('Conexión SQL');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('servidor.interno.local');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('1433');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('datos');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('usuario');
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('Proporcionadas');
expect(overlay.querySelector('.sql-summary')?.textContent).not.toContain('secreto');
expect(overlay.querySelector('.upload-dialog')?.innerHTML).not.toContain('secreto');
expect(overlay.querySelector('#connection-check-title')?.textContent).toContain('Verificación de conexión');
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'La conexión todavía no ha sido verificada.',
);
const processButton = () => overlay.querySelector<HTMLButtonElement>('.upload-dialog__process')!;
const verifyButton = () => overlay.querySelector<HTMLButtonElement>('.connection-check__action button')!;
expect(verifyButton().textContent).toContain('Probar conexión');
expect(verifyButton().disabled).toBe(false);
expect(overlay.querySelector('.upload-dialog__process')?.hasAttribute('disabled')).toBe(true);
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
expect(verifyButton().disabled).toBe(true);
expect(processButton().disabled).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 1250));
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'Conexión verificada correctamente.',
);
expect(processButton().disabled).toBe(false);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detect();
expect(overlay.querySelector<HTMLInputElement>('[formcontrolname="host"]')?.value).toBe(' servidor.interno.local ');
expect(overlay.querySelector<HTMLInputElement>('[formcontrolname="password"]')?.value).toBe('secreto');
const visiblePasswordButton = overlay.querySelector<HTMLButtonElement>('[aria-label="Mostrar contraseña"]')!;
visiblePasswordButton.click();
detect();
overlay.querySelector<HTMLButtonElement>('[aria-label="Ocultar contraseña"]')!.click();
detect();
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'Conexión verificada correctamente.',
);
expect(processButton().disabled).toBe(false);
const changedFields: Array<[string, string]> = [
['[formcontrolname="host"]', 'nuevo.servidor.local'],
['[formcontrolname="port"]', ''],
['[formcontrolname="database"]', 'otra_base'],
['[formcontrolname="username"]', 'otro_usuario'],
['[formcontrolname="password"]', 'otra_clave'],
];
for (let index = 0; index < changedFields.length; index++) {
overlay.querySelector<HTMLButtonElement>('.upload-dialog__back')!.click();
detect();
type(changedFields[index][0], changedFields[index][1]);
overlay.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain(
'La conexión todavía no ha sido verificada.',
);
expect(processButton().disabled).toBe(true);
if (changedFields[index][0] === '[formcontrolname="port"]') {
expect(overlay.querySelector('.sql-summary')?.textContent).toContain('No especificado');
}
if (index < changedFields.length - 1) {
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
await new Promise((resolve) => setTimeout(resolve, 1250));
detect();
expect(processButton().disabled).toBe(false);
}
}
expect(overlay.querySelector('.sql-summary')?.textContent).not.toContain('otra_clave');
expect(overlay.querySelector('.upload-dialog')?.innerHTML).not.toContain('otra_clave');
verifyButton().click();
detect();
expect(overlay.querySelector('#connection-check-state')?.textContent).toContain('Verificando conexión...');
overlay.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
detect();
fixture.detectChanges();
await new Promise((resolve) => setTimeout(resolve, 200));
fixture.nativeElement.querySelector('.home__action').click();
fixture.detectChanges();
await fixture.whenStable();
const reopened = document.querySelector('.cdk-overlay-container')!;
reopened.querySelectorAll<HTMLButtonElement>('.source-card')[1].click();
const reopenedDialog = TestBed.inject(MatDialog).openDialogs[0].componentRef!;
expect(
(reopenedDialog.instance as import('./information-upload-dialog').InformationUploadDialog)
.sqlVerificationState(),
).toBe('idle');
reopenedDialog.changeDetectorRef.detectChanges();
reopened.querySelector<HTMLButtonElement>('.upload-dialog__continue')!.click();
reopenedDialog.changeDetectorRef.detectChanges();
expect(reopened.querySelector<HTMLInputElement>('[formcontrolname="host"]')?.value).toBe('');
expect(reopened.querySelector<HTMLInputElement>('[formcontrolname="password"]')?.value).toBe('');
reopened.querySelector<HTMLButtonElement>('.upload-dialog__cancel')!.click();
}, 15000);
it('processes selected files in the same dialog and only exits from success', async () => {
const close = vi.fn();
await TestBed.configureTestingModule({
imports: [InformationUploadDialog],
providers: [{ provide: MatDialogRef, useValue: { close, disableClose: true } }],
}).compileComponents();
vi.useFakeTimers();
const fixture = TestBed.createComponent(InformationUploadDialog);
const component = fixture.componentInstance;
component.step.set('confirmation');
component.source.set('file');
component.files.set([new File(['data'], 'datos.csv')]);
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
root.querySelector<HTMLButtonElement>('.upload-dialog__process')!.click();
fixture.detectChanges();
expect(component.processingState()).toBe('processing');
expect(root.querySelector('.upload-dialog__close')).toBeNull();
expect(root.querySelector('.upload-steps')).toBeNull();
expect(root.querySelector('.upload-dialog__cancel')).toBeNull();
expect(root.querySelector('.upload-dialog__back')).toBeNull();
expect(root.querySelector('.upload-dialog__process')).toBeNull();
component.close();
expect(close).not.toHaveBeenCalled();
vi.advanceTimersByTime(2250);
fixture.detectChanges();
expect(component.processingProgress()).toBe(50);
expect(root.querySelector('.processing__percentage')?.textContent).toContain('50 %');
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
expect(component.processingState()).toBe('processing');
vi.advanceTimersByTime(2250);
fixture.detectChanges();
expect(component.processingState()).toBe('success');
expect(root.querySelector('#processing-success-title')?.textContent).toContain('Procesamiento completado');
expect(root.querySelector('.processing__finish')).not.toBeNull();
root.querySelector<HTMLButtonElement>('.processing__finish')!.click();
expect(close).toHaveBeenCalledOnce();
fixture.destroy();
vi.useRealTimers();
});
it('requires successful SQL verification and uses the shared processing screen', async () => {
const close = vi.fn();
await TestBed.configureTestingModule({
imports: [InformationUploadDialog],
providers: [{ provide: MatDialogRef, useValue: { close, disableClose: true } }],
}).compileComponents();
vi.useFakeTimers();
const fixture = TestBed.createComponent(InformationUploadDialog);
const component = fixture.componentInstance;
component.step.set('confirmation');
component.source.set('sql');
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(true);
component.sqlVerificationState.set('success');
fixture.detectChanges();
expect(root.querySelector<HTMLButtonElement>('.upload-dialog__process')?.disabled).toBe(false);
root.querySelector<HTMLButtonElement>('.upload-dialog__process')!.click();
fixture.detectChanges();
expect(component.processingState()).toBe('processing');
vi.advanceTimersByTime(4500);
fixture.detectChanges();
expect(component.processingState()).toBe('success');
expect(root.querySelector('.processing__finish')).not.toBeNull();
root.querySelector<HTMLButtonElement>('.processing__finish')!.click();
expect(close).toHaveBeenCalledOnce();
fixture.destroy();
vi.useRealTimers();
});
});
+35 -11
View File
@@ -1,3 +1,6 @@
@if (processingState()) {
<app-processing-status [state]="processingState()!" [progress]="processingProgress()" (finishRequested)="finishProcessing()" />
} @else {
<section class="upload-dialog" aria-labelledby="upload-title">
<header class="upload-dialog__header">
<h2 id="upload-title">Cargar información</h2>
@@ -77,17 +80,37 @@
</div>
} @else if (step() === 'configuration') {
<p class="upload-dialog__description">Configura la fuente seleccionada.</p>
<div class="upload-dialog__content configuration-placeholder" aria-live="polite">
<span class="configuration-placeholder__icon"><mat-icon aria-hidden="true">storage</mat-icon></span>
<h3>Conexión SQL</h3>
<p>La configuración de la conexión se implementará en la siguiente fase.</p>
<div class="upload-dialog__content" aria-live="polite">
<app-sql-connection-config [config]="sqlConfig()" (configChange)="updateSqlConfig($event)" (validChange)="isSqlConfigValid($event)" />
</div>
} @else if (source() === 'sql') {
<p class="upload-dialog__description">Revisa la información antes de iniciar el procesamiento.</p>
<div class="upload-dialog__content" aria-live="polite">
<app-sql-connection-confirmation [config]="sqlConfig()" [verificationState]="sqlVerificationState()" (verifyRequested)="simulateConnectionCheck()" />
</div>
} @else {
<p class="upload-dialog__description">Revisa el siguiente paso de la carga de información.</p>
<div class="upload-dialog__content configuration-placeholder" aria-live="polite">
<span class="configuration-placeholder__icon"><mat-icon aria-hidden="true">checklist</mat-icon></span>
<h3>Confirmación</h3>
<p>La confirmación de los archivos se implementará en la siguiente fase.</p>
<p class="upload-dialog__description">Revisa la información antes de iniciar el procesamiento.</p>
<div class="upload-dialog__content" aria-live="polite">
<dl class="confirmation-summary" aria-label="Resumen de la selección">
<div><dt>Fuente</dt><dd>Archivo</dd></div>
<div><dt>Archivos seleccionados</dt><dd>{{ files().length }}</dd></div>
<div><dt>Tamaño total</dt><dd>{{ formatFileSize(totalFileSize()) }}</dd></div>
</dl>
<section class="selected-files confirmation-files" aria-labelledby="confirmation-files-title">
<header class="selected-files__header">
<h3 id="confirmation-files-title">Archivos a procesar</h3>
<span class="selected-files__count" aria-label="Cantidad de archivos">{{ files().length }}</span>
</header>
<ul class="selected-files__list">
@for (file of files(); track file.name + ':' + file.size) {
<li class="file-row file-row--readonly">
<mat-icon class="file-row__icon" aria-hidden="true">{{ fileIcon(file) }}</mat-icon>
<span class="file-row__name" [title]="file.name">{{ file.name }}</span>
<span class="file-row__size">{{ formatFileSize(file.size) }}</span>
</li>
}
</ul>
</section>
</div>
}
@@ -98,8 +121,9 @@
<button class="upload-action upload-action--outlined action-back upload-dialog__back" mat-button type="button" (click)="back()">Regresar</button>
}
@if (step() !== 'confirmation') {
<button class="upload-action action-continue upload-dialog__continue" mat-flat-button type="button" [disabled]="step() === 'source' ? !source() : source() !== 'file' || files().length === 0" (click)="continue()">Continuar</button>
}
<button class="upload-action action-continue upload-dialog__continue" mat-flat-button type="button" [disabled]="step() === 'source' ? !source() : source() === 'file' ? files().length === 0 : !sqlConfigValid()" (click)="continue()">Continuar</button>
} @else { <button class="upload-action action-continue upload-dialog__process" mat-flat-button type="button" [disabled]="source() === 'file' ? files().length === 0 : sqlVerificationState() !== 'success'" (click)="process()">Procesar</button> }
</div>
</footer>
</section>
}
+19 -50
View File
@@ -5,6 +5,8 @@
.upload-dialog {
background: #fff;
color: #081839;
max-height: 100dvh;
overflow: auto;
padding: 28px 32px 24px;
}
.upload-dialog__header {
@@ -103,13 +105,6 @@
padding: 20px;
position: relative;
text-align: left;
transition:
background-color 0.16s ease,
border-color 0.16s ease;
}
.source-card:hover {
background: #fafbf7;
border-color: #c7d49a;
}
.source-card:focus-visible,
.upload-dialog__close:focus-visible,
@@ -195,9 +190,6 @@
min-height: 244px;
padding: 24px;
text-align: center;
transition:
background-color 0.14s ease,
border-color 0.14s ease;
}
.dropzone--active {
background: #f5f8e9;
@@ -300,6 +292,17 @@
overflow-y: auto;
padding: 0;
}
.confirmation-summary {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
margin: 0;
padding: 0;
}
.confirmation-summary div { background: #fcfdfb; border: 1px solid #e7eae3; border-radius: 8px; min-width: 0; padding: 10px 12px; }
.confirmation-summary dt { color: #7a7a7a; font-size: 12px; }
.confirmation-summary dd { font-size: 15px; font-weight: 600; margin: 4px 0 0; overflow-wrap: anywhere; }
.file-row--readonly { grid-template-columns: 22px minmax(0, 1fr) auto; padding-right: 12px; }
.file-row {
align-items: center;
display: grid;
@@ -331,9 +334,6 @@
}
.file-row__remove {
color: #596273;
height: 36px;
line-height: 36px;
width: 36px;
}
.upload-dialog__footer {
align-items: center;
@@ -372,9 +372,6 @@
.action-cancel:hover {
background: #696969;
}
.action-cancel:active {
background: #5d5d5d;
}
.action-back {
--mat-button-text-label-text-color: #081839;
background: #fff;
@@ -384,9 +381,6 @@
background: #f3f6e9;
border-color: #a8c243;
}
.action-back:active {
background: #e8eed5;
}
.action-continue {
--mat-button-filled-container-color: #6f821c;
--mat-button-filled-label-text-color: #f7f9ef;
@@ -397,9 +391,6 @@
.action-continue:hover:not(:disabled) {
--mat-button-filled-container-color: #809625;
}
.action-continue:active:not(:disabled) {
--mat-button-filled-container-color: #607216;
}
.action-continue:disabled {
--mat-button-filled-disabled-container-color: #e8ecdf;
--mat-button-filled-disabled-label-text-color: #9da38f;
@@ -455,40 +446,18 @@
grid-template-columns: 20px minmax(0, 1fr) auto 36px;
padding-left: 8px;
}
.file-row__name {
font-size: 12px;
}
.file-row__size {
font-size: 11px;
}
.file-row--readonly { grid-template-columns: 20px minmax(0, 1fr) auto; }
.file-row__name { font-size: 12px; }
.file-row__size { font-size: 11px; }
}
@media (max-width: 360px) {
.upload-dialog {
padding-inline: 16px;
}
.upload-steps li {
font-size: 10px;
}
.upload-dialog__footer {
gap: 4px;
}
.upload-dialog__navigation {
gap: 4px;
}
.upload-dialog { padding-inline: 16px; }
.upload-dialog__footer, .upload-dialog__navigation { gap: 4px; }
.action-cancel,
.action-back {
min-width: 56px;
padding-inline: 6px;
}
.action-continue {
min-width: 92px;
padding-inline: 10px;
}
}
@media (max-width: 300px) {
.upload-dialog__footer {
grid-template-columns: minmax(0, 1fr);
}
.action-continue { min-width: 92px; padding-inline: 10px; }
}
+101 -3
View File
@@ -1,26 +1,39 @@
import { Component, signal } from '@angular/core';
import { Component, computed, OnDestroy, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { SqlConnectionConfig, SqlConnectionConfigComponent } from './sql-connection-config';
import { SqlConnectionConfirmationComponent, SqlConnectionVerificationState } from './sql-connection-confirmation';
import { ProcessingStatusComponent } from './processing-status';
type UploadSource = 'file' | 'sql';
type UploadStep = 'source' | 'configuration' | 'confirmation';
export type ProcessingState = 'processing' | 'success' | 'error';
@Component({
imports: [MatButtonModule, MatDialogModule, MatIconModule],
imports: [MatButtonModule, MatDialogModule, MatIconModule, SqlConnectionConfigComponent, SqlConnectionConfirmationComponent, ProcessingStatusComponent],
selector: 'app-information-upload-dialog',
styleUrl: './information-upload-dialog.scss',
templateUrl: './information-upload-dialog.html',
})
export class InformationUploadDialog {
export class InformationUploadDialog implements OnDestroy {
readonly step = signal<UploadStep>('source');
readonly source = signal<UploadSource | null>(null);
readonly files = signal<File[]>([]);
readonly totalFileSize = computed(() => this.files().reduce((total, file) => total + file.size, 0));
readonly fileMessages = signal<string[]>([]);
readonly isDragOver = signal(false);
readonly sqlConfig = signal<SqlConnectionConfig>({ host: '', port: '', database: '', username: '', password: '' });
readonly sqlConfigValid = signal(false);
readonly sqlVerificationState = signal<SqlConnectionVerificationState>('idle');
readonly processingState = signal<ProcessingState | null>(null);
readonly processingProgress = signal(0);
private dragDepth = 0;
private readonly allowedExtensions = new Set(['xlsx', 'csv', 'json', 'pdf']);
private verifiedSqlConfig: SqlConnectionConfig | null = null;
private verificationTimer: ReturnType<typeof setTimeout> | null = null;
private processingTimer: ReturnType<typeof setInterval> | null = null;
constructor(private readonly dialogRef: MatDialogRef<InformationUploadDialog>) {}
@@ -32,18 +45,103 @@ export class InformationUploadDialog {
if (this.step() === 'source' && this.source()) this.step.set('configuration');
else if (this.step() === 'configuration' && this.source() === 'file' && this.files().length > 0) {
this.step.set('confirmation');
} else if (this.step() === 'configuration' && this.source() === 'sql' && this.sqlConfigValid()) {
this.step.set('confirmation');
}
}
updateSqlConfig(config: SqlConnectionConfig): void {
this.sqlConfig.set(config);
if (this.verifiedSqlConfig && !this.sameSqlConfig(this.verifiedSqlConfig, config)) {
this.clearVerificationTimer();
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
}
}
simulateConnectionCheck(): void {
if (this.sqlVerificationState() === 'checking') return;
// TODO: replace this fixed frontend simulation with verification via WebApi.
this.clearVerificationTimer();
this.verifiedSqlConfig = { ...this.sqlConfig() };
this.sqlVerificationState.set('checking');
this.verificationTimer = setTimeout(() => {
this.verificationTimer = null;
if (this.verifiedSqlConfig && this.sameSqlConfig(this.verifiedSqlConfig, this.sqlConfig())) {
this.sqlVerificationState.set('success');
} else {
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
}
}, 1200);
}
private sameSqlConfig(left: SqlConnectionConfig, right: SqlConnectionConfig): boolean {
return left.host === right.host && left.port === right.port && left.database === right.database &&
left.username === right.username && left.password === right.password;
}
private clearVerificationTimer(): void {
if (this.verificationTimer !== null) clearTimeout(this.verificationTimer);
this.verificationTimer = null;
}
back(): void {
if (this.step() === 'confirmation') this.step.set('configuration');
else if (this.step() === 'configuration') this.step.set('source');
}
isSqlConfigValid(valid: boolean): void {
this.sqlConfigValid.set(valid);
}
close(): void {
if (this.processingState() === 'processing') return;
this.clearVerificationTimer();
this.verifiedSqlConfig = null;
this.sqlVerificationState.set('idle');
this.dialogRef.close();
}
process(): void {
const allowed = this.source() === 'file'
? this.files().length > 0
: this.source() === 'sql' && this.sqlVerificationState() === 'success';
if (this.step() !== 'confirmation' || !allowed) return;
this.processingState.set('processing');
this.dialogRef.disableClose = true;
this.simulateProcessing();
}
finishProcessing(): void {
if (this.processingState() !== 'success') return;
this.close();
}
ngOnDestroy(): void {
this.clearVerificationTimer();
this.clearProcessingTimer();
}
private simulateProcessing(): void {
// TODO: reemplazar simulación por estado/progreso reportado por WebApi
this.clearProcessingTimer();
this.processingProgress.set(0);
this.processingTimer = setInterval(() => {
const progress = Math.min(this.processingProgress() + 1, 100);
this.processingProgress.set(progress);
if (progress === 100) {
this.clearProcessingTimer();
this.processingState.set('success');
}
}, 45);
}
private clearProcessingTimer(): void {
if (this.processingTimer !== null) clearInterval(this.processingTimer);
this.processingTimer = null;
}
onFileSelection(event: Event): void {
const input = event.target as HTMLInputElement;
this.addFiles(input.files ? Array.from(input.files) : []);
+30
View File
@@ -0,0 +1,30 @@
<section class="processing" [attr.aria-labelledby]="state === 'success' ? 'processing-success-title' : 'processing-title'">
@if (state === 'success') {
<div class="processing__success" aria-live="polite" aria-atomic="true">
<span class="processing__success-icon"><mat-icon aria-hidden="true">check</mat-icon></span>
<h2 id="processing-success-title">Procesamiento completado</h2>
<p>Los resultados están listos.</p>
<button class="processing__finish" mat-flat-button type="button" (click)="finishRequested.emit()">Finalizar</button>
</div>
} @else {
<div class="processing__active" aria-live="polite" aria-atomic="true">
<h2 id="processing-title">Procesando información</h2>
<p class="processing__intro">Estamos preparando los resultados.<br />Este proceso puede tardar unos minutos.</p>
<div class="processing__meter">
<mat-progress-bar mode="determinate" [value]="progress" aria-label="Progreso del procesamiento" />
<span class="processing__percentage">{{ progress }} %</span>
</div>
<p class="processing__current">{{ currentStage }}...</p>
<ol class="processing__stages" aria-label="Etapas del procesamiento">
@for (stage of ['Preparando información', 'Procesando datos', 'Generando resultados']; track stage; let i = $index) {
<li [class.processing__stage--complete]="stageStatus(i) === 'complete'" [class.processing__stage--active]="stageStatus(i) === 'active'" [class.processing__stage--pending]="stageStatus(i) === 'pending'">
<mat-icon aria-hidden="true">{{ stageStatus(i) === 'complete' ? 'check_circle' : stageStatus(i) === 'active' ? 'radio_button_checked' : 'radio_button_unchecked' }}</mat-icon>
<span>{{ stage }}</span>
<span class="visually-hidden">{{ stageStatus(i) === 'complete' ? 'completada' : stageStatus(i) === 'active' ? 'activa' : 'pendiente' }}</span>
</li>
}
</ol>
<p class="processing__note">No cierres esta ventana mientras termina el procesamiento.</p>
</div>
}
</section>
+33
View File
@@ -0,0 +1,33 @@
:host { display: block; }
.processing {
align-items: center;
background: #fff;
color: #081839;
display: flex;
justify-content: center;
min-height: min(500px, 100dvh);
padding: 36px clamp(20px, 7vw, 64px);
text-align: center;
}
.processing__active, .processing__success { margin: auto; max-width: 520px; width: 100%; }
.processing h2 { font-family: var(--font-heading); font-size: clamp(24px, 4vw, 30px); line-height: 1.2; margin: 0; }
.processing__intro, .processing__success p { color: #7a7a7a; font-size: 15px; line-height: 1.55; margin: 14px 0 30px; }
.processing__meter { align-items: center; display: flex; gap: 14px; }
.processing__meter mat-progress-bar { --mat-progress-bar-active-indicator-color: #71882b; --mat-progress-bar-track-color: #e9eddf; flex: 1; }
.processing__percentage { color: #081839; font-size: 14px; font-variant-numeric: tabular-nums; font-weight: 600; min-width: 42px; text-align: right; }
.processing__current { color: #52651d; font-size: 15px; font-weight: 600; margin: 18px 0 26px; }
.processing__stages { display: grid; gap: 14px; list-style: none; margin: 0 auto; max-width: 320px; padding: 0; text-align: left; }
.processing__stages li { align-items: center; display: flex; gap: 10px; font-size: 14px; }
.processing__stages mat-icon { flex: 0 0 20px; font-size: 20px; height: 20px; width: 20px; }
.processing__stage--complete { color: #71882b; }
.processing__stage--active { color: #081839; font-weight: 600; }
.processing__stage--pending { color: #858585; }
.processing__note { color: #858585; font-size: 13px; line-height: 1.5; margin: 30px auto 0; max-width: 300px; }
.processing__success { padding: 28px 0; }
.processing__success-icon { align-items: center; background: #f0f3e8; border-radius: 50%; color: #71882b; display: inline-flex; height: 64px; justify-content: center; margin-bottom: 22px; width: 64px; }
.processing__success-icon mat-icon { font-size: 34px; height: 34px; width: 34px; }
.processing__success p { margin-bottom: 28px; }
.processing__finish { --mat-button-filled-container-color: #6f821c; --mat-button-filled-label-text-color: #f7f9ef; --mat-button-filled-state-layer-color: transparent; border-radius: 8px; font-weight: 600; min-height: 46px; min-width: 150px; }
.processing__finish:hover { --mat-button-filled-container-color: #809625; }
.visually-hidden { clip: rect(0, 0, 0, 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; }
@media (max-width: 480px) { .processing { min-height: min(440px, 100dvh); padding: 28px 4px; } .processing__intro { font-size: 14px; } .processing__stages { gap: 12px; } }
+28
View File
@@ -0,0 +1,28 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import type { ProcessingState } from './information-upload-dialog';
@Component({
imports: [MatButtonModule, MatIconModule, MatProgressBarModule],
selector: 'app-processing-status',
styleUrl: './processing-status.scss',
templateUrl: './processing-status.html',
})
export class ProcessingStatusComponent {
@Input({ required: true }) state!: ProcessingState;
@Input({ required: true }) progress = 0;
@Output() readonly finishRequested = new EventEmitter<void>();
get currentStage(): string {
if (this.progress <= 20) return 'Preparando información';
if (this.progress <= 80) return 'Procesando datos';
return 'Generando resultados';
}
stageStatus(stage: number): 'complete' | 'active' | 'pending' {
const active = this.progress <= 20 ? 0 : this.progress <= 80 ? 1 : 2;
return stage < active ? 'complete' : stage === active ? 'active' : 'pending';
}
}
+33
View File
@@ -0,0 +1,33 @@
<form class="sql-config" [formGroup]="form" aria-label="Configuración de conexión SQL" novalidate>
<p class="sql-config__hint">Ingresa los datos de la base de datos que deseas utilizar.</p>
<div class="sql-config__host-row">
<mat-form-field appearance="outline">
<mat-label>Servidor / Host</mat-label>
<input matInput formControlName="host" autocomplete="off" />
@if (form.controls.host.invalid && (form.controls.host.dirty || form.controls.host.touched)) { <mat-error>El servidor es obligatorio.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Puerto</mat-label>
<input matInput formControlName="port" type="text" inputmode="numeric" placeholder="Ej. 1433" />
@if (form.controls.port.hasError('portRange') && (form.controls.port.dirty || form.controls.port.touched)) { <mat-error>El puerto debe estar entre 1 y 65535.</mat-error> }
</mat-form-field>
</div>
<mat-form-field appearance="outline">
<mat-label>Base de datos</mat-label>
<input matInput formControlName="database" autocomplete="off" />
@if (form.controls.database.invalid && (form.controls.database.dirty || form.controls.database.touched)) { <mat-error>La base de datos es obligatoria.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Usuario</mat-label>
<input matInput formControlName="username" autocomplete="username" />
@if (form.controls.username.invalid && (form.controls.username.dirty || form.controls.username.touched)) { <mat-error>El usuario es obligatorio.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Contraseña</mat-label>
<input matInput formControlName="password" [type]="passwordVisible ? 'text' : 'password'" autocomplete="off" />
<button class="password-toggle" mat-icon-button matSuffix type="button" [attr.aria-label]="passwordVisible ? 'Ocultar contraseña' : 'Mostrar contraseña'" [attr.aria-pressed]="passwordVisible" (click)="passwordVisible = !passwordVisible">
<mat-icon aria-hidden="true">{{ passwordVisible ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
@if (form.controls.password.invalid && (form.controls.password.dirty || form.controls.password.touched)) { <mat-error>La contraseña es obligatoria.</mat-error> }
</mat-form-field>
</form>
+28
View File
@@ -0,0 +1,28 @@
:host { display: block; min-width: 0; }
.sql-config { display: grid; gap: 2px; min-width: 0; }
.sql-config__hint { color: #7a7a7a; font-size: 14px; margin: 0 0 10px; }
.sql-config__host-row { display: grid; gap: 12px; grid-template-columns: minmax(0, 2.5fr) minmax(130px, 1fr); }
mat-form-field {
--mat-form-field-outlined-focus-outline-color: #a8c243;
--mat-form-field-outlined-focus-label-text-color: #71882b;
--mat-form-field-outlined-label-text-color: #596273;
min-width: 0;
width: 100%;
}
mat-form-field input { color: #081839; }
.password-toggle {
--mat-icon-button-icon-color: #7a7a7a;
--mat-icon-button-state-layer-color: transparent;
--mat-icon-button-ripple-color: transparent;
background: transparent;
border: 0;
border-radius: 50%;
box-shadow: none;
color: #7a7a7a;
opacity: 0.82;
transition: color 120ms ease, opacity 120ms ease;
}
.password-toggle:hover { background: transparent; color: #596273; opacity: 1; }
.password-toggle:active { background: transparent; color: #4d586a; }
.password-toggle:focus-visible { outline: 2px solid #a8c243; outline-offset: -3px; }
@media (max-width: 560px) { .sql-config__host-row { grid-template-columns: minmax(0, 1fr); gap: 2px; } }
+52
View File
@@ -0,0 +1,52 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, ValidationErrors, ValidatorFn } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
export interface SqlConnectionConfig {
host: string;
port: string;
database: string;
username: string;
password: string;
}
const requiredTrimmed: ValidatorFn = (control): ValidationErrors | null =>
String(control.value ?? '').trim() ? null : { required: true };
const optionalPort: ValidatorFn = (control): ValidationErrors | null => {
const value = String(control.value ?? '').trim();
if (!value) return null;
return /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 65535 ? null : { portRange: true };
};
@Component({
imports: [ReactiveFormsModule, MatFormFieldModule, MatIconModule, MatInputModule],
selector: 'app-sql-connection-config',
styleUrl: './sql-connection-config.scss',
templateUrl: './sql-connection-config.html',
})
export class SqlConnectionConfigComponent implements OnInit {
@Input({ required: true }) config!: SqlConnectionConfig;
@Output() readonly configChange = new EventEmitter<SqlConnectionConfig>();
@Output() readonly validChange = new EventEmitter<boolean>();
readonly form = new FormGroup({
host: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
port: new FormControl('', { nonNullable: true, validators: [optionalPort] }),
database: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
username: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
password: new FormControl('', { nonNullable: true, validators: [requiredTrimmed] }),
});
passwordVisible = false;
ngOnInit(): void {
this.form.setValue(this.config);
this.emitState();
this.form.valueChanges.subscribe(() => this.emitState());
}
private emitState(): void {
this.configChange.emit(this.form.getRawValue());
this.validChange.emit(this.form.valid);
}
}
+35
View File
@@ -0,0 +1,35 @@
<dl class="sql-summary" aria-label="Resumen de la conexión SQL">
<div class="sql-summary__item"><dt>Fuente</dt><dd>Conexión SQL</dd></div>
<div class="sql-summary__item"><dt>Servidor / Host</dt><dd [title]="config.host">{{ config.host }}</dd></div>
<div class="sql-summary__item"><dt>Puerto</dt><dd>{{ config.port.trim() ? config.port : 'No especificado' }}</dd></div>
<div class="sql-summary__item"><dt>Base de datos</dt><dd [title]="config.database">{{ config.database }}</dd></div>
<div class="sql-summary__item"><dt>Usuario</dt><dd [title]="config.username">{{ config.username }}</dd></div>
<div class="sql-summary__item"><dt>Credenciales</dt><dd>✓ Proporcionadas</dd></div>
</dl>
<section class="connection-check" aria-labelledby="connection-check-title">
<div class="connection-check__copy">
<h3 id="connection-check-title">Verificación de conexión</h3>
<div class="connection-check__status" id="connection-check-state" role="status" aria-live="polite">
@if (verificationState === 'idle') {
<p>La conexión todavía no ha sido verificada.</p>
} @else if (verificationState === 'checking') {
<mat-progress-spinner class="connection-check__spinner" mode="indeterminate" diameter="18" aria-hidden="true" />
<p>Verificando conexión...</p>
} @else if (verificationState === 'success') {
<mat-icon class="connection-check__success" aria-hidden="true">check_circle</mat-icon>
<p>Conexión verificada correctamente.</p>
} @else {
<mat-icon class="connection-check__error" aria-hidden="true">error_outline</mat-icon>
<p>No se pudo verificar la conexión.</p>
}
</div>
</div>
<div class="connection-check__action">
<button mat-stroked-button type="button" [disabled]="verificationState === 'checking'" aria-describedby="connection-check-state" (click)="verifyRequested.emit()">
<mat-icon aria-hidden="true">{{ verificationState === 'success' ? 'refresh' : 'sync' }}</mat-icon>
{{ verificationState === 'success' ? 'Verificar nuevamente' : 'Probar conexión' }}
</button>
@if (verificationState === 'idle') { <span>Pendiente de integración con WebApi</span> }
</div>
</section>
+43
View File
@@ -0,0 +1,43 @@
:host { display: block; min-width: 0; }
.sql-summary {
display: grid;
gap: 10px;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin: 0;
}
.sql-summary__item {
background: #fcfdfb;
border: 1px solid #e7eae3;
border-radius: 8px;
min-width: 0;
padding: 10px 12px;
}
.sql-summary dt { color: #7a7a7a; font-size: 12px; }
.sql-summary dd { color: #081839; font-size: 15px; font-weight: 600; margin: 4px 0 0; overflow-wrap: anywhere; }
.connection-check {
align-items: center;
background: #fcfdfb;
border: 1px solid #e7eae3;
border-radius: 8px;
display: flex;
gap: 16px;
justify-content: space-between;
margin-top: 14px;
padding: 12px 14px;
}
.connection-check h3 { color: #081839; font-size: 14px; font-weight: 600; margin: 0; }
.connection-check p { color: #7a7a7a; font-size: 13px; margin: 4px 0 0; }
.connection-check__status { align-items: center; display: flex; gap: 7px; min-height: 20px; }
.connection-check__status p { margin: 4px 0 0; }
.connection-check__spinner { --mat-progress-spinner-active-indicator-color: #71882b; flex: 0 0 auto; }
.connection-check__success { color: #71882b; }
.connection-check__error { color: #7a7a7a; }
.connection-check__action { align-items: flex-end; display: flex; flex-direction: column; gap: 3px; }
.connection-check__action button { --mat-button-outlined-label-text-color: #596273; --mat-button-outlined-outline-color: #d7dccf; white-space: nowrap; }
.connection-check__action span { color: #7a7a7a; font-size: 11px; }
@media (max-width: 760px) { .sql-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 480px) {
.sql-summary { grid-template-columns: minmax(0, 1fr); }
.connection-check { align-items: flex-start; flex-direction: column; }
.connection-check__action { align-items: flex-start; }
}
+19
View File
@@ -0,0 +1,19 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { SqlConnectionConfig } from './sql-connection-config';
export type SqlConnectionVerificationState = 'idle' | 'checking' | 'success' | 'error';
@Component({
imports: [MatButtonModule, MatIconModule, MatProgressSpinnerModule],
selector: 'app-sql-connection-confirmation',
styleUrl: './sql-connection-confirmation.scss',
templateUrl: './sql-connection-confirmation.html',
})
export class SqlConnectionConfirmationComponent {
@Input({ required: true }) config!: SqlConnectionConfig;
@Input({ required: true }) verificationState: SqlConnectionVerificationState = 'idle';
@Output() readonly verifyRequested = new EventEmitter<void>();
}