Compare commits
19 Commits
feature/ca
...
625e2fea6c
| Author | SHA1 | Date | |
|---|---|---|---|
| 625e2fea6c | |||
| 3697c4b97c | |||
| bedb74ebd5 | |||
| 6bab2e9ab2 | |||
| bd4b86fe85 | |||
| 6ffffc6ea8 | |||
| 57f58c92be | |||
| 5365811a50 | |||
| 3c98600193 | |||
| ff3c3233c1 | |||
| 20e8578440 | |||
| 193ba7472b | |||
| bc9390394a | |||
| 4393280fd9 | |||
| 956411254e | |||
| 4cbf87feb1 | |||
| 93d49fc7e6 | |||
| 85465ce7e1 | |||
| ee83e7ab32 |
@@ -1,9 +1,11 @@
|
|||||||
import { provideHttpClient, withFetch } from '@angular/common/http';
|
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
|
||||||
import { ApplicationConfig, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
|
import { ApplicationConfig, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { provideClientHydration } from '@angular/platform-browser';
|
import { provideClientHydration } from '@angular/platform-browser';
|
||||||
|
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
|
import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
||||||
|
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
@@ -11,7 +13,8 @@ export const appConfig: ApplicationConfig = {
|
|||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
provideClientHydration(),
|
provideClientHydration(),
|
||||||
provideHttpClient(withFetch()),
|
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
|
||||||
|
provideAppInitializer(authBootstrap),
|
||||||
provideAppInitializer(tenantBootstrap)
|
provideAppInitializer(tenantBootstrap)
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import { signal } from '@angular/core';
|
import { computed, signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { of } from 'rxjs';
|
||||||
|
|
||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { routes } from './app.routes';
|
import { AuthService } from './core/services/auth/auth.service';
|
||||||
|
import { CartService } from './core/services/cart/cart.service';
|
||||||
import { Tenant } from './core/services/tenant.interface';
|
import { Tenant } from './core/services/tenant.interface';
|
||||||
import { TenantService } from './core/services/tenant.service';
|
import { TenantService } from './core/services/tenant.service';
|
||||||
import { CartService } from './core/services/cart/cart.service';
|
import { routes } from './app.routes';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -47,9 +48,33 @@ function createTenantServiceStub(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createAuthServiceStub(isAuthenticated = false) {
|
||||||
|
const tokenState = signal<string | null>(isAuthenticated ? 'test-token' : null);
|
||||||
|
const userState = signal(
|
||||||
|
isAuthenticated ? { id: 1, nombre_apellido: 'Ada Lovelace', email: 'ada@example.com' } : null
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
user: userState.asReadonly(),
|
||||||
|
token: tokenState.asReadonly(),
|
||||||
|
isAuthenticated: computed(() => tokenState() !== null),
|
||||||
|
login: vi.fn(),
|
||||||
|
register: vi.fn(),
|
||||||
|
logout: vi.fn(),
|
||||||
|
loadCurrentUser: vi.fn(),
|
||||||
|
hydrateSession: vi.fn(),
|
||||||
|
bootstrap: vi.fn().mockResolvedValue(undefined),
|
||||||
|
clearSession: vi.fn(() => {
|
||||||
|
userState.set(null);
|
||||||
|
tokenState.set(null);
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async function renderAppAt(
|
async function renderAppAt(
|
||||||
url: string,
|
url: string,
|
||||||
tenantService: ReturnType<typeof createTenantServiceStub> = createTenantServiceStub()
|
tenantService: ReturnType<typeof createTenantServiceStub> = createTenantServiceStub(),
|
||||||
|
authService: ReturnType<typeof createAuthServiceStub> = createAuthServiceStub()
|
||||||
) {
|
) {
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
|
|
||||||
@@ -67,6 +92,10 @@ async function renderAppAt(
|
|||||||
cart: signal(null).asReadonly(),
|
cart: signal(null).asReadonly(),
|
||||||
loadCart: () => of({ id: 1, items: [], subtotal: '0' })
|
loadCart: () => of({ id: 1, items: [], subtotal: '0' })
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: AuthService,
|
||||||
|
useValue: authService
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -106,10 +135,47 @@ describe('app routes', () => {
|
|||||||
expect(compiled.textContent).toContain('Componentes reutilizables');
|
expect(compiled.textContent).toContain('Componentes reutilizables');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('loads the login page at /login and shows the create account CTA', async () => {
|
||||||
|
const { fixture, router } = await renderAppAt('/login');
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
expect(router.url).toBe('/login');
|
||||||
|
expect(compiled.querySelector('app-login-page')).not.toBeNull();
|
||||||
|
expect(compiled.textContent).toContain('Iniciar sesion');
|
||||||
|
expect(compiled.textContent).toContain('Crear cuenta');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads the register page at /register and renders the shared auth fields', async () => {
|
||||||
|
const { fixture, router } = await renderAppAt('/register');
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
const registerPage = compiled.querySelector('app-register-page');
|
||||||
|
const placeholders = Array.from(registerPage?.querySelectorAll('input') ?? []).map((input) =>
|
||||||
|
input.getAttribute('placeholder')
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(router.url).toBe('/register');
|
||||||
|
expect(registerPage).not.toBeNull();
|
||||||
|
expect(compiled.textContent).toContain('CREAR CUENTA');
|
||||||
|
expect(compiled.textContent).toContain('Volver');
|
||||||
|
expect(placeholders).toEqual([
|
||||||
|
'Nombre y Apellido',
|
||||||
|
'Email',
|
||||||
|
'Contrasena',
|
||||||
|
'Repetir Contrasena'
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirects authenticated users away from /login', async () => {
|
||||||
|
const { router } = await renderAppAt('/login', createTenantServiceStub(), createAuthServiceStub(true));
|
||||||
|
|
||||||
|
expect(router.url).toBe('/');
|
||||||
|
});
|
||||||
|
|
||||||
it('renders the tenant not found screen for any route when the tenant is missing', async () => {
|
it('renders the tenant not found screen for any route when the tenant is missing', async () => {
|
||||||
const { fixture } = await renderAppAt(
|
const { fixture } = await renderAppAt(
|
||||||
'/componentes-test/reutilizables',
|
'/componentes-test/reutilizables',
|
||||||
createTenantServiceStub('not-found', null)
|
createTenantServiceStub('not-found', null),
|
||||||
|
createAuthServiceStub()
|
||||||
);
|
);
|
||||||
const compiled = fixture.nativeElement as HTMLElement;
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
|||||||
13
src/app/core/layout/auth-layout/auth-layout.component.html
Normal file
13
src/app/core/layout/auth-layout/auth-layout.component.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<section class="auth-layout">
|
||||||
|
<div class="auth-layout__container container-xl">
|
||||||
|
<div class="auth-layout__row row justify-content-center">
|
||||||
|
<div class="auth-layout__column col-12 col-md-9 col-lg-7 col-xl-5">
|
||||||
|
<article class="auth-layout__card card border-0 shadow-lg">
|
||||||
|
<div class="auth-layout__body card-body">
|
||||||
|
<router-outlet />
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
50
src/app/core/layout/auth-layout/auth-layout.component.scss
Normal file
50
src/app/core/layout/auth-layout/auth-layout.component.scss
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout {
|
||||||
|
padding: 1.5rem 0 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__container {
|
||||||
|
padding-inline: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__row {
|
||||||
|
padding-block: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__card {
|
||||||
|
border-radius: 1.5rem;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__body {
|
||||||
|
padding: 2rem 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host ::ng-deep .auth-title {
|
||||||
|
margin: 0;
|
||||||
|
color: #666666;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.auth-layout {
|
||||||
|
padding: 3rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__container {
|
||||||
|
padding-inline: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__row {
|
||||||
|
padding-block: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-layout__body {
|
||||||
|
padding: 3rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/app/core/layout/auth-layout/auth-layout.component.ts
Normal file
11
src/app/core/layout/auth-layout/auth-layout.component.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
||||||
|
import { RouterOutlet } from '@angular/router';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-auth-layout',
|
||||||
|
imports: [RouterOutlet],
|
||||||
|
templateUrl: './auth-layout.component.html',
|
||||||
|
styleUrl: './auth-layout.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
|
})
|
||||||
|
export class AuthLayoutComponent {}
|
||||||
@@ -44,6 +44,7 @@
|
|||||||
variant="user"
|
variant="user"
|
||||||
ariaLabel="Mi cuenta"
|
ariaLabel="Mi cuenta"
|
||||||
title="Mi cuenta"
|
title="Mi cuenta"
|
||||||
|
(click)="userClick.emit()"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ export class StoreHeaderComponent {
|
|||||||
readonly logoUrl = input<string | null>(null);
|
readonly logoUrl = input<string | null>(null);
|
||||||
readonly cartQuantity = input<number>(0);
|
readonly cartQuantity = input<number>(0);
|
||||||
readonly cartClick = output<void>();
|
readonly cartClick = output<void>();
|
||||||
|
readonly userClick = output<void>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
[cartQuantity]="cartQuantity()"
|
[cartQuantity]="cartQuantity()"
|
||||||
[logoUrl]="tenant()?.header_logo ?? null"
|
[logoUrl]="tenant()?.header_logo ?? null"
|
||||||
(cartClick)="isCartOpen.set(!isCartOpen())"
|
(cartClick)="isCartOpen.set(!isCartOpen())"
|
||||||
|
(userClick)="onUserClick()"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@if (isCartOpen()) {
|
@if (isCartOpen()) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { of } from 'rxjs';
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ import { Tenant } from '../../services/tenant.interface';
|
|||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { ToastService } from '../../services/toast.service';
|
import { ToastService } from '../../services/toast.service';
|
||||||
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { StoreLayoutComponent } from './store-layout.component';
|
import { StoreLayoutComponent } from './store-layout.component';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
@@ -60,6 +62,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
success: vi.fn(),
|
success: vi.fn(),
|
||||||
dismiss: vi.fn()
|
dismiss: vi.fn()
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: AuthService,
|
||||||
|
useValue: {
|
||||||
|
isAuthenticated: signal(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -98,4 +106,44 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('redirects to /login when user icon is clicked and user is not logged in', () => {
|
||||||
|
const authService = TestBed.inject(AuthService);
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
vi.spyOn(router, 'navigate');
|
||||||
|
|
||||||
|
// Set isAuthenticated to false
|
||||||
|
(authService.isAuthenticated as any).set(false);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
const userButton = compiled.querySelector('app-icon-button[variant="user"] button') as HTMLButtonElement;
|
||||||
|
expect(userButton).not.toBeNull();
|
||||||
|
userButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not redirect to /login when user icon is clicked and user is logged in', () => {
|
||||||
|
const authService = TestBed.inject(AuthService);
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
vi.spyOn(router, 'navigate');
|
||||||
|
|
||||||
|
// Set isAuthenticated to true
|
||||||
|
(authService.isAuthenticated as any).set(true);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
const userButton = compiled.querySelector('app-icon-button[variant="user"] button') as HTMLButtonElement;
|
||||||
|
expect(userButton).not.toBeNull();
|
||||||
|
userButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(router.navigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
||||||
import { RouterOutlet } from '@angular/router';
|
import { Router, RouterOutlet } from '@angular/router';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection, StoreSocialLink } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection, StoreSocialLink } from './store-footer/store-footer.component';
|
||||||
@@ -7,6 +7,7 @@ import { StoreHeaderComponent } from './store-header/store-header.component';
|
|||||||
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
|
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
|
||||||
import { ButtonComponent } from '../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../shared/components/button/button.component';
|
||||||
import { CartItem } from '../../services/cart/cart.interface';
|
import { CartItem } from '../../services/cart/cart.interface';
|
||||||
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -17,6 +18,8 @@ import { CartItem } from '../../services/cart/cart.interface';
|
|||||||
export class StoreLayoutComponent implements OnInit {
|
export class StoreLayoutComponent implements OnInit {
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
|
|
||||||
@@ -80,6 +83,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected onUserClick(): void {
|
||||||
|
if (!this.authService.isAuthenticated()) {
|
||||||
|
this.router.navigate(['/login']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
protected readonly footerSections: StoreFooterSection[] = [
|
protected readonly footerSections: StoreFooterSection[] = [
|
||||||
{
|
{
|
||||||
|
|||||||
9
src/app/core/services/auth/auth-bootstrap.ts
Normal file
9
src/app/core/services/auth/auth-bootstrap.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
export function authBootstrap(): Promise<void> {
|
||||||
|
const authService = inject(AuthService);
|
||||||
|
|
||||||
|
return authService.bootstrap();
|
||||||
|
}
|
||||||
62
src/app/core/services/auth/auth.guards.spec.ts
Normal file
62
src/app/core/services/auth/auth.guards.spec.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { computed, signal } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter, Router, UrlTree } from '@angular/router';
|
||||||
|
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { authGuard, guestOnlyGuard } from './auth.guards';
|
||||||
|
|
||||||
|
function createAuthServiceStub(isAuthenticated = false) {
|
||||||
|
const tokenState = signal<string | null>(isAuthenticated ? 'jwt-token' : null);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isAuthenticated: computed(() => tokenState() !== null)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('auth guards', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirects unauthenticated users to /login', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
|
||||||
|
|
||||||
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows authenticated users through authGuard', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirects authenticated users away from guest routes', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() => guestOnlyGuard(null as never, null as never));
|
||||||
|
|
||||||
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows guests into login/register routes', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() => guestOnlyGuard(null as never, null as never));
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
18
src/app/core/services/auth/auth.guards.ts
Normal file
18
src/app/core/services/auth/auth.guards.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
|
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
export const authGuard: CanActivateFn = () => {
|
||||||
|
const authService = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
|
||||||
|
return authService.isAuthenticated() ? true : router.createUrlTree(['/login']);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const guestOnlyGuard: CanActivateFn = () => {
|
||||||
|
const authService = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
|
||||||
|
return authService.isAuthenticated() ? router.createUrlTree(['/']) : true;
|
||||||
|
};
|
||||||
96
src/app/core/services/auth/auth.interceptor.spec.ts
Normal file
96
src/app/core/services/auth/auth.interceptor.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { computed, signal } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
|
||||||
|
import { environment } from '../../../../environments/environment';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { authInterceptor } from './auth.interceptor';
|
||||||
|
|
||||||
|
function createAuthServiceStub(token: string | null = null) {
|
||||||
|
const tokenState = signal(token);
|
||||||
|
|
||||||
|
return {
|
||||||
|
token: tokenState.asReadonly(),
|
||||||
|
isAuthenticated: computed(() => tokenState() !== null),
|
||||||
|
clearSession: vi.fn(() => tokenState.set(null))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('authInterceptor', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds the bearer token when a session exists', () => {
|
||||||
|
const authService = createAuthServiceStub('jwt-token');
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(withInterceptors([authInterceptor])),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{ provide: AuthService, useValue: authService }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = TestBed.inject(HttpClient);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
client.get(`${environment.url}me`).subscribe();
|
||||||
|
|
||||||
|
const request = httpController.expectOne(`${environment.url}me`);
|
||||||
|
expect(request.request.headers.get('Authorization')).toBe('Bearer jwt-token');
|
||||||
|
request.flush({ id: 1 });
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not add the authorization header when no token exists', () => {
|
||||||
|
const authService = createAuthServiceStub();
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(withInterceptors([authInterceptor])),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{ provide: AuthService, useValue: authService }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = TestBed.inject(HttpClient);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
client.get(`${environment.url}productos`).subscribe();
|
||||||
|
|
||||||
|
const request = httpController.expectOne(`${environment.url}productos`);
|
||||||
|
expect(request.request.headers.has('Authorization')).toBe(false);
|
||||||
|
request.flush([]);
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the local session when an authenticated request returns 401', () => {
|
||||||
|
const authService = createAuthServiceStub('expired-token');
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(withInterceptors([authInterceptor])),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{ provide: AuthService, useValue: authService }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = TestBed.inject(HttpClient);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
client.get(`${environment.url}me`).subscribe({
|
||||||
|
error: () => undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
const request = httpController.expectOne(`${environment.url}me`);
|
||||||
|
request.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||||
|
|
||||||
|
expect(authService.clearSession).toHaveBeenCalledTimes(1);
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
});
|
||||||
37
src/app/core/services/auth/auth.interceptor.ts
Normal file
37
src/app/core/services/auth/auth.interceptor.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import {
|
||||||
|
HttpErrorResponse,
|
||||||
|
HttpEvent,
|
||||||
|
HttpHandlerFn,
|
||||||
|
HttpInterceptorFn,
|
||||||
|
HttpRequest
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { Observable, catchError, throwError } from 'rxjs';
|
||||||
|
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
export const authInterceptor: HttpInterceptorFn = (
|
||||||
|
request: HttpRequest<unknown>,
|
||||||
|
next: HttpHandlerFn
|
||||||
|
): Observable<HttpEvent<unknown>> => {
|
||||||
|
const authService = inject(AuthService);
|
||||||
|
const token = authService.token();
|
||||||
|
|
||||||
|
const authenticatedRequest = token
|
||||||
|
? request.clone({
|
||||||
|
setHeaders: {
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
: request;
|
||||||
|
|
||||||
|
return next(authenticatedRequest).pipe(
|
||||||
|
catchError((error: unknown) => {
|
||||||
|
if (error instanceof HttpErrorResponse && error.status === 401 && token) {
|
||||||
|
authService.clearSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
return throwError(() => error);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
29
src/app/core/services/auth/auth.interfaces.ts
Normal file
29
src/app/core/services/auth/auth.interfaces.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
export interface AuthUser {
|
||||||
|
id: number;
|
||||||
|
nombre_apellido: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginPayload {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterPayload {
|
||||||
|
nombre_apellido: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
password_confirmation: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResponse {
|
||||||
|
message: string;
|
||||||
|
token: string;
|
||||||
|
token_type: 'Bearer';
|
||||||
|
user: AuthUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterResponse {
|
||||||
|
message: string;
|
||||||
|
data: AuthUser;
|
||||||
|
}
|
||||||
188
src/app/core/services/auth/auth.service.spec.ts
Normal file
188
src/app/core/services/auth/auth.service.spec.ts
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
import { PLATFORM_ID } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
|
||||||
|
import { environment } from '../../../../environments/environment';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
describe('AuthService', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores token and user on successful login', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
service.login({ email: 'ada@example.com', password: 'secret123' }).subscribe((user) => {
|
||||||
|
expect(user.email).toBe('ada@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
const request = httpController.expectOne(`${environment.url}login`);
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
request.flush({
|
||||||
|
message: 'Sesion iniciada correctamente.',
|
||||||
|
token: 'plain-text-token',
|
||||||
|
token_type: 'Bearer',
|
||||||
|
user: {
|
||||||
|
id: 1,
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.token()).toBe('plain-text-token');
|
||||||
|
expect(service.user()?.email).toBe('ada@example.com');
|
||||||
|
expect(service.isAuthenticated()).toBe(true);
|
||||||
|
expect(window.localStorage.getItem('shopit.auth.token')).toBe('plain-text-token');
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hydrates token from localStorage and loads the current user during bootstrap', async () => {
|
||||||
|
window.localStorage.setItem('shopit.auth.token', 'persisted-token');
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
const bootstrapPromise = service.bootstrap();
|
||||||
|
const request = httpController.expectOne(`${environment.url}me`);
|
||||||
|
|
||||||
|
expect(request.request.method).toBe('GET');
|
||||||
|
request.flush({
|
||||||
|
id: 9,
|
||||||
|
nombre_apellido: 'Grace Hopper',
|
||||||
|
email: 'grace@example.com'
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(bootstrapPromise).resolves.toBeUndefined();
|
||||||
|
expect(service.user()?.email).toBe('grace@example.com');
|
||||||
|
expect(service.isAuthenticated()).toBe(true);
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the session when bootstrap receives 401 from /me', async () => {
|
||||||
|
window.localStorage.setItem('shopit.auth.token', 'expired-token');
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
const bootstrapPromise = service.bootstrap();
|
||||||
|
const request = httpController.expectOne(`${environment.url}me`);
|
||||||
|
|
||||||
|
request.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||||
|
|
||||||
|
await expect(bootstrapPromise).resolves.toBeUndefined();
|
||||||
|
expect(service.user()).toBeNull();
|
||||||
|
expect(service.token()).toBeNull();
|
||||||
|
expect(service.isAuthenticated()).toBe(false);
|
||||||
|
expect(window.localStorage.getItem('shopit.auth.token')).toBeNull();
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('registers without creating a session', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
service
|
||||||
|
.register({
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123',
|
||||||
|
password_confirmation: 'secret123'
|
||||||
|
})
|
||||||
|
.subscribe((response) => {
|
||||||
|
expect(response.data.email).toBe('ada@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
const request = httpController.expectOne(`${environment.url}register`);
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
request.flush({
|
||||||
|
message: 'Usuario registrado correctamente.',
|
||||||
|
data: {
|
||||||
|
id: 1,
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.token()).toBeNull();
|
||||||
|
expect(service.user()).toBeNull();
|
||||||
|
expect(service.isAuthenticated()).toBe(false);
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears local session even when logout request fails', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
service.login({ email: 'ada@example.com', password: 'secret123' }).subscribe();
|
||||||
|
httpController.expectOne(`${environment.url}login`).flush({
|
||||||
|
message: 'Sesion iniciada correctamente.',
|
||||||
|
token: 'plain-text-token',
|
||||||
|
token_type: 'Bearer',
|
||||||
|
user: {
|
||||||
|
id: 1,
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
service.logout().subscribe({
|
||||||
|
error: () => undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
const logoutRequest = httpController.expectOne(`${environment.url}logout`);
|
||||||
|
expect(logoutRequest.request.method).toBe('POST');
|
||||||
|
logoutRequest.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||||
|
|
||||||
|
expect(service.token()).toBeNull();
|
||||||
|
expect(service.user()).toBeNull();
|
||||||
|
expect(window.localStorage.getItem('shopit.auth.token')).toBeNull();
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not access localStorage on the server', () => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
AuthService,
|
||||||
|
{ provide: PLATFORM_ID, useValue: 'server' }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
|
||||||
|
service.hydrateSession();
|
||||||
|
|
||||||
|
expect(service.token()).toBeNull();
|
||||||
|
expect(service.isAuthenticated()).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
115
src/app/core/services/auth/auth.service.ts
Normal file
115
src/app/core/services/auth/auth.service.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { isPlatformBrowser } from '@angular/common';
|
||||||
|
import { computed, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
||||||
|
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
||||||
|
|
||||||
|
import { environment } from '../../../../environments/environment';
|
||||||
|
import {
|
||||||
|
AuthUser,
|
||||||
|
LoginPayload,
|
||||||
|
LoginResponse,
|
||||||
|
RegisterPayload,
|
||||||
|
RegisterResponse
|
||||||
|
} from './auth.interfaces';
|
||||||
|
|
||||||
|
const AUTH_TOKEN_STORAGE_KEY = 'shopit.auth.token';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class AuthService {
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
|
|
||||||
|
private readonly userState = signal<AuthUser | null>(null);
|
||||||
|
private readonly tokenState = signal<string | null>(null);
|
||||||
|
|
||||||
|
readonly user = this.userState.asReadonly();
|
||||||
|
readonly token = this.tokenState.asReadonly();
|
||||||
|
readonly isAuthenticated = computed(() => this.tokenState() !== null);
|
||||||
|
|
||||||
|
login(payload: LoginPayload): Observable<AuthUser> {
|
||||||
|
return this.http.post<LoginResponse>(`${environment.url}login`, payload).pipe(
|
||||||
|
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
|
||||||
|
map((response) => response.user)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
register(payload: RegisterPayload): Observable<RegisterResponse> {
|
||||||
|
return this.http.post<RegisterResponse>(`${environment.url}register`, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
logout(): Observable<void> {
|
||||||
|
if (!this.tokenState()) {
|
||||||
|
this.clearSession();
|
||||||
|
return of(void 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.http.post<void>(`${environment.url}logout`, {}).pipe(
|
||||||
|
tap({
|
||||||
|
next: () => this.clearSession(),
|
||||||
|
error: () => this.clearSession()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bootstrap(): Promise<void> {
|
||||||
|
this.hydrateSession();
|
||||||
|
|
||||||
|
if (!this.tokenState() || this.userState()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await firstValueFrom(this.loadCurrentUser());
|
||||||
|
} catch (error) {
|
||||||
|
if (this.isUnauthorizedError(error)) {
|
||||||
|
this.clearSession();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadCurrentUser(): Observable<AuthUser> {
|
||||||
|
return this.http.get<AuthUser>(`${environment.url}me`).pipe(
|
||||||
|
tap((user) => this.userState.set(user))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
hydrateSession(): void {
|
||||||
|
if (!isPlatformBrowser(this.platformId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);
|
||||||
|
this.tokenState.set(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearSession(): void {
|
||||||
|
this.userState.set(null);
|
||||||
|
this.tokenState.set(null);
|
||||||
|
|
||||||
|
if (!isPlatformBrowser(this.platformId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyAuthenticatedState(token: string, user: AuthUser): void {
|
||||||
|
this.tokenState.set(token);
|
||||||
|
this.userState.set(user);
|
||||||
|
|
||||||
|
if (!isPlatformBrowser(this.platformId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isUnauthorizedError(error: unknown): error is HttpErrorResponse {
|
||||||
|
return error instanceof HttpErrorResponse && error.status === 401;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
import {
|
import {
|
||||||
MODAL_DATA,
|
MODAL_DATA,
|
||||||
ModalRef,
|
ModalRef,
|
||||||
@@ -212,6 +213,41 @@ describe('ModalService', () => {
|
|||||||
showCloseButton: false
|
showCloseButton: false
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the simple modal with default button label', () => {
|
||||||
|
service.openSimple({
|
||||||
|
title: 'Aviso',
|
||||||
|
content: 'Este es un aviso simple.'
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeModal = service.activeModal();
|
||||||
|
|
||||||
|
expect(activeModal?.component).toBe(SimpleModalComponent);
|
||||||
|
expect(activeModal?.config).toEqual({
|
||||||
|
title: 'Aviso',
|
||||||
|
data: {
|
||||||
|
content: 'Este es un aviso simple.',
|
||||||
|
buttonLabel: 'Entendido'
|
||||||
|
},
|
||||||
|
size: 'md',
|
||||||
|
closeOnBackdrop: true,
|
||||||
|
closeOnEscape: true,
|
||||||
|
showCloseButton: true
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps the simple modal close result to undefined', async () => {
|
||||||
|
const result$ = service.openSimple({
|
||||||
|
title: 'Aviso',
|
||||||
|
content: 'Este es un aviso simple.'
|
||||||
|
});
|
||||||
|
const activeModal = service.activeModal();
|
||||||
|
const resultPromise = firstValueFrom(result$);
|
||||||
|
|
||||||
|
activeModal?.ref.close();
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { InjectionToken, Injectable, Type, signal } from '@angular/core';
|
|||||||
import { Observable, Subject, map } from 'rxjs';
|
import { Observable, Subject, map } from 'rxjs';
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
|
|
||||||
export type ModalSize = 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
export type ModalSize = 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||||
export type ModalDismissReason =
|
export type ModalDismissReason =
|
||||||
@@ -43,6 +44,17 @@ export interface ConfirmModalConfig
|
|||||||
cancelLabel?: string;
|
cancelLabel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SimpleModalData {
|
||||||
|
content: string;
|
||||||
|
buttonLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SimpleModalConfig
|
||||||
|
extends Omit<ModalConfig<SimpleModalData>, 'data'> {
|
||||||
|
content: string;
|
||||||
|
buttonLabel?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
||||||
component: Type<unknown>;
|
component: Type<unknown>;
|
||||||
config: NormalizedModalConfig<TData>;
|
config: NormalizedModalConfig<TData>;
|
||||||
@@ -158,6 +170,19 @@ export class ModalService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
openSimple(config: SimpleModalConfig): Observable<void> {
|
||||||
|
return this.openSimpleRef(config).afterClosed$.pipe(
|
||||||
|
map(() => undefined)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
openSimpleRef(config: SimpleModalConfig): ModalRef<void> {
|
||||||
|
return this.open(
|
||||||
|
SimpleModalComponent,
|
||||||
|
this.buildSimpleModalConfig(config)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
||||||
if (this.activeModalState()?.ref !== ref) {
|
if (this.activeModalState()?.ref !== ref) {
|
||||||
return;
|
return;
|
||||||
@@ -207,4 +232,22 @@ export class ModalService {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private buildSimpleModalConfig(
|
||||||
|
config: SimpleModalConfig
|
||||||
|
): ModalConfig<SimpleModalData> {
|
||||||
|
const {
|
||||||
|
content,
|
||||||
|
buttonLabel = 'Entendido',
|
||||||
|
...modalConfig
|
||||||
|
} = config;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...modalConfig,
|
||||||
|
data: {
|
||||||
|
content,
|
||||||
|
buttonLabel
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -91,6 +91,9 @@
|
|||||||
<app-button variant="danger-secondary" (click)="openWideModal()">
|
<app-button variant="danger-secondary" (click)="openWideModal()">
|
||||||
Abrir modal ancho
|
Abrir modal ancho
|
||||||
</app-button>
|
</app-button>
|
||||||
|
<app-button (click)="openSimpleModal()">
|
||||||
|
Abrir simple modal
|
||||||
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-showcase__result" data-testid="modal-last-result">
|
<div class="modal-showcase__result" data-testid="modal-last-result">
|
||||||
{{ lastModalResult }}
|
{{ lastModalResult }}
|
||||||
|
|||||||
@@ -186,9 +186,61 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
).toContain('Todavia no se abrio ningun modal.');
|
).toContain('Todavia no se abrio ningun modal.');
|
||||||
|
|
||||||
confirmButton.click();
|
confirmButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
deleteButton.click();
|
deleteButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(modalServiceStub.openConfirm).toHaveBeenCalled();
|
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
||||||
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalled();
|
title: 'Confirmar accion',
|
||||||
|
content: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
||||||
|
confirmLabel: 'Confirmar'
|
||||||
|
});
|
||||||
|
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalledWith({
|
||||||
|
title: 'Eliminar producto',
|
||||||
|
content:
|
||||||
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
|
confirmLabel: 'Eliminar'
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
element.querySelector('[data-testid="modal-last-result"]')?.textContent
|
||||||
|
).toContain('Resultado: false');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates the visible result when the confirm modal resolves to true', async () => {
|
||||||
|
const modalServiceStub = createModalServiceStub();
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [ReutilizablesTestPageComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: createTenantServiceStub(tenant)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ToastService,
|
||||||
|
useValue: createToastServiceStub()
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalService,
|
||||||
|
useValue: modalServiceStub
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(ReutilizablesTestPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const confirmButton = Array.from(
|
||||||
|
element.querySelectorAll('.button-group app-button button')
|
||||||
|
).find((button) =>
|
||||||
|
button.textContent?.includes('Abrir confirm modal')
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
|
confirmButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
element.querySelector('[data-testid="modal-last-result"]')?.textContent
|
||||||
|
).toContain('Resultado: true');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -198,14 +198,11 @@ export class ReutilizablesTestPageComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected openConfirmDeleteModal(): void {
|
protected openConfirmDeleteModal(): void {
|
||||||
this.modalService.openConfirmDelete({
|
this.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
content:
|
content:
|
||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar'
|
||||||
cancelLabel: 'Conservar'
|
|
||||||
}).subscribe((confirmed) => {
|
|
||||||
this.lastModalResult = `Resultado: ${confirmed}`;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,9 +226,27 @@ export class ReutilizablesTestPageComponent {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openSimpleModal(): void {
|
||||||
|
this.modalService.openSimple({
|
||||||
|
title: 'Mensaje del sistema',
|
||||||
|
content: 'Este es un mensaje simple del sistema que no requiere confirmación.',
|
||||||
|
buttonLabel: 'Entendido'
|
||||||
|
}).subscribe(() => {
|
||||||
|
this.lastModalResult = 'Simple modal cerrado';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
||||||
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
||||||
this.lastModalResult = `Resultado: ${confirmed}`;
|
this.lastModalResult = `Resultado: ${confirmed}`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private openConfirmDelete(
|
||||||
|
config: Parameters<ModalService['openConfirmDelete']>[0]
|
||||||
|
): void {
|
||||||
|
this.modalService.openConfirmDelete(config).subscribe((confirmed) => {
|
||||||
|
this.lastModalResult = `Resultado: ${confirmed}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
<header class="login-page__header text-center mb-2">
|
||||||
|
<h1 id="login-title" class="auth-title mb-3">Iniciar sesion</h1>
|
||||||
|
@if (serverError(); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<form
|
||||||
|
class="login-page__form d-grid gap-3"
|
||||||
|
novalidate
|
||||||
|
aria-labelledby="login-title"
|
||||||
|
[formGroup]="form"
|
||||||
|
(ngSubmit)="onSubmit()"
|
||||||
|
>
|
||||||
|
<div class="d-grid gap-3">
|
||||||
|
<label class="visually-hidden" for="login-email">Email</label>
|
||||||
|
<app-input
|
||||||
|
id="login-email"
|
||||||
|
type="email"
|
||||||
|
placeholder="Email"
|
||||||
|
[value]="form.controls.email.value"
|
||||||
|
[invalid]="showControlError('email')"
|
||||||
|
(valueChange)="updateEmail($event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('email'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="d-grid gap-1">
|
||||||
|
<label class="visually-hidden" for="login-password">Contrasena</label>
|
||||||
|
<app-input
|
||||||
|
id="login-password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Contrasena"
|
||||||
|
[value]="form.controls.password.value"
|
||||||
|
[invalid]="showControlError('password')"
|
||||||
|
(valueChange)="updatePassword($event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('password'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
<div class="text-end">
|
||||||
|
<button type="button" class="login-page__forgot-password btn btn-link p-0 border-0 text-decoration-none">
|
||||||
|
Olvide mi contrasena
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-grid gap-2 text-center">
|
||||||
|
<app-button
|
||||||
|
type="submit"
|
||||||
|
hostClass="w-100 d-block"
|
||||||
|
buttonClass="w-100"
|
||||||
|
[disabled]="isSubmitting()"
|
||||||
|
>
|
||||||
|
{{ isSubmitting() ? 'Ingresando...' : 'Ingresar' }}
|
||||||
|
</app-button>
|
||||||
|
|
||||||
|
<app-button
|
||||||
|
type="button"
|
||||||
|
variant="borderless"
|
||||||
|
hostClass="w-100 d-block text-center"
|
||||||
|
buttonClass="login-page__create-account px-3 py-2"
|
||||||
|
[disabled]="isSubmitting()"
|
||||||
|
(click)="goToRegister()"
|
||||||
|
>
|
||||||
|
Crear cuenta
|
||||||
|
</app-button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="login-page__divider d-flex align-items-center justify-content-center gap-3 my-4" aria-hidden="true">
|
||||||
|
<span class="login-page__divider-line flex-grow-1"></span>
|
||||||
|
<span class="login-page__divider-dot rounded-circle border flex-shrink-0"></span>
|
||||||
|
<span class="login-page__divider-line flex-grow-1"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<app-button
|
||||||
|
type="button"
|
||||||
|
variant="neutral-outline"
|
||||||
|
hostClass="w-100 d-block"
|
||||||
|
buttonClass="w-100 d-inline-flex align-items-center justify-content-center gap-2 py-2 fw-semibold"
|
||||||
|
[disabled]="true"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
viewBox="0 0 48 48"
|
||||||
|
width="18"
|
||||||
|
height="18"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
fill="#FFC107"
|
||||||
|
d="M43.61 20.08H42V20H24v8h11.3C33.65 32.66 29.19 36 24 36c-6.63 0-12-5.37-12-12s5.37-12 12-12c3.06 0 5.84 1.15 7.96 3.04l5.66-5.66C34.09 6.05 29.3 4 24 4C12.95 4 4 12.95 4 24s8.95 20 20 20s20-8.95 20-20c0-1.34-.14-2.65-.39-3.92z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#FF3D00"
|
||||||
|
d="M6.31 14.69l6.57 4.82C14.66 15.1 18.96 12 24 12c3.06 0 5.84 1.15 7.96 3.04l5.66-5.66C34.09 6.05 29.3 4 24 4C16.32 4 9.66 8.34 6.31 14.69z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#4CAF50"
|
||||||
|
d="M24 44c5.2 0 9.9-1.99 13.47-5.23l-6.19-5.24C29.2 35.11 26.72 36 24 36c-5.17 0-9.62-3.32-11.28-7.95l-6.52 5.02C9.51 39.56 16.24 44 24 44z"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
fill="#1976D2"
|
||||||
|
d="M43.61 20.08H42V20H24v8h11.3c-.79 2.37-2.31 4.38-4.28 5.53l.01-.01l6.19 5.24C36.78 39.13 44 34 44 24c0-1.34-.14-2.65-.39-3.92z"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
<span>Continuar con Google</span>
|
||||||
|
</app-button>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__header {
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__form {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__forgot-password {
|
||||||
|
color: #a0a0a0;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 325;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__create-account {
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__divider {
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__divider-line {
|
||||||
|
max-width: 18rem;
|
||||||
|
height: 1px;
|
||||||
|
background-color: #d9d9d9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-page__divider-dot {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border-color: #d9d9d9 !important;
|
||||||
|
background-color: #ffffff;
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
|
||||||
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import { LoginPageComponent } from './login-page.component';
|
||||||
|
|
||||||
|
describe('LoginPageComponent', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('submits credentials and navigates to home on success', async () => {
|
||||||
|
const authService = {
|
||||||
|
login: vi.fn().mockReturnValue(
|
||||||
|
of({
|
||||||
|
id: 1,
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [LoginPageComponent],
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123'
|
||||||
|
});
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(authService.login).toHaveBeenCalledWith({
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123'
|
||||||
|
});
|
||||||
|
expect(navigateSpy).toHaveBeenCalledWith(['/']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('surfaces backend login errors', async () => {
|
||||||
|
const authService = {
|
||||||
|
login: vi.fn().mockReturnValue(
|
||||||
|
throwError(() => ({
|
||||||
|
error: {
|
||||||
|
errors: {
|
||||||
|
email: ['Las credenciales son invalidas.']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [LoginPageComponent],
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'wrong-password'
|
||||||
|
});
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(component.serverError()).toBe('Las credenciales son invalidas.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates email length and password minimum length before submit', async () => {
|
||||||
|
const authService = {
|
||||||
|
login: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [LoginPageComponent],
|
||||||
|
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
email: `${'a'.repeat(250)}@example.com`,
|
||||||
|
password: '1234567'
|
||||||
|
});
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(authService.login).not.toHaveBeenCalled();
|
||||||
|
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
||||||
|
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
||||||
|
});
|
||||||
|
});
|
||||||
122
src/app/features/store/pages/login-page/login-page.component.ts
Normal file
122
src/app/features/store/pages/login-page/login-page.component.ts
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||||
|
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||||
|
|
||||||
|
const PASSWORD_MIN_LENGTH = 8;
|
||||||
|
const EMAIL_MAX_LENGTH = 255;
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-login-page',
|
||||||
|
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
||||||
|
templateUrl: './login-page.component.html',
|
||||||
|
styleUrl: './login-page.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
|
})
|
||||||
|
export class LoginPageComponent {
|
||||||
|
private readonly formBuilder = inject(FormBuilder);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly authService = inject(AuthService);
|
||||||
|
|
||||||
|
private readonly submittedState = signal(false);
|
||||||
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
|
private readonly isSubmittingState = signal(false);
|
||||||
|
|
||||||
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
|
email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]],
|
||||||
|
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]]
|
||||||
|
});
|
||||||
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
|
|
||||||
|
goToRegister(): void {
|
||||||
|
void this.router.navigate(['/register']);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
this.submittedState.set(true);
|
||||||
|
this.serverErrorState.set(null);
|
||||||
|
|
||||||
|
if (this.form.invalid) {
|
||||||
|
this.form.markAllAsTouched();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isSubmittingState.set(true);
|
||||||
|
|
||||||
|
this.authService.login(this.form.getRawValue()).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.isSubmittingState.set(false);
|
||||||
|
void this.router.navigate(['/']);
|
||||||
|
},
|
||||||
|
error: (error: unknown) => {
|
||||||
|
this.isSubmittingState.set(false);
|
||||||
|
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected updateEmail(value: string | number): void {
|
||||||
|
this.form.controls.email.setValue(String(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected updatePassword(value: string | number): void {
|
||||||
|
this.form.controls.password.setValue(String(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected showControlError(controlName: 'email' | 'password'): boolean {
|
||||||
|
const control = this.form.controls[controlName];
|
||||||
|
|
||||||
|
return control.invalid && (control.touched || this.submitted());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getControlError(controlName: 'email' | 'password'): string | null {
|
||||||
|
const control = this.form.controls[controlName];
|
||||||
|
|
||||||
|
if (!this.showControlError(controlName)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('required')) {
|
||||||
|
return 'Este campo es obligatorio.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('maxlength')) {
|
||||||
|
return `No puede superar los ${EMAIL_MAX_LENGTH} caracteres.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('email')) {
|
||||||
|
return 'Ingresa un email valido.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('minlength')) {
|
||||||
|
return `Debe tener al menos ${PASSWORD_MIN_LENGTH} caracteres.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'El valor ingresado no es valido.';
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveErrorMessage(error: unknown): string {
|
||||||
|
const errorPayload =
|
||||||
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
|
? (error as { error?: { errors?: Record<string, string[]>; message?: string } }).error
|
||||||
|
: undefined;
|
||||||
|
const apiErrors = errorPayload?.errors;
|
||||||
|
const emailMessages = apiErrors?.['email'];
|
||||||
|
const emailError = Array.isArray(emailMessages) ? emailMessages[0] : null;
|
||||||
|
|
||||||
|
if (typeof emailError === 'string' && emailError.trim()) {
|
||||||
|
return emailError;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof errorPayload?.message === 'string' && errorPayload.message.trim()) {
|
||||||
|
return errorPayload.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'No se pudo iniciar sesion. Intenta nuevamente.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<header class="register-page__header text-center mb-4">
|
||||||
|
<h1 id="register-title" class="auth-title">CREAR CUENTA</h1>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<form
|
||||||
|
class="register-page__form d-grid gap-3"
|
||||||
|
novalidate
|
||||||
|
aria-labelledby="register-title"
|
||||||
|
[formGroup]="form"
|
||||||
|
(ngSubmit)="onSubmit()"
|
||||||
|
>
|
||||||
|
<div class="d-grid gap-3">
|
||||||
|
<label class="visually-hidden" for="register-full-name">Nombre y Apellido</label>
|
||||||
|
<app-input
|
||||||
|
id="register-full-name"
|
||||||
|
placeholder="Nombre y Apellido"
|
||||||
|
[value]="form.controls.nombre_apellido.value"
|
||||||
|
[invalid]="showControlError('nombre_apellido')"
|
||||||
|
(valueChange)="updateField('nombre_apellido', $event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('nombre_apellido'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
|
||||||
|
<label class="visually-hidden" for="register-email">Email</label>
|
||||||
|
<app-input
|
||||||
|
id="register-email"
|
||||||
|
type="email"
|
||||||
|
placeholder="Email"
|
||||||
|
[value]="form.controls.email.value"
|
||||||
|
[invalid]="showControlError('email')"
|
||||||
|
(valueChange)="updateField('email', $event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('email'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
|
||||||
|
<label class="visually-hidden" for="register-password">Contrasena</label>
|
||||||
|
<app-input
|
||||||
|
id="register-password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Contrasena"
|
||||||
|
[value]="form.controls.password.value"
|
||||||
|
[invalid]="showControlError('password')"
|
||||||
|
(valueChange)="updateField('password', $event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('password'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
|
||||||
|
<label class="visually-hidden" for="register-password-repeat">Repetir Contrasena</label>
|
||||||
|
<app-input
|
||||||
|
id="register-password-repeat"
|
||||||
|
type="password"
|
||||||
|
placeholder="Repetir Contrasena"
|
||||||
|
[value]="form.controls.password_confirmation.value"
|
||||||
|
[invalid]="showControlError('password_confirmation')"
|
||||||
|
(valueChange)="updateField('password_confirmation', $event)"
|
||||||
|
/>
|
||||||
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="d-grid gap-2 text-center">
|
||||||
|
@if (serverError(); as errorMessage) {
|
||||||
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
}
|
||||||
|
<app-button
|
||||||
|
type="submit"
|
||||||
|
hostClass="w-100 d-block"
|
||||||
|
buttonClass="w-100"
|
||||||
|
[disabled]="isSubmitting()"
|
||||||
|
>
|
||||||
|
{{ isSubmitting() ? 'Creando cuenta...' : 'Crear Cuenta' }}
|
||||||
|
</app-button>
|
||||||
|
<app-button
|
||||||
|
type="button"
|
||||||
|
variant="borderless"
|
||||||
|
hostClass="w-100 d-block text-center"
|
||||||
|
buttonClass="register-page__back-action px-3 py-2"
|
||||||
|
[disabled]="isSubmitting()"
|
||||||
|
(click)="goToLogin()"
|
||||||
|
>
|
||||||
|
Volver
|
||||||
|
</app-button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.register-page__header {
|
||||||
|
}
|
||||||
|
|
||||||
|
.register-page__form {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.register-page__back-action {
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
|
||||||
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import { ModalService } from '../../../../core/services/modal.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
|
import { RegisterPageComponent } from './register-page.component';
|
||||||
|
|
||||||
|
describe('RegisterPageComponent', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('submits registration data and redirects to /login on success', async () => {
|
||||||
|
const authService = {
|
||||||
|
register: vi.fn().mockReturnValue(
|
||||||
|
of({
|
||||||
|
message: 'Usuario registrado correctamente.',
|
||||||
|
data: {
|
||||||
|
id: 1,
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
};
|
||||||
|
const modalService = {
|
||||||
|
openSimple: vi.fn().mockReturnValue(of(undefined))
|
||||||
|
};
|
||||||
|
const toastService = {
|
||||||
|
danger: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [RegisterPageComponent],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AuthService, useValue: authService },
|
||||||
|
{ provide: ModalService, useValue: modalService },
|
||||||
|
{ provide: ToastService, useValue: toastService }
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123',
|
||||||
|
password_confirmation: 'secret123'
|
||||||
|
});
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(authService.register).toHaveBeenCalledWith({
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123',
|
||||||
|
password_confirmation: 'secret123'
|
||||||
|
});
|
||||||
|
expect(modalService.openSimple).toHaveBeenCalledWith({
|
||||||
|
content: 'Tu cuenta fue creada correctamente',
|
||||||
|
buttonLabel: 'Cerrar'
|
||||||
|
});
|
||||||
|
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a mismatch message when passwords do not match', async () => {
|
||||||
|
const authService = {
|
||||||
|
register: vi.fn()
|
||||||
|
};
|
||||||
|
const modalService = {
|
||||||
|
openSimple: vi.fn()
|
||||||
|
};
|
||||||
|
const toastService = {
|
||||||
|
danger: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [RegisterPageComponent],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AuthService, useValue: authService },
|
||||||
|
{ provide: ModalService, useValue: modalService },
|
||||||
|
{ provide: ToastService, useValue: toastService }
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123',
|
||||||
|
password_confirmation: 'different'
|
||||||
|
});
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(authService.register).not.toHaveBeenCalled();
|
||||||
|
expect(component.getControlError('password_confirmation')).toBe('Las contrasenas no coinciden.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates max length and password minimum length before submit', async () => {
|
||||||
|
const authService = {
|
||||||
|
register: vi.fn()
|
||||||
|
};
|
||||||
|
const modalService = {
|
||||||
|
openSimple: vi.fn()
|
||||||
|
};
|
||||||
|
const toastService = {
|
||||||
|
danger: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [RegisterPageComponent],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AuthService, useValue: authService },
|
||||||
|
{ provide: ModalService, useValue: modalService },
|
||||||
|
{ provide: ToastService, useValue: toastService }
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
nombre_apellido: 'A'.repeat(256),
|
||||||
|
email: `${'a'.repeat(250)}@example.com`,
|
||||||
|
password: '1234567',
|
||||||
|
password_confirmation: '1234567'
|
||||||
|
});
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(authService.register).not.toHaveBeenCalled();
|
||||||
|
expect(component.getControlError('nombre_apellido')).toBe('No puede superar los 255 caracteres.');
|
||||||
|
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
||||||
|
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('surfaces backend register errors', async () => {
|
||||||
|
const authService = {
|
||||||
|
register: vi.fn().mockReturnValue(
|
||||||
|
throwError(() => ({
|
||||||
|
error: {
|
||||||
|
errors: {
|
||||||
|
email: ['El email ya esta en uso.']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
};
|
||||||
|
const modalService = {
|
||||||
|
openSimple: vi.fn()
|
||||||
|
};
|
||||||
|
const toastService = {
|
||||||
|
danger: vi.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [RegisterPageComponent],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AuthService, useValue: authService },
|
||||||
|
{ provide: ModalService, useValue: modalService },
|
||||||
|
{ provide: ToastService, useValue: toastService }
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||||
|
const component = fixture.componentInstance as any;
|
||||||
|
|
||||||
|
component.form.setValue({
|
||||||
|
nombre_apellido: 'Ada Lovelace',
|
||||||
|
email: 'ada@example.com',
|
||||||
|
password: 'secret123',
|
||||||
|
password_confirmation: 'secret123'
|
||||||
|
});
|
||||||
|
component.onSubmit();
|
||||||
|
|
||||||
|
expect(component.serverError()).toBe('El email ya esta en uso.');
|
||||||
|
expect(toastService.danger).toHaveBeenCalledWith('El email ya esta en uso.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||||
|
import {
|
||||||
|
AbstractControl,
|
||||||
|
FormBuilder,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
ValidationErrors,
|
||||||
|
ValidatorFn,
|
||||||
|
Validators
|
||||||
|
} from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import { ModalService } from '../../../../core/services/modal.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||||
|
|
||||||
|
const PASSWORD_MIN_LENGTH = 8;
|
||||||
|
const TEXT_MAX_LENGTH = 255;
|
||||||
|
|
||||||
|
const passwordsMatchValidator: ValidatorFn = (
|
||||||
|
control: AbstractControl
|
||||||
|
): ValidationErrors | null => {
|
||||||
|
const password = control.get('password')?.value;
|
||||||
|
const passwordConfirmation = control.get('password_confirmation')?.value;
|
||||||
|
|
||||||
|
if (!password || !passwordConfirmation) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return password === passwordConfirmation ? null : { passwordMismatch: true };
|
||||||
|
};
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-register-page',
|
||||||
|
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
||||||
|
templateUrl: './register-page.component.html',
|
||||||
|
styleUrl: './register-page.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
|
})
|
||||||
|
export class RegisterPageComponent {
|
||||||
|
private readonly formBuilder = inject(FormBuilder);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly modalService = inject(ModalService);
|
||||||
|
private readonly toastService = inject(ToastService);
|
||||||
|
|
||||||
|
private readonly submittedState = signal(false);
|
||||||
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
|
private readonly isSubmittingState = signal(false);
|
||||||
|
|
||||||
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
|
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
||||||
|
email: [
|
||||||
|
'',
|
||||||
|
[Validators.required, Validators.email, Validators.maxLength(TEXT_MAX_LENGTH)]
|
||||||
|
],
|
||||||
|
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]],
|
||||||
|
password_confirmation: ['', [Validators.required]]
|
||||||
|
}, {
|
||||||
|
validators: [passwordsMatchValidator]
|
||||||
|
});
|
||||||
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
|
|
||||||
|
goToLogin(): void {
|
||||||
|
void this.router.navigate(['/login']);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
this.submittedState.set(true);
|
||||||
|
this.serverErrorState.set(null);
|
||||||
|
|
||||||
|
if (this.form.invalid) {
|
||||||
|
this.form.markAllAsTouched();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isSubmittingState.set(true);
|
||||||
|
|
||||||
|
this.authService.register(this.form.getRawValue()).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.isSubmittingState.set(false);
|
||||||
|
this.modalService.openSimple({
|
||||||
|
content: 'Tu cuenta fue creada correctamente',
|
||||||
|
buttonLabel: 'Cerrar'
|
||||||
|
}).subscribe(() => {
|
||||||
|
void this.router.navigate(['/login']);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
error: (error: unknown) => {
|
||||||
|
this.isSubmittingState.set(false);
|
||||||
|
const errorMessage = this.resolveErrorMessage(error);
|
||||||
|
this.serverErrorState.set(errorMessage);
|
||||||
|
this.toastService.danger(errorMessage);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected updateField(
|
||||||
|
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation',
|
||||||
|
value: string | number
|
||||||
|
): void {
|
||||||
|
this.form.controls[controlName].setValue(String(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected showControlError(
|
||||||
|
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation'
|
||||||
|
): boolean {
|
||||||
|
const control = this.form.controls[controlName];
|
||||||
|
const hasPasswordMismatch =
|
||||||
|
controlName === 'password_confirmation' &&
|
||||||
|
this.form.hasError('passwordMismatch') &&
|
||||||
|
(control.touched || this.submitted());
|
||||||
|
|
||||||
|
return (control.invalid && (control.touched || this.submitted())) || hasPasswordMismatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected getControlError(
|
||||||
|
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation'
|
||||||
|
): string | null {
|
||||||
|
const control = this.form.controls[controlName];
|
||||||
|
|
||||||
|
if (!this.showControlError(controlName)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('required')) {
|
||||||
|
return 'Este campo es obligatorio.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('maxlength')) {
|
||||||
|
return `No puede superar los ${TEXT_MAX_LENGTH} caracteres.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('email')) {
|
||||||
|
return 'Ingresa un email valido.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (control.hasError('minlength')) {
|
||||||
|
return `Debe tener al menos ${PASSWORD_MIN_LENGTH} caracteres.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (controlName === 'password_confirmation' && this.form.hasError('passwordMismatch')) {
|
||||||
|
return 'Las contrasenas no coinciden.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'El valor ingresado no es valido.';
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveErrorMessage(error: unknown): string {
|
||||||
|
const errorPayload =
|
||||||
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
|
? (error as { error?: { errors?: Record<string, string[]>; message?: string } }).error
|
||||||
|
: undefined;
|
||||||
|
const apiErrors = errorPayload?.errors;
|
||||||
|
|
||||||
|
if (apiErrors && typeof apiErrors === 'object') {
|
||||||
|
for (const field of ['nombre_apellido', 'email', 'password'] as const) {
|
||||||
|
const messages = apiErrors[field];
|
||||||
|
|
||||||
|
if (Array.isArray(messages) && typeof messages[0] === 'string' && messages[0].trim()) {
|
||||||
|
return messages[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof errorPayload?.message === 'string' && errorPayload.message.trim()) {
|
||||||
|
return errorPayload.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'No se pudo crear la cuenta. Intenta nuevamente.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
|
|
||||||
|
import { AuthLayoutComponent } from '../../core/layout/auth-layout/auth-layout.component';
|
||||||
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
|
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
|
||||||
|
import { guestOnlyGuard } from '../../core/services/auth/auth.guards';
|
||||||
|
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
||||||
|
import { RegisterPageComponent } from './pages/register-page/register-page.component';
|
||||||
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
@@ -12,6 +16,28 @@ export const routes: Routes = [
|
|||||||
path: '',
|
path: '',
|
||||||
component: StoreHomePageComponent
|
component: StoreHomePageComponent
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'login',
|
||||||
|
canActivate: [guestOnlyGuard],
|
||||||
|
component: AuthLayoutComponent,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
component: LoginPageComponent
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'register',
|
||||||
|
canActivate: [guestOnlyGuard],
|
||||||
|
component: AuthLayoutComponent,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: '',
|
||||||
|
component: RegisterPageComponent
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'producto/:id',
|
path: 'producto/:id',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
|
|||||||
@@ -29,7 +29,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.btn-outline-primary,
|
.btn-outline-primary,
|
||||||
.btn-outline-danger {
|
.btn-outline-neutral,
|
||||||
|
.btn-outline-danger,
|
||||||
|
.btn-borderless {
|
||||||
--bs-btn-bg: transparent;
|
--bs-btn-bg: transparent;
|
||||||
--bs-btn-hover-color: #fff;
|
--bs-btn-hover-color: #fff;
|
||||||
--bs-btn-active-color: #fff;
|
--bs-btn-active-color: #fff;
|
||||||
@@ -85,6 +87,17 @@
|
|||||||
--bs-btn-disabled-border-color: color-mix(in srgb, transparent 35%, var(--tenant-primary));
|
--bs-btn-disabled-border-color: color-mix(in srgb, transparent 35%, var(--tenant-primary));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.btn-outline-neutral {
|
||||||
|
--bs-btn-color: #666666;
|
||||||
|
--bs-btn-border-color: #a0a0a0;
|
||||||
|
--bs-btn-hover-bg: #a0a0a0;
|
||||||
|
--bs-btn-hover-border-color: #a0a0a0;
|
||||||
|
--bs-btn-active-bg: #8a8a8a;
|
||||||
|
--bs-btn-active-border-color: #8a8a8a;
|
||||||
|
--bs-btn-disabled-color: rgba(102, 102, 102, 0.55);
|
||||||
|
--bs-btn-disabled-border-color: rgba(160, 160, 160, 0.55);
|
||||||
|
}
|
||||||
|
|
||||||
.btn-outline-danger {
|
.btn-outline-danger {
|
||||||
--bs-btn-color: var(--tenant-danger);
|
--bs-btn-color: var(--tenant-danger);
|
||||||
--bs-btn-border-color: var(--tenant-danger);
|
--bs-btn-border-color: var(--tenant-danger);
|
||||||
@@ -95,3 +108,22 @@
|
|||||||
--bs-btn-disabled-color: color-mix(in srgb, transparent 35%, var(--tenant-danger));
|
--bs-btn-disabled-color: color-mix(in srgb, transparent 35%, var(--tenant-danger));
|
||||||
--bs-btn-disabled-border-color: color-mix(in srgb, transparent 35%, var(--tenant-danger));
|
--bs-btn-disabled-border-color: color-mix(in srgb, transparent 35%, var(--tenant-danger));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.btn-borderless {
|
||||||
|
min-width: auto;
|
||||||
|
padding-inline: 0;
|
||||||
|
border: 0;
|
||||||
|
color: var(--tenant-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
--bs-btn-border-color: transparent;
|
||||||
|
--bs-btn-hover-color: color-mix(in srgb, black 18%, var(--tenant-primary));
|
||||||
|
--bs-btn-hover-bg: transparent;
|
||||||
|
--bs-btn-hover-border-color: transparent;
|
||||||
|
--bs-btn-active-color: color-mix(in srgb, black 24%, var(--tenant-primary));
|
||||||
|
--bs-btn-active-bg: transparent;
|
||||||
|
--bs-btn-active-border-color: transparent;
|
||||||
|
--bs-btn-disabled-color: color-mix(in srgb, transparent 35%, var(--tenant-primary));
|
||||||
|
--bs-btn-disabled-bg: transparent;
|
||||||
|
--bs-btn-disabled-border-color: transparent;
|
||||||
|
--bs-btn-disabled-opacity: 1;
|
||||||
|
}
|
||||||
|
|||||||
19
src/app/shared/components/button/button.component.spec.ts
Normal file
19
src/app/shared/components/button/button.component.spec.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
|
||||||
|
import { ButtonComponent } from './button.component';
|
||||||
|
|
||||||
|
describe('ButtonComponent', () => {
|
||||||
|
it('applies the borderless variant class', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [ButtonComponent]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(ButtonComponent);
|
||||||
|
fixture.componentRef.setInput('variant', 'borderless');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button') as HTMLButtonElement;
|
||||||
|
|
||||||
|
expect(button.classList.contains('btn-borderless')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,8 @@ import { NgClass } from '@angular/common';
|
|||||||
export type ButtonVariant =
|
export type ButtonVariant =
|
||||||
| 'primary'
|
| 'primary'
|
||||||
| 'secondary'
|
| 'secondary'
|
||||||
|
| 'neutral-outline'
|
||||||
|
| 'borderless'
|
||||||
| 'danger'
|
| 'danger'
|
||||||
| 'danger-secondary'
|
| 'danger-secondary'
|
||||||
| 'cancel';
|
| 'cancel';
|
||||||
@@ -13,22 +15,29 @@ export type ButtonVariant =
|
|||||||
imports: [NgClass],
|
imports: [NgClass],
|
||||||
templateUrl: './button.component.html',
|
templateUrl: './button.component.html',
|
||||||
styleUrl: './button.component.scss',
|
styleUrl: './button.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
host: {
|
||||||
|
'[class]': 'hostClass()'
|
||||||
|
}
|
||||||
})
|
})
|
||||||
export class ButtonComponent {
|
export class ButtonComponent {
|
||||||
readonly variant = input<ButtonVariant>('primary');
|
readonly variant = input<ButtonVariant>('primary');
|
||||||
readonly type = input<'button' | 'submit' | 'reset'>('button');
|
readonly type = input<'button' | 'submit' | 'reset'>('button');
|
||||||
readonly disabled = input(false);
|
readonly disabled = input(false);
|
||||||
|
readonly hostClass = input<string>('');
|
||||||
|
readonly buttonClass = input<string>('');
|
||||||
|
|
||||||
protected readonly buttonClasses = computed(() => {
|
protected readonly buttonClasses = computed(() => {
|
||||||
const variants: Record<ButtonVariant, string> = {
|
const variants: Record<ButtonVariant, string> = {
|
||||||
primary: 'btn-primary',
|
primary: 'btn-primary',
|
||||||
secondary: 'btn-outline-primary',
|
secondary: 'btn-outline-primary',
|
||||||
|
'neutral-outline': 'btn-outline-neutral',
|
||||||
|
borderless: 'btn-borderless',
|
||||||
danger: 'btn-danger',
|
danger: 'btn-danger',
|
||||||
'danger-secondary': 'btn-outline-danger',
|
'danger-secondary': 'btn-outline-danger',
|
||||||
cancel: 'btn-secondary'
|
cancel: 'btn-secondary'
|
||||||
};
|
};
|
||||||
|
|
||||||
return ['btn', variants[this.variant()]];
|
return ['btn', variants[this.variant()], this.buttonClass()];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="d-grid gap-2 flex-grow-1 overflow-y-auto cart-items-container">
|
<div class="d-grid gap-2 flex-grow-1 overflow-y-auto cart-items-container">
|
||||||
@for (item of items(); track item.product + item.discountedPrice + resetKey(); let idx = $index) {
|
@for (item of items(); track item.productVariantId || item.product + item.discountedPrice; let idx = $index) {
|
||||||
<app-cart-item
|
<app-cart-item
|
||||||
[imageUrl]="item.imageUrl"
|
[imageUrl]="item.imageUrl"
|
||||||
[product]="item.product"
|
[product]="item.product"
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
[discountedPrice]="item.discountedPrice"
|
[discountedPrice]="item.discountedPrice"
|
||||||
[discountPercentage]="item.discountPercentage"
|
[discountPercentage]="item.discountPercentage"
|
||||||
[attributes]="item.attributes"
|
[attributes]="item.attributes"
|
||||||
[quantity]="item.quantity"
|
[quantity]="getItemQuantity(item)"
|
||||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||||
(remove)="onItemRemove(idx)"
|
(remove)="onItemRemove(idx)"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
BrowserTestingModule,
|
BrowserTestingModule,
|
||||||
platformBrowserTesting
|
platformBrowserTesting
|
||||||
} from '@angular/platform-browser/testing';
|
} from '@angular/platform-browser/testing';
|
||||||
import { of } from 'rxjs';
|
import { of, throwError } from 'rxjs';
|
||||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { CartService } from '../../../core/services/cart/cart.service';
|
import { CartService } from '../../../core/services/cart/cart.service';
|
||||||
@@ -141,4 +141,136 @@ describe('CartComponent', () => {
|
|||||||
expect(openConfirmDelete).toHaveBeenCalled();
|
expect(openConfirmDelete).toHaveBeenCalled();
|
||||||
expect(removeItem).not.toHaveBeenCalled();
|
expect(removeItem).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('optimistically updates quantity and rolls back on error', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
|
||||||
|
const danger = vi.fn();
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CartComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: CartService,
|
||||||
|
useValue: {
|
||||||
|
cart: signal(null).asReadonly(),
|
||||||
|
updateItemQuantity,
|
||||||
|
removeItem: vi.fn()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalService,
|
||||||
|
useValue: {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ToastService,
|
||||||
|
useValue: {
|
||||||
|
success: vi.fn(),
|
||||||
|
info: vi.fn(),
|
||||||
|
danger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CartComponent);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
|
||||||
|
const item = {
|
||||||
|
productVariantId: 10,
|
||||||
|
imageUrl: null,
|
||||||
|
product: 'Producto de prueba',
|
||||||
|
originalPrice: null,
|
||||||
|
discountedPrice: 1000,
|
||||||
|
discountPercentage: null,
|
||||||
|
attributes: [],
|
||||||
|
quantity: 1
|
||||||
|
};
|
||||||
|
|
||||||
|
fixture.componentRef.setInput('items', [item]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// Trigger quantity change to 3
|
||||||
|
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('quantityChange', 3);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// Optimistic update should be active immediately in local getter
|
||||||
|
expect((component as any).getItemQuantity(item)).toBe(3);
|
||||||
|
|
||||||
|
// Wait for the debounce time (1000ms)
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// After failure, it should roll back to original quantity (1)
|
||||||
|
expect((component as any).getItemQuantity(item)).toBe(1);
|
||||||
|
expect(danger).toHaveBeenCalled();
|
||||||
|
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('optimistically updates quantity and clears override on success', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const updateItemQuantity = vi.fn().mockReturnValue(of({ message: 'Success', data: {} }));
|
||||||
|
const success = vi.fn();
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CartComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: CartService,
|
||||||
|
useValue: {
|
||||||
|
cart: signal(null).asReadonly(),
|
||||||
|
updateItemQuantity,
|
||||||
|
removeItem: vi.fn()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalService,
|
||||||
|
useValue: {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ToastService,
|
||||||
|
useValue: {
|
||||||
|
success,
|
||||||
|
info: vi.fn(),
|
||||||
|
danger: vi.fn()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CartComponent);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
|
||||||
|
const item = {
|
||||||
|
productVariantId: 10,
|
||||||
|
imageUrl: null,
|
||||||
|
product: 'Producto de prueba',
|
||||||
|
originalPrice: null,
|
||||||
|
discountedPrice: 1000,
|
||||||
|
discountPercentage: null,
|
||||||
|
attributes: [],
|
||||||
|
quantity: 1
|
||||||
|
};
|
||||||
|
|
||||||
|
fixture.componentRef.setInput('items', [item]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// Trigger quantity change to 3
|
||||||
|
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('quantityChange', 3);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// Optimistic update should be active immediately in local getter
|
||||||
|
expect((component as any).getItemQuantity(item)).toBe(3);
|
||||||
|
|
||||||
|
// Wait for the debounce time (1000ms)
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
// After success, it should clear override and use input quantity (which is 1 since we didn't update items input here)
|
||||||
|
expect((component as any).getItemQuantity(item)).toBe(1);
|
||||||
|
expect(success).toHaveBeenCalled();
|
||||||
|
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export class CartComponent {
|
|||||||
|
|
||||||
readonly closed = output<void>();
|
readonly closed = output<void>();
|
||||||
|
|
||||||
protected readonly resetKey = signal(0);
|
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.quantityUpdates$.pipe(
|
this.quantityUpdates$.pipe(
|
||||||
@@ -55,12 +55,13 @@ export class CartComponent {
|
|||||||
next: (res) => {
|
next: (res) => {
|
||||||
const msg = res.message || 'Cantidad de producto actualizada.';
|
const msg = res.message || 'Cantidad de producto actualizada.';
|
||||||
this.toastService.success(msg);
|
this.toastService.success(msg);
|
||||||
|
this.clearOverride(update.productVariantId);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
console.error('Error updating cart quantity', err);
|
console.error('Error updating cart quantity', err);
|
||||||
const msg = err.error?.message || 'Error al actualizar la cantidad del producto.';
|
const msg = err.error?.message || 'Error al actualizar la cantidad del producto.';
|
||||||
this.toastService.danger(msg);
|
this.toastService.danger(msg);
|
||||||
this.resetKey.update(k => k + 1);
|
this.clearOverride(update.productVariantId);
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
catchError(() => EMPTY)
|
catchError(() => EMPTY)
|
||||||
@@ -70,10 +71,29 @@ export class CartComponent {
|
|||||||
).subscribe();
|
).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected getItemQuantity(item: CartItemMock): number {
|
||||||
|
if (item.productVariantId !== undefined && this.quantityOverrides()[item.productVariantId] !== undefined) {
|
||||||
|
return this.quantityOverrides()[item.productVariantId];
|
||||||
|
}
|
||||||
|
return item.quantity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearOverride(productVariantId: number): void {
|
||||||
|
this.quantityOverrides.update((overrides) => {
|
||||||
|
const copy = { ...overrides };
|
||||||
|
delete copy[productVariantId];
|
||||||
|
return copy;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||||
const mockItem = this.items()[index];
|
const mockItem = this.items()[index];
|
||||||
const productVariantId = mockItem?.productVariantId;
|
const productVariantId = mockItem?.productVariantId;
|
||||||
if (productVariantId) {
|
if (productVariantId) {
|
||||||
|
this.quantityOverrides.update((overrides) => ({
|
||||||
|
...overrides,
|
||||||
|
[productVariantId]: newQuantity
|
||||||
|
}));
|
||||||
this.quantityUpdates$.next({
|
this.quantityUpdates$.next({
|
||||||
productVariantId,
|
productVariantId,
|
||||||
quantity: newQuantity
|
quantity: newQuantity
|
||||||
@@ -81,6 +101,10 @@ export class CartComponent {
|
|||||||
} else {
|
} else {
|
||||||
const item = this.cartService.cart()?.items[index];
|
const item = this.cartService.cart()?.items[index];
|
||||||
if (item) {
|
if (item) {
|
||||||
|
this.quantityOverrides.update((overrides) => ({
|
||||||
|
...overrides,
|
||||||
|
[item.product_variant_id]: newQuantity
|
||||||
|
}));
|
||||||
this.quantityUpdates$.next({
|
this.quantityUpdates$.next({
|
||||||
productVariantId: item.product_variant_id,
|
productVariantId: item.product_variant_id,
|
||||||
quantity: newQuantity
|
quantity: newQuantity
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
.form-control {
|
.form-control {
|
||||||
min-height: 40px;
|
min-height: 40px;
|
||||||
padding: 0.625rem 1rem;
|
padding: 0.625rem 1rem;
|
||||||
border-radius: 0.5rem;
|
border-radius: 5px;
|
||||||
border-color: #cccccc;
|
border-color: #cccccc;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.modal-shell__content {
|
.modal-shell__content {
|
||||||
|
min-height: 180px;
|
||||||
max-height: calc(100dvh - 2rem);
|
max-height: calc(100dvh - 2rem);
|
||||||
border-radius: 1.25rem;
|
border-radius: 1.25rem;
|
||||||
background:
|
background:
|
||||||
@@ -72,6 +73,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.modal-shell__body {
|
.modal-shell__body {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
padding: 0 1.25rem 1.25rem;
|
padding: 0 1.25rem 1.25rem;
|
||||||
color: #303030;
|
color: #303030;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<div class="simple-modal">
|
||||||
|
<p class="simple-modal__content">{{ data.content }}</p>
|
||||||
|
|
||||||
|
<div class="simple-modal__actions">
|
||||||
|
<app-button (click)="close()">
|
||||||
|
{{ data.buttonLabel }}
|
||||||
|
</app-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
.simple-modal {
|
||||||
|
display: grid;
|
||||||
|
gap: 1.5rem;
|
||||||
|
justify-items: center;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.simple-modal__content {
|
||||||
|
margin: 0;
|
||||||
|
color: #666666;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.simple-modal__actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import '@angular/compiler';
|
||||||
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
|
import {
|
||||||
|
BrowserTestingModule,
|
||||||
|
platformBrowserTesting
|
||||||
|
} from '@angular/platform-browser/testing';
|
||||||
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
SimpleModalData,
|
||||||
|
MODAL_DATA,
|
||||||
|
ModalRef
|
||||||
|
} from '../../../core/services/modal.service';
|
||||||
|
import { SimpleModalComponent } from './simple-modal.component';
|
||||||
|
|
||||||
|
describe('SimpleModalComponent', () => {
|
||||||
|
const data: SimpleModalData = {
|
||||||
|
content: 'Este es un mensaje simple.',
|
||||||
|
buttonLabel: 'Entendido'
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
try {
|
||||||
|
getTestBed().initTestEnvironment(
|
||||||
|
BrowserTestingModule,
|
||||||
|
platformBrowserTesting()
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the configured content and button label', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [SimpleModalComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: MODAL_DATA,
|
||||||
|
useValue: data
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalRef,
|
||||||
|
useValue: {
|
||||||
|
close: vi.fn()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SimpleModalComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
expect(element.textContent).toContain(data.content);
|
||||||
|
expect(element.textContent).toContain(data.buttonLabel);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes when clicking the primary button', async () => {
|
||||||
|
const closeSpy = vi.fn();
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [SimpleModalComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: MODAL_DATA,
|
||||||
|
useValue: data
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalRef,
|
||||||
|
useValue: {
|
||||||
|
close: closeSpy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(SimpleModalComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button');
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
expect(closeSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||||
|
|
||||||
|
import {
|
||||||
|
SimpleModalData,
|
||||||
|
MODAL_DATA,
|
||||||
|
ModalRef
|
||||||
|
} from '../../../core/services/modal.service';
|
||||||
|
import { ButtonComponent } from '../button/button.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-simple-modal',
|
||||||
|
imports: [ButtonComponent],
|
||||||
|
templateUrl: './simple-modal.component.html',
|
||||||
|
styleUrl: './simple-modal.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
|
})
|
||||||
|
export class SimpleModalComponent {
|
||||||
|
protected readonly data = inject<SimpleModalData>(MODAL_DATA);
|
||||||
|
private readonly modalRef = inject<ModalRef<void>>(ModalRef);
|
||||||
|
|
||||||
|
protected close(): void {
|
||||||
|
this.modalRef.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
@import "../node_modules/bootstrap/scss/bootstrap";
|
@import "../node_modules/bootstrap/scss/bootstrap";
|
||||||
|
|
||||||
:root {
|
:root, app-root {
|
||||||
--bs-body-font-family: "Gotham", sans-serif;
|
--bs-body-font-family: "Gotham", sans-serif;
|
||||||
--bs-primary: var(--tenant-primary);
|
--bs-primary: var(--tenant-primary);
|
||||||
--bs-primary-rgb: var(--tenant-primary-rgb);
|
--bs-primary-rgb: var(--tenant-primary-rgb);
|
||||||
|
|||||||
Reference in New Issue
Block a user