2 Commits

Author SHA1 Message Date
902f65d8d0 feat: enhance checkout process with purchase editing and status handling
- Implemented purchase editing functionality in CheckoutPageComponent, allowing users to modify items in their purchase.
- Added a new guard (checkoutPendingPurchaseGuard) to prevent navigation away from the checkout page while a purchase is in progress.
- Updated the login page to handle return URLs after authentication.
- Enhanced product detail page to support direct purchases with a new buyNow method.
- Introduced new UI elements and logic to handle purchase status, including expired and rejected states in PurchaseStatusPageComponent.
- Improved cart component to allow editing of item quantities with a toggle button.
- Added quantity selector enhancements to disable controls when necessary.
- Updated tests to cover new functionalities and ensure proper behavior of components.
2026-07-27 12:49:00 -03:00
9dcedc9382 Forgot password flow 2026-07-27 09:42:22 -03:00
47 changed files with 2934 additions and 209 deletions

View File

@@ -165,6 +165,55 @@ describe('app routes', () => {
]);
});
it('loads the recover password page inside the simple layout', async () => {
const { fixture, router } = await renderAppAt('/recuperar-contrasena');
const compiled = fixture.nativeElement as HTMLElement;
const recoverPasswordPage = compiled.querySelector('app-recover-password-page');
expect(router.url).toBe('/recuperar-contrasena');
expect(compiled.querySelector('.simple-layout')).not.toBeNull();
expect(recoverPasswordPage).not.toBeNull();
expect(recoverPasswordPage?.textContent).toContain('Recuperar contraseña');
expect(recoverPasswordPage?.querySelector('input')?.getAttribute('placeholder')).toBe('Email');
expect(recoverPasswordPage?.textContent).toContain('Recuperar acceso');
expect(recoverPasswordPage?.textContent).toContain('Volver');
});
it('loads the recovery code page and shows the entered email', async () => {
const { fixture, router } = await renderAppAt(
'/recuperar-contrasena/codigo?email=ada%40example.com'
);
const compiled = fixture.nativeElement as HTMLElement;
const codePage = compiled.querySelector('app-recover-password-code-page');
expect(router.url).toBe('/recuperar-contrasena/codigo?email=ada%40example.com');
expect(compiled.querySelector('.simple-layout')).not.toBeNull();
expect(codePage).not.toBeNull();
expect(codePage?.textContent).toContain('ada@example.com');
expect(codePage?.querySelectorAll('app-input')).toHaveLength(4);
expect(codePage?.textContent).toContain('Validar');
});
it('loads the reset password page with the shared password inputs', async () => {
const { fixture, router } = await renderAppAt(
'/recuperar-contrasena/restablecer?email=ada%40example.com&code=1234'
);
const compiled = fixture.nativeElement as HTMLElement;
const resetPage = compiled.querySelector('app-reset-password-page');
const placeholders = Array.from(resetPage?.querySelectorAll('input') ?? []).map((input) =>
input.getAttribute('placeholder')
);
expect(router.url).toBe(
'/recuperar-contrasena/restablecer?email=ada%40example.com&code=1234'
);
expect(compiled.querySelector('.simple-layout')).not.toBeNull();
expect(resetPage).not.toBeNull();
expect(resetPage?.textContent).toContain('Restablecer contraseña');
expect(placeholders).toEqual(['Nueva Contraseña', 'Repetir Nueva Contraseña']);
expect(resetPage?.textContent).toContain('Guardar');
});
it('redirects authenticated users away from /login', async () => {
const { router } = await renderAppAt('/login', createTenantServiceStub(), createAuthServiceStub(true));
@@ -186,7 +235,7 @@ describe('app routes', () => {
it('redirects unauthenticated users from /checkout to /login', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
expect(router.url).toBe('/login');
expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
});
it('allows authenticated users to access /checkout', async () => {

View File

@@ -14,7 +14,10 @@
/>
@if (isCartOpen()) {
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
<div
class="store-layout__cart-overlay"
(click)="isCartOpen.set(false)"
></div>
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
<app-cart
[showClose]="true"
@@ -25,12 +28,20 @@
[backgroundColor]="'#ffffff'"
(closed)="isCartOpen.set(false)"
>
<app-button variant="secondary" class="flex-grow-1" (click)="isCartOpen.set(false)"
<app-button
variant="secondary"
class="flex-grow-1"
(click)="isCartOpen.set(false)"
>Seguir comprando</app-button
>
<app-button variant="primary" class="flex-grow-1" (click)="onCheckoutClick()"
>Comprar</app-button
<app-button
variant="primary"
class="flex-grow-1"
[disabled]="isCreatingPurchase()"
(click)="onCheckoutClick()"
>
Comprar
</app-button>
</app-cart>
</div>
}

View File

@@ -15,6 +15,7 @@ import { AuthService } from '../../services/auth/auth.service';
import { AuthUser } from '../../services/auth/auth.interfaces';
import { StoreLayoutComponent } from './store-layout.component';
import { StoreHeaderComponent } from './store-header/store-header.component';
import { CheckoutService } from '../../services/checkout.service';
const tenant: Tenant = {
id: 1,
@@ -127,12 +128,17 @@ const tenant: Tenant = {
describe('StoreLayoutComponent', () => {
let tenantState = signal<Tenant | null>(tenant);
let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
beforeEach(async () => {
tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null);
const authUserState = signal<AuthUser | null>(null);
authUserState = signal<AuthUser | null>(null);
const isAuthenticatedState = signal(false);
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
};
await TestBed.configureTestingModule({
imports: [StoreLayoutComponent],
@@ -156,6 +162,7 @@ describe('StoreLayoutComponent', () => {
.fn()
.mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
removeItem: vi.fn().mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
clearCart: vi.fn(() => cartState.set(null)),
},
},
{
@@ -176,6 +183,10 @@ describe('StoreLayoutComponent', () => {
logout: vi.fn().mockReturnValue(of(void 0)),
},
},
{
provide: CheckoutService,
useValue: checkoutServiceStub,
},
],
}).compileComponents();
});
@@ -394,8 +405,9 @@ describe('StoreLayoutComponent', () => {
expect(router.navigate).not.toHaveBeenCalled();
});
it('logs out from the authenticated user dropdown', () => {
it('logs out from the authenticated user dropdown, clears the cart and returns home', () => {
const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate');
@@ -424,11 +436,13 @@ describe('StoreLayoutComponent', () => {
fixture.detectChanges();
expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
expect(cartService.clearCart).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
it('provides account actions from the footer', () => {
const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate');
@@ -455,7 +469,28 @@ describe('StoreLayoutComponent', () => {
fixture.detectChanges();
expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
expect(cartService.clearCart).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
it('leaves checkout before logging out so the pending purchase can be cancelled', async () => {
const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
await (fixture.componentInstance as any).onLogoutClick();
expect(navigateSpy).toHaveBeenCalledWith(['/']);
expect(authService.logout).toHaveBeenCalled();
expect(navigateSpy.mock.invocationCallOrder[0]).toBeLessThan(
(authService.logout as any).mock.invocationCallOrder[0],
);
expect(cartService.clearCart).toHaveBeenCalled();
});
it('renders only the help submenus assigned to the tenant in the footer', () => {
@@ -481,7 +516,7 @@ describe('StoreLayoutComponent', () => {
expect(compiled.textContent).not.toContain('Medios de pago');
});
it('redirects to /checkout when cart buy button is clicked', () => {
it('creates a purchase and redirects to checkout when cart buy is clicked', async () => {
const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate');
cartState.set({
@@ -503,23 +538,73 @@ describe('StoreLayoutComponent', () => {
},
],
});
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
const buyButton = Array.from(compiled.querySelectorAll('app-button button')).find(
(button) => button.textContent?.trim() === 'Comprar',
) as HTMLButtonElement | undefined;
expect(buyButton).toBeDefined();
buyButton!.click();
await Promise.resolve();
fixture.detectChanges();
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1,
});
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 55 },
});
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
});
it('allows modifying quantities directly in the regular cart without a toggle', () => {
cartState.set({
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [
{
id: 1,
cantidad: 1,
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: null,
product: {
nombre: 'Producto',
imagen: null,
},
},
],
});
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
(fixture.componentInstance as any).isCartOpen.set(true);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
const buyButton = Array.from(compiled.querySelectorAll('app-button button')).find(
(button) => button.textContent?.trim() === 'Comprar',
) as HTMLButtonElement | undefined;
const element = fixture.nativeElement as HTMLElement;
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
const buyButton = Array.from(
element.querySelectorAll<HTMLButtonElement>('app-button button'),
).find((button) => button.textContent?.trim() === 'Comprar');
expect(element.querySelector('.cart-edit-btn')).toBeNull();
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
expect(buyButton).toBeDefined();
buyButton!.click();
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['/checkout']);
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
});
});

View File

@@ -9,6 +9,8 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
import { CartItem } from '../../services/cart/cart.interface';
import { AuthService } from '../../services/auth/auth.service';
import { findMenu } from '../../services/menu.utils';
import { CheckoutService } from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service';
@Component({
selector: 'app-store-layout',
@@ -26,9 +28,12 @@ export class StoreLayoutComponent implements OnInit {
private readonly tenantService = inject(TenantService);
private readonly cartService = inject(CartService);
private readonly authService = inject(AuthService);
private readonly checkoutService = inject(CheckoutService);
private readonly toastService = inject(ToastService);
private readonly router = inject(Router);
protected readonly isCartOpen = signal(false);
protected readonly isCreatingPurchase = signal(false);
protected readonly cartSubtotal = computed(() => {
const cart = this.cartService.cart();
@@ -128,16 +133,69 @@ export class StoreLayoutComponent implements OnInit {
}
}
protected onLogoutClick(): void {
protected async onLogoutClick(): Promise<void> {
const isLeavingCheckout = this.router.url.startsWith('/checkout');
// Checkout must be left while the authenticated session is still valid so
// its CanDeactivate guard can cancel the pending purchase.
if (isLeavingCheckout) {
const navigationSucceeded = await this.router.navigate(['/']);
if (!navigationSucceeded) {
return;
}
}
this.authService.logout().subscribe({
next: () => void this.router.navigate(['/login']),
next: () => {
this.cartService.clearCart();
this.isCartOpen.set(false);
if (!isLeavingCheckout) {
void this.router.navigate(['/']);
}
},
error: (err) => console.error('Error logging out', err),
});
}
protected onCheckoutClick(): void {
this.isCartOpen.set(false);
void this.router.navigate(['/checkout']);
protected async onCheckoutClick(): Promise<void> {
if (this.isCreatingPurchase()) {
return;
}
const cart = this.cartService.cart();
const tenant = this.tenantService.tenant();
const user = this.authService.user();
if (!user) {
this.isCartOpen.set(false);
void this.router.navigate(['/login'], { queryParams: { returnUrl: '/' } });
return;
}
if (!cart?.id || !tenant) {
this.toastService.danger('No hay un carrito activo para iniciar la compra.');
return;
}
this.isCreatingPurchase.set(true);
try {
const purchase = await this.checkoutService.startCheckout(tenant.codigo, {
cart_id: cart.id,
});
this.cartService.clearCart();
this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
} catch (error) {
console.error('Failed to create cart purchase:', error);
this.toastService.danger('No se pudo iniciar la compra.');
} finally {
this.isCreatingPurchase.set(false);
}
}
protected readonly footerSections = computed<StoreFooterSection[]>(() => {

View File

@@ -23,10 +23,14 @@ describe('auth guards', () => {
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
});
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
);
expect(result instanceof UrlTree).toBe(true);
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login');
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
);
});
it('allows authenticated users through authGuard', () => {
@@ -34,7 +38,9 @@ describe('auth guards', () => {
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
});
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout' } as never),
);
expect(result).toBe(true);
});

View File

@@ -3,11 +3,15 @@ import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () => {
export const authGuard: CanActivateFn = (_route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
return authService.isAuthenticated() ? true : router.createUrlTree(['/login']);
return authService.isAuthenticated()
? true
: router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};
export const guestOnlyGuard: CanActivateFn = () => {

View File

@@ -37,3 +37,25 @@ export interface RegisterResponse {
message: string;
data: AuthUser;
}
export interface ResetPasswordAttemptResponse {
message: string;
status: 'pending';
}
export interface ValidateResetPasswordAttemptResponse {
message: string;
status: 'validated';
}
export interface ResetPasswordPayload {
email: string;
codigo: string;
password: string;
password_confirmation: string;
}
export interface ResetPasswordResponse {
message: string;
status: 'used';
}

View File

@@ -19,8 +19,12 @@ describe('AuthService', () => {
function createCookieServiceStub() {
return {
get: (name: string) => cookieStore[name] || null,
set: (name: string, value: string) => { cookieStore[name] = value; },
delete: (name: string) => { delete cookieStore[name]; }
set: (name: string, value: string) => {
cookieStore[name] = value;
},
delete: (name: string) => {
delete cookieStore[name];
}
};
}
@@ -31,6 +35,10 @@ describe('AuthService', () => {
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState
]
});
@@ -44,6 +52,12 @@ describe('AuthService', () => {
const request = httpController.expectOne(`${environment.url}login`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
email: 'ada@example.com',
password: 'secret123',
tenant_codigo: 'tenant-test'
});
expect(request.request.withCredentials).toBe(true);
request.flush({
message: 'Sesion iniciada correctamente.',
token: 'plain-text-token',
@@ -96,6 +110,47 @@ describe('AuthService', () => {
httpController.verify();
});
it('sends tenant and credentials when completing Google login', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState
]
});
const service = TestBed.inject(AuthService);
const httpController = TestBed.inject(HttpTestingController);
service.completeGoogleLogin('oauth-code').subscribe();
const request = httpController.expectOne(`${environment.url}auth/google/exchange`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
oauth_code: 'oauth-code',
tenant_codigo: 'tenant-test'
});
expect(request.request.withCredentials).toBe(true);
request.flush({
message: 'Sesion iniciada correctamente.',
token: 'google-token',
token_type: 'Bearer',
user: {
id: 1,
nombre_apellido: 'Ada Lovelace',
email: 'ada@example.com'
}
});
httpController.verify();
});
it('clears an expired session when /me returns 401', async () => {
cookieStore['shopit.auth.token'] = 'expired-token';
@@ -174,6 +229,121 @@ describe('AuthService', () => {
httpController.verify();
});
it('requests a password reset and exposes the final HTTP status', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState
]
});
const service = TestBed.inject(AuthService);
const httpController = TestBed.inject(HttpTestingController);
service.requestPasswordReset('ada@example.com').subscribe((response) => {
expect(response.status).toBe(202);
expect(response.body?.status).toBe('pending');
});
const request = httpController.expectOne(`${environment.url}password/reset-attempts`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
email: 'ada@example.com',
tenant_codigo: 'tenant-test'
});
request.flush(
{
message: 'Si el email está registrado, recibirás un código.',
status: 'pending'
},
{ status: 202, statusText: 'Accepted' }
);
httpController.verify();
});
it('validates a password reset code and exposes its final status', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
TransferState
]
});
const service = TestBed.inject(AuthService);
const httpController = TestBed.inject(HttpTestingController);
service.validatePasswordResetCode('ada@example.com', '0123').subscribe((response) => {
expect(response.status).toBe(200);
expect(response.body?.status).toBe('validated');
});
const request = httpController.expectOne(`${environment.url}password/reset-attempts/validate`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({
email: 'ada@example.com',
codigo: '0123'
});
request.flush(
{
message: 'Código validado correctamente.',
status: 'validated'
},
{ status: 200, statusText: 'OK' }
);
httpController.verify();
});
it('resets the password and exposes the consumed attempt status', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
TransferState
]
});
const service = TestBed.inject(AuthService);
const httpController = TestBed.inject(HttpTestingController);
const payload = {
email: 'ada@example.com',
codigo: '0123',
password: 'NewSecret!456',
password_confirmation: 'NewSecret!456'
};
service.resetPassword(payload).subscribe((response) => {
expect(response.status).toBe(200);
expect(response.body?.status).toBe('used');
});
const request = httpController.expectOne(`${environment.url}password/reset`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual(payload);
request.flush(
{
message: 'Contraseña modificada correctamente.',
status: 'used'
},
{ status: 200, statusText: 'OK' }
);
httpController.verify();
});
it('propagates logout errors without clearing the local session', () => {
TestBed.configureTestingModule({
providers: [
@@ -181,6 +351,10 @@ describe('AuthService', () => {
provideHttpClientTesting(),
AuthService,
{ provide: CookieService, useValue: createCookieServiceStub() },
{
provide: TenantService,
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
},
TransferState
]
});

View File

@@ -1,5 +1,5 @@
import { DOCUMENT } from '@angular/common';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
@@ -11,7 +11,11 @@ import {
LoginResponse,
RegisterPayload,
RegisterResponse,
UpdateProfilePayload
ResetPasswordPayload,
ResetPasswordAttemptResponse,
ResetPasswordResponse,
UpdateProfilePayload,
ValidateResetPasswordAttemptResponse
} from './auth.interfaces';
import { CookieService } from '../cookie/cookie.service';
import { TenantService } from '../tenant.service';
@@ -38,10 +42,21 @@ export class AuthService {
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)
);
const tenant = this.tenantService.getTenant();
if (!tenant) {
throw new Error('No se pudo resolver el tenant activo.');
}
return this.http
.post<LoginResponse>(
`${environment.url}login`,
{ ...payload, tenant_codigo: tenant.codigo },
{ withCredentials: true }
)
.pipe(
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
map((response) => response.user)
);
}
register(payload: RegisterPayload): Observable<RegisterResponse> {
@@ -53,6 +68,36 @@ export class AuthService {
});
}
requestPasswordReset(email: string): Observable<HttpResponse<ResetPasswordAttemptResponse>> {
const tenantCode = this.tenantService.getTenant()?.codigo;
return this.http.post<ResetPasswordAttemptResponse>(
`${environment.url}password/reset-attempts`,
{
email,
...(tenantCode ? { tenant_codigo: tenantCode } : {})
},
{ observe: 'response' }
);
}
validatePasswordResetCode(
email: string,
codigo: string
): Observable<HttpResponse<ValidateResetPasswordAttemptResponse>> {
return this.http.post<ValidateResetPasswordAttemptResponse>(
`${environment.url}password/reset-attempts/validate`,
{ email, codigo },
{ observe: 'response' }
);
}
resetPassword(payload: ResetPasswordPayload): Observable<HttpResponse<ResetPasswordResponse>> {
return this.http.post<ResetPasswordResponse>(`${environment.url}password/reset`, payload, {
observe: 'response'
});
}
loginWithGoogle(): void {
const tenant = this.tenantService.getTenant();
if (!tenant) {
@@ -68,16 +113,25 @@ export class AuthService {
}
completeGoogleLogin(oauthCode: string): Observable<AuthUser> {
return this.http.post<LoginResponse>(`${environment.url}auth/google/exchange`, { oauth_code: oauthCode }).pipe(
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
map((response) => response.user)
);
const tenant = this.tenantService.getTenant();
if (!tenant) {
throw new Error('No se pudo resolver el tenant activo.');
}
return this.http
.post<LoginResponse>(
`${environment.url}auth/google/exchange`,
{ oauth_code: oauthCode, tenant_codigo: tenant.codigo },
{ withCredentials: true }
)
.pipe(
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
map((response) => response.user)
);
}
updateProfile(payload: UpdateProfilePayload): Observable<AuthUser> {
return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe(
tap((user) => this.userState.set(user))
);
return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe(tap((user) => this.userState.set(user)));
}
logout(): Observable<void> {
@@ -86,9 +140,7 @@ export class AuthService {
return of(void 0);
}
return this.http.post<void>(`${environment.url}logout`, {}).pipe(
tap(() => this.clearSession())
);
return this.http.post<void>(`${environment.url}logout`, {}).pipe(tap(() => this.clearSession()));
}
async bootstrap(): Promise<void> {
@@ -127,9 +179,7 @@ export class AuthService {
}
loadCurrentUser(): Observable<AuthUser> {
return this.http.get<AuthUser>(`${environment.url}me`).pipe(
tap((user) => this.userState.set(user))
);
return this.http.get<AuthUser>(`${environment.url}me`).pipe(tap((user) => this.userState.set(user)));
}
hydrateSession(): void {

View File

@@ -4,14 +4,25 @@ import { firstValueFrom } from 'rxjs';
import { environment } from '../../../environments/environment';
export interface CreatePurchasePayload {
cart_id: number;
export interface UpdatePurchaseCustomerPayload {
dni: string;
telefono: string;
nombre_apellido: string;
email: string;
}
export type StartCheckoutPayload =
| {
cart_id: number;
}
| {
direct_item: {
catalog_item_id: number;
variant_id: number | null;
cantidad: number;
};
};
export interface PurchaseStatusResponse {
status: string | null;
}
@@ -62,17 +73,23 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
}
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class CheckoutService {
private readonly http = inject(HttpClient);
async createPurchase(tenantCode: string, payload: CreatePurchasePayload): Promise<{ id: number }> {
async startCheckout(
tenantCode: string,
payload: StartCheckoutPayload,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: { id: number }; id?: number }>(`${environment.url}tenants/${tenantCode}/compras`, payload)
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
payload,
),
);
const purchase = this.extractResponseData<{ id: number }>(response);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase?.id) {
throw new Error('Error al crear la compra.');
@@ -81,13 +98,21 @@ export class CheckoutService {
return purchase;
}
async generatePaymentIntent(tenantCode: string, purchaseId: number, method: 'qr' | 'transfer' | 'telepagos', payerDni?: string): Promise<any> {
async generatePaymentIntent(
tenantCode: string,
purchaseId: number,
method: 'qr' | 'transfer' | 'telepagos',
payerDni?: string,
): Promise<any> {
const payload: any = { method };
if (payerDni) {
payload.transfer_payer_dni = payerDni;
}
const response = await firstValueFrom(
this.http.post<any>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/payment-intent`, payload)
this.http.post<any>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/payment-intent`,
payload,
),
);
if (!response) {
throw new Error('Error al generar la intención de pago.');
@@ -95,9 +120,72 @@ export class CheckoutService {
return response;
}
async updateCustomerData(
tenantCode: string,
purchaseId: number,
payload: UpdatePurchaseCustomerPayload,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/customer-data`,
payload,
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al actualizar los datos de la compra.');
}
return purchase;
}
async updateItemQuantity(
tenantCode: string,
purchaseId: number,
itemId: number,
quantity: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
{ quantity },
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al actualizar la cantidad del producto.');
}
return purchase;
}
async prepareItemEditing(
tenantCode: string,
purchaseId: number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/edit-items`,
{},
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase) {
throw new Error('Error al preparar la compra para editarla.');
}
return purchase;
}
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`, {})
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
{},
),
);
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
@@ -107,27 +195,49 @@ export class CheckoutService {
}
return {
status: purchase.status ?? null
status: purchase.status ?? null,
};
}
async getPurchases(tenantCode: string, status?: string): Promise<{ data: PurchaseSummaryResponse[] }> {
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/cancel`,
{},
),
);
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
if (!purchase) {
throw new Error('Error al cancelar la compra.');
}
return { status: purchase.status ?? null };
}
async getPurchases(
tenantCode: string,
status?: string,
): Promise<{ data: PurchaseSummaryResponse[] }> {
let url = `${environment.url}tenants/${tenantCode}/compras`;
if (status) {
url += `?status=${status}`;
}
const response = await firstValueFrom(
this.http.get<{ data: PurchaseSummaryResponse[] }>(url)
);
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
if (!response) {
throw new Error('Error al obtener las compras.');
}
return response;
}
async getPurchase(tenantCode: string, purchaseId: string | number): Promise<PurchaseDetailResponse> {
async getPurchase(
tenantCode: string,
purchaseId: string | number,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.get<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(`${environment.url}tenants/${tenantCode}/compras/${purchaseId}`)
this.http.get<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}`,
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);

View File

@@ -1,7 +1,11 @@
<div class="checkout-page">
<div class="checkout-page__stepper-col ">
<app-stepper #stepper>
<div class="checkout-page">
<div
class="checkout-page__stepper-col"
[class.checkout-page__stepper-col--editing]="isEditingItems()"
[attr.aria-hidden]="isEditingItems()"
[attr.inert]="isEditingItems() ? '' : null"
>
<app-stepper #stepper>
<app-step label="Datos" [isValid]="isStep1Valid()">
<app-checkout-data-step
[form]="form"
@@ -30,16 +34,32 @@
(retryQrPolling)="retryQrPolling()"
/>
</app-step>
</app-stepper>
</div>
<div class="checkout-page__cart-col">
<app-cart
[items]="mappedCartItems()"
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
backgroundColor="transparent"
/>
</div>
</app-stepper>
</div>
@if (isEditingItems()) {
<div class="checkout-page__editing-notice" role="status">
<p>Terminá de modificar las cantidades para continuar con el pago.</p>
</div>
}
<div class="checkout-page__cart-col">
<app-cart
title="COMPRA"
[items]="mappedCartItems()"
[subtotal]="cartSubtotal()"
[discount]="cartDiscount()"
[total]="cartTotal()"
[allowEditing]="
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
"
[allowRemove]="false"
[persistQuantityChanges]="false"
[editing]="isEditingItems()"
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
backgroundColor="transparent"
(editingChange)="onEditingItemsChange($event)"
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
/>
</div>
</div>

View File

@@ -12,6 +12,27 @@
min-width: 0;
border-radius: 4px;
min-height: 420px;
&--editing {
display: none;
}
}
&__editing-notice {
display: grid;
min-height: 420px;
place-items: center;
padding: 2rem;
border-radius: 4px;
background: #f5f5f5;
color: #666666;
text-align: center;
p {
max-width: 360px;
margin: 0;
font-size: 14px;
}
}
&__cart-col {

View File

@@ -1,18 +1,24 @@
import { signal } from '@angular/core';
import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { Router } from '@angular/router';
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
import { of } from 'rxjs';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { CheckoutPageComponent } from './checkout-page.component';
describe('CheckoutPageComponent payment validation', () => {
let checkoutServiceStub: {
startCheckout: ReturnType<typeof vi.fn>;
updateCustomerData: ReturnType<typeof vi.fn>;
updateItemQuantity: ReturnType<typeof vi.fn>;
prepareItemEditing: ReturnType<typeof vi.fn>;
cancelPurchase: ReturnType<typeof vi.fn>;
generatePaymentIntent: ReturnType<typeof vi.fn>;
getPurchase: ReturnType<typeof vi.fn>;
};
@@ -23,6 +29,8 @@ describe('CheckoutPageComponent payment validation', () => {
clearCart: ReturnType<typeof vi.fn>;
};
let routerStub: { navigate: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>;
beforeAll(() => {
try {
@@ -36,6 +44,16 @@ describe('CheckoutPageComponent payment validation', () => {
vi.useFakeTimers();
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({
id: 25,
items: [],
subtotal: '0.00',
total: '0.00',
}),
updateCustomerData: vi.fn(),
updateItemQuantity: vi.fn(),
prepareItemEditing: vi.fn(),
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
generatePaymentIntent: vi.fn().mockResolvedValue({
qr_data: { qr_code: 'qr-value' },
}),
@@ -63,14 +81,27 @@ describe('CheckoutPageComponent payment validation', () => {
});
});
routerStub = { navigate: vi.fn() };
routeQueryParamMap = convertToParamMap({});
authUserState = signal(null);
await TestBed.configureTestingModule({
imports: [CheckoutPageComponent],
providers: [
{ provide: CheckoutService, useValue: checkoutServiceStub },
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
{ provide: CartService, useValue: cartServiceStub },
{ provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } },
{ provide: AuthService, useValue: { user: signal(null) } },
{ provide: AuthService, useValue: { user: authUserState } },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
get queryParamMap() {
return routeQueryParamMap;
},
},
},
},
{ provide: Router, useValue: routerStub },
],
})
@@ -87,6 +118,7 @@ describe('CheckoutPageComponent payment validation', () => {
const fixture = TestBed.createComponent(CheckoutPageComponent);
fixture.detectChanges();
fixture.componentInstance['createdPurchaseId'].set(25);
routerStub.navigate.mockClear();
return { fixture, component: fixture.componentInstance as any };
}
@@ -105,7 +137,7 @@ describe('CheckoutPageComponent payment validation', () => {
await vi.advanceTimersByTimeAsync(5_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
});
@@ -181,7 +213,7 @@ describe('CheckoutPageComponent payment validation', () => {
await component.onComplete();
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
});
@@ -197,4 +229,175 @@ describe('CheckoutPageComponent payment validation', () => {
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled();
});
it('loads purchase items but prefills customer data from the user', async () => {
const purchase = {
id: 25,
cart_id: null,
nombre_apellido: 'Datos de la compra',
email: 'compra@example.com',
dni: '11111111',
telefono: '1111111111',
items: [
{
id: 91,
quantity: 2,
unit_price: '1250.50',
line_total: '2501.00',
source_catalog_item_id: 8,
source_variant_id: 21,
item_details: {
nombre: 'Remera',
descripcion: null,
slug: 'remera',
imagen: 'https://example.com/remera.jpg',
attributes: [{ name: 'Color', value: 'Negro' }],
},
},
],
subtotal: '2501.00',
total: '2501.00',
};
routeQueryParamMap = convertToParamMap({ purchase: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const { component } = createComponent();
await Promise.resolve();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(component.mappedCartItems()).toEqual([
{
cartItemId: 91,
imageUrl: 'https://example.com/remera.jpg',
product: 'Remera',
originalPrice: null,
discountedPrice: 1250.5,
discountPercentage: null,
attributes: [{ label: 'Color', value: 'Negro' }],
quantity: 2,
},
]);
expect(component.cartSubtotal()).toBe(2501);
expect(component.cartTotal()).toBe(2501);
expect(component.form.getRawValue()).toEqual({
nombre: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
});
it('updates a purchase item while editing and refreshes checkout totals', async () => {
const updatedPurchase = {
id: 25,
items: [],
subtotal: '300.00',
total: '300.00',
};
checkoutServiceStub.updateItemQuantity.mockResolvedValue(updatedPurchase);
const { component } = createComponent();
component.isEditingItems.set(true);
await component.onPurchaseItemQuantityChange({
item: {
cartItemId: 91,
imageUrl: null,
product: 'Remera',
originalPrice: null,
discountedPrice: 100,
discountPercentage: null,
attributes: [],
quantity: 2,
},
quantity: 3,
});
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
'tenant-test',
25,
91,
3,
);
expect(component.createdPurchase()).toBe(updatedPurchase);
expect(component.isUpdatingItem()).toBe(false);
});
it('keeps the payment step selected while editing and regenerates payment afterward', async () => {
const editablePurchase = {
id: 25,
status: 'created',
items: [],
subtotal: '100.00',
total: '100.00',
};
checkoutServiceStub.prepareItemEditing.mockResolvedValue(editablePurchase);
const { component } = createComponent();
component.stepper = { currentStepIndex: signal(1) };
const selectPaymentMethod = vi
.spyOn(component, 'selectPaymentMethod')
.mockResolvedValue(undefined);
await component.onEditingItemsChange(true);
expect(checkoutServiceStub.prepareItemEditing).toHaveBeenCalledWith('tenant-test', 25);
expect(component.isEditingItems()).toBe(true);
expect(component.createdPurchase()).toBe(editablePurchase);
await component.onEditingItemsChange(false);
expect(component.stepper.currentStepIndex()).toBe(1);
expect(selectPaymentMethod).toHaveBeenCalledWith('qr');
expect(component.isEditingItems()).toBe(false);
});
it('updates customer data on the existing purchase before payment', async () => {
const updatedPurchase = {
id: 25,
cart_id: 10,
items: [],
subtotal: '100.00',
total: '100.00',
};
checkoutServiceStub.updateCustomerData.mockResolvedValue(updatedPurchase);
const { component } = createComponent();
component.form.setValue({
nombre: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
component.stepper = { next: vi.fn() };
await component.onStep1Continue();
expect(checkoutServiceStub.startCheckout).not.toHaveBeenCalled();
expect(checkoutServiceStub.updateCustomerData).toHaveBeenCalledWith('tenant-test', 25, {
dni: '12345678',
telefono: '3415555555',
email: 'juan@example.com',
nombre_apellido: 'Juan Perez',
});
expect(component.createdPurchase()).toEqual({
...updatedPurchase,
status: 'pending_payment',
});
expect(component.stepper.next).toHaveBeenCalledOnce();
});
it('cancels the pending purchase before allowing navigation away', async () => {
const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true);
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.loadCart).toHaveBeenCalled();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(component.createdPurchaseId()).toBeNull();
});
});

View File

@@ -2,24 +2,25 @@ import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
OnDestroy,
OnInit,
signal,
untracked,
ViewChild,
} from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { startWith } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { firstValueFrom, startWith } from 'rxjs';
import { CartService } from '../../../../core/services/cart/cart.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { CheckoutService, CreatePurchasePayload } from '../../../../core/services/checkout.service';
import {
CheckoutService,
PurchaseDetailItemResponse,
PurchaseDetailResponse,
} from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { BankAccount } from '../../../../core/services/tenant.interface';
import { CartItem } from '../../../../core/services/cart/cart.interface';
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
@@ -51,11 +52,12 @@ import {
})
export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly formBuilder = inject(FormBuilder);
private readonly cartService = inject(CartService);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService);
private readonly authService = inject(AuthService);
private readonly cartService = inject(CartService);
private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 60;
@@ -74,19 +76,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
telefono: ['', [Validators.required]],
});
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly cartSubtotal = computed(() => {
const cart = this.cartService.cart();
return cart ? parseFloat(cart.subtotal) : 0;
const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.subtotal) : 0;
});
protected readonly cartDiscount = computed(() => 0);
protected readonly cartTotal = computed(() => this.cartSubtotal() - this.cartDiscount());
protected readonly cartTotal = computed(() => {
const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.total) : this.cartSubtotal() - this.cartDiscount();
});
protected readonly mappedCartItems = computed<CartItemMock[]>(() => {
const cart = this.cartService.cart();
if (!cart || !cart.items) return [];
return cart.items.map((item) => this.mapCartItemToMock(item));
const purchase = this.createdPurchase();
return purchase ? purchase.items.map((item) => this.mapPurchaseItemToMock(item)) : [];
});
protected readonly isStep1Valid = signal(this.form.valid);
@@ -100,32 +106,19 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly transferAccount = signal<TransferAccount | null>(null);
protected readonly transferDni = signal<string>('');
protected readonly isCreatingPurchase = signal(false);
protected readonly isUpdatingPurchase = signal(false);
protected readonly isEditingItems = signal(false);
protected readonly isUpdatingItem = signal(false);
protected readonly isPreparingItemEdit = signal(false);
protected readonly createdPurchaseId = signal<number | null>(null);
protected readonly isGeneratingIntent = signal(false);
protected readonly isPaymentLoading = computed(
() => this.isGeneratingIntent() || this.cartService.isUpdating(),
);
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
protected readonly qrData = signal<string | null>(null);
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
protected readonly isCheckingQrPayment = signal(false);
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
constructor() {
effect(() => {
// We only want to trigger the intent generation when the cart changes.
// So we track the cart, but untrack the other signals to prevent duplicate calls.
const cart = this.cartService.cart();
untracked(() => {
const purchaseId = this.createdPurchaseId();
if (cart && purchaseId && !this.navigationStarted) {
// Trigger payment intent generation when cart changes and we are on the payment step
void this.selectPaymentMethod(this.selectedPaymentMethod());
}
});
});
this.form.statusChanges
.pipe(startWith(this.form.status))
.subscribe(() => this.isStep1Valid.set(this.form.valid));
@@ -144,68 +137,126 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
this.cartService.loadCart().subscribe();
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']);
return;
}
void this.loadPurchase(purchaseId);
}
ngOnDestroy(): void {
this.stopQrPolling();
}
private mapCartItemToMock(item: CartItem): CartItemMock {
const fullName = item.product?.nombre ?? '';
let product = fullName;
let attributes: { label: string; value: string }[] = [];
const match = fullName.match(/^(.*?)\s*\((.*?)\)$/);
if (match) {
product = match[1];
const attributesString = match[2];
attributes = attributesString.split(',').map((attr) => {
const parts = attr.split(':');
if (parts.length === 2) {
return { label: parts[0].trim(), value: parts[1].trim() };
}
return { label: '', value: attr.trim() };
});
}
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
return {
cartItemId: item.id,
imageUrl: item.product?.imagen ?? null,
product,
imageUrl: item.item_details.imagen,
product: item.item_details.nombre,
originalPrice: null,
discountedPrice: parseFloat(item.precio_unitario),
discountedPrice: parseFloat(item.unit_price),
discountPercentage: null,
attributes,
quantity: item.cantidad,
attributes: item.item_details.attributes.map((attribute) => ({
label: attribute.name,
value: attribute.value === null ? '' : String(attribute.value),
})),
quantity: item.quantity,
};
}
protected async onStep1Continue(): Promise<void> {
if (this.form.invalid) return;
protected async onEditingItemsChange(editing: boolean): Promise<void> {
if (this.isUpdatingItem() || this.isPreparingItemEdit()) {
return;
}
const tenant = this.tenantService.tenant();
if (!tenant) return;
if (!editing) {
this.isEditingItems.set(false);
this.isCreatingPurchase.set(true);
try {
const cart = this.cartService.cart();
if (!cart?.id) {
throw new Error('No hay un carrito activo para finalizar la compra.');
if (this.stepper?.currentStepIndex() === 1) {
void this.selectPaymentMethod(this.selectedPaymentMethod());
}
return;
}
this.isEditingItems.set(true);
this.stopQrPolling();
this.qrData.set(null);
this.qrPaymentStatus.set('idle');
this.transferAccount.set(null);
this.transferValidationStatus.set('idle');
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) {
this.isEditingItems.set(false);
return;
}
this.isPreparingItemEdit.set(true);
try {
const purchase = await this.checkoutService.prepareItemEditing(
tenant.codigo,
purchaseId,
);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to prepare purchase item editing:', error);
this.isEditingItems.set(false);
} finally {
this.isPreparingItemEdit.set(false);
}
}
protected async onPurchaseItemQuantityChange(event: {
item: CartItemMock;
quantity: number;
}): Promise<void> {
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
const itemId = event.item.cartItemId;
if (!tenant || !purchaseId || !itemId || this.isUpdatingItem() || !this.isEditingItems()) {
return;
}
this.isUpdatingItem.set(true);
try {
const purchase = await this.checkoutService.updateItemQuantity(
tenant.codigo,
purchaseId,
itemId,
event.quantity,
);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to update purchase item quantity:', error);
} finally {
this.isUpdatingItem.set(false);
}
}
protected async onStep1Continue(): Promise<void> {
if (this.form.invalid || this.isUpdatingPurchase() || this.isEditingItems()) return;
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) return;
this.isUpdatingPurchase.set(true);
try {
const formValue = this.form.getRawValue();
const payload: CreatePurchasePayload = {
cart_id: cart.id,
const purchase = await this.checkoutService.updateCustomerData(tenant.codigo, purchaseId, {
dni: formValue.dni,
telefono: formValue.telefono,
email: formValue.email,
nombre_apellido: formValue.nombre,
};
const response = await this.checkoutService.createPurchase(tenant.codigo, payload);
this.createdPurchaseId.set(response.id);
});
this.createdPurchase.set(purchase);
this.stepper.next();
@@ -215,17 +266,50 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
console.error('Failed to create purchase:', error);
// Here we could show an alert or toast
} finally {
this.isCreatingPurchase.set(false);
this.isUpdatingPurchase.set(false);
}
}
protected onCancel(): void {
protected async onCancel(): Promise<void> {
if (await this.canDeactivate()) {
void this.router.navigate(['/']);
}
}
public async canDeactivate(): Promise<boolean> {
this.stopQrPolling();
void this.router.navigate(['/']);
if (this.navigationStarted) {
return true;
}
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
if (!purchaseId || !tenant) {
return true;
}
try {
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
this.createdPurchaseId.set(null);
this.createdPurchase.set(null);
try {
await firstValueFrom(this.cartService.loadCart());
} catch (error) {
console.error('Failed to restore cart after cancelling checkout:', error);
}
return true;
} catch (error) {
console.error('Failed to cancel purchase:', error);
return false;
}
}
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
if (this.navigationStarted) {
if (this.navigationStarted || this.isEditingItems()) {
return;
}
@@ -266,6 +350,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
this.qrData.set(response.qr_data.qr_code);
this.markPurchasePendingPayment();
this.startQrPolling();
}
} catch (error) {
@@ -276,6 +361,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
protected async generateTransferIntent(dni: string): Promise<void> {
if (this.isEditingItems()) {
return;
}
const purchaseId = this.createdPurchaseId();
const tenant = this.tenantService.tenant();
@@ -291,10 +380,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
tenant.codigo,
purchaseId,
'transfer',
dni
dni,
);
if (response.transfer_data) {
this.markPurchasePendingPayment();
this.transferAccount.set({
titular: response.transfer_data.titular,
entidad: response.transfer_data.entidad,
@@ -334,6 +424,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
!purchaseId ||
!tenant ||
this.navigationStarted ||
this.isEditingItems() ||
this.transferValidationStatus() === 'checking'
) {
return;
@@ -448,11 +539,22 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
}
private handleConfirmedPayment(purchaseId: number): void {
this.navigateToPurchaseStatus(purchaseId, true);
private markPurchasePendingPayment(): void {
this.createdPurchase.update((purchase) =>
purchase
? {
...purchase,
status: 'pending_payment',
}
: purchase,
);
}
private navigateToPurchaseStatus(purchaseId: number, clearCart = false): void {
private handleConfirmedPayment(purchaseId: number): void {
this.navigateToPurchaseStatus(purchaseId);
}
private navigateToPurchaseStatus(purchaseId: number): void {
if (this.navigationStarted) {
return;
}
@@ -460,10 +562,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true;
this.stopQrPolling();
if (clearCart) {
this.cartService.clearCart();
}
void this.router.navigate(['/checkout/status', purchaseId]);
}
private async loadPurchase(purchaseId: number): Promise<void> {
const tenant = this.tenantService.tenant();
if (!tenant) {
void this.router.navigate(['/']);
return;
}
try {
const purchase = await this.checkoutService.getPurchase(tenant.codigo, purchaseId);
this.createdPurchaseId.set(purchase.id);
this.createdPurchase.set(purchase);
} catch (error) {
console.error('Failed to load purchase:', error);
void this.router.navigate(['/']);
}
}
}

View File

@@ -0,0 +1,8 @@
import { CanDeactivateFn } from '@angular/router';
interface PendingCheckoutComponent {
canDeactivate(): Promise<boolean>;
}
export const checkoutPendingPurchaseGuard: CanDeactivateFn<PendingCheckoutComponent> = (component) =>
component.canDeactivate();

View File

@@ -40,7 +40,11 @@
<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">
<button
type="button"
class="login-page__forgot-password btn btn-link p-0 border-0 text-decoration-none"
(click)="goToRecoverPassword()"
>
Olvide mi contraseña
</button>
</div>
@@ -56,7 +60,7 @@
>
{{ isSubmitting() ? 'Ingresando...' : 'Ingresar' }}
</app-button>
<app-button
type="button"
variant="borderless"

View File

@@ -9,6 +9,7 @@ import { InputComponent } from '../../../../shared/components/input/input.compon
const PASSWORD_MIN_LENGTH = 8;
const EMAIL_MAX_LENGTH = 255;
const POST_LOGIN_RETURN_URL_KEY = 'shopit.auth.return-url';
@Component({
selector: 'app-login-page',
@@ -53,6 +54,10 @@ export class LoginPageComponent {
void this.router.navigate(['/register']);
}
goToRecoverPassword(): void {
void this.router.navigate(['/recuperar-contrasena']);
}
onSubmit(): void {
this.submittedState.set(true);
this.serverErrorState.set(null);
@@ -80,6 +85,10 @@ export class LoginPageComponent {
this.serverErrorState.set(null);
try {
const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
if (returnUrl?.startsWith('/') && !returnUrl.startsWith('//')) {
this.document.defaultView?.sessionStorage.setItem(POST_LOGIN_RETURN_URL_KEY, returnUrl);
}
this.authService.loginWithGoogle();
} catch (error: unknown) {
this.serverErrorState.set(this.resolveErrorMessage(error));
@@ -127,8 +136,16 @@ export class LoginPageComponent {
}
protected redirectToHome(): void {
const homeUrl = this.router.serializeUrl(this.router.createUrlTree(['/']));
this.document.location.assign(homeUrl);
const requestedUrl =
this.route.snapshot.queryParamMap.get('returnUrl') ??
this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY);
const destination =
requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//')
? requestedUrl
: this.router.serializeUrl(this.router.createUrlTree(['/']));
this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY);
this.document.location.assign(destination);
}
private completeGoogleLogin(oauthCode: string): void {

View File

@@ -73,9 +73,12 @@
<app-button
class="product-detail__cta"
type="button"
[disabled]="!selectedVariantAvailable() || variantLoading()"
[disabled]="
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
"
(click)="buyNow()"
>
@if (variantLoading()) {
@if (variantLoading() || creatingDirectPurchase()) {
<div class="spinner-border spinner-border-sm" role="status"></div>
} @else {
Comprar

View File

@@ -1,4 +1,5 @@
import { TestBed, getTestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, Router } from '@angular/router';
import { By } from '@angular/platform-browser';
@@ -10,6 +11,9 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
import { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import {
PRODUCT_DETAIL_ERROR_MESSAGE,
ProductDetailResolvedData,
@@ -41,6 +45,7 @@ describe('ProductDetailPageComponent', () => {
let routerStub: any;
let cartServiceStub: any;
let toastServiceStub: any;
let checkoutServiceStub: any;
beforeAll(() => {
try {
@@ -72,6 +77,9 @@ describe('ProductDetailPageComponent', () => {
danger: vi.fn(),
info: vi.fn(),
};
checkoutServiceStub = {
startCheckout: vi.fn().mockResolvedValue({ id: 44 }),
};
});
async function configureTestingModule() {
@@ -100,6 +108,26 @@ describe('ProductDetailPageComponent', () => {
provide: ToastService,
useValue: toastServiceStub,
},
{
provide: CheckoutService,
useValue: checkoutServiceStub,
},
{
provide: TenantService,
useValue: { tenant: signal({ codigo: 'tenant-test' }) },
},
{
provide: AuthService,
useValue: {
user: signal({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
}),
},
},
],
}).compileComponents();
}
@@ -364,7 +392,7 @@ describe('ProductDetailPageComponent', () => {
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
});
it('renders purchase actions without side effects', async () => {
it('renders purchase actions and starts a direct checkout', async () => {
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
@@ -380,8 +408,18 @@ describe('ProductDetailPageComponent', () => {
buttons[0].click();
buttons[1].click();
await Promise.resolve();
expect(routerStub.navigate).not.toHaveBeenCalled();
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('tenant-test', {
direct_item: {
catalog_item_id: 1,
variant_id: null,
cantidad: 1,
},
});
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 44 },
});
});
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {

View File

@@ -28,6 +28,9 @@ import { ButtonComponent } from '../../../../shared/components/button/button.com
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
import { ProductDetailResolvedData } from './product-detail-page.resolver';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
@Component({
selector: 'app-product-detail-page',
@@ -50,6 +53,9 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
private readonly catalogService = inject(CatalogService);
private readonly toastService = inject(ToastService);
private readonly cartService = inject(CartService);
private readonly checkoutService = inject(CheckoutService);
private readonly tenantService = inject(TenantService);
private readonly authService = inject(AuthService);
private readonly attributeSelector = viewChild(ProductAttributeSelectorComponent);
private readonly carouselHost = viewChild<ElementRef<HTMLElement>>('carouselHost');
private readonly descriptionBody = viewChild<ElementRef<HTMLElement>>('descriptionBody');
@@ -77,6 +83,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly loading = signal(false);
protected readonly variantLoading = signal(false);
protected readonly addingToCart = signal(false);
protected readonly creatingDirectPurchase = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
protected readonly quantity = signal(1);
@@ -253,6 +260,55 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
});
}
protected async buyNow(): Promise<void> {
const currentProduct = this.product();
const variant = this.selectedVariant();
if (this.creatingDirectPurchase()) {
return;
}
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
return;
}
const tenant = this.tenantService.tenant();
const user = this.authService.user();
if (!user) {
void this.router.navigate(['/login'], {
queryParams: { returnUrl: `/producto/${currentProduct.id}` },
});
return;
}
if (!tenant) {
this.toastService.danger('No se pudo identificar la tienda.');
return;
}
this.creatingDirectPurchase.set(true);
try {
const purchase = await this.checkoutService.startCheckout(tenant.codigo, {
direct_item: {
catalog_item_id: currentProduct.id,
variant_id: variant?.id ?? null,
cantidad: this.quantity(),
},
});
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
} catch (error) {
console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.');
} finally {
this.creatingDirectPurchase.set(false);
}
}
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
}

View File

@@ -57,6 +57,20 @@
Actualizar estado
</app-button>
</div>
} @else if (status() === 'expired') {
<div class="status-content__section status-content__section--primary">
<div class="status-content__icon status-content__icon--warning">
<i class="fa-solid fa-clock"></i>
</div>
<h2 class="status-content__title">LA COMPRA VENCI&Oacute;</h2>
<p class="status-content__subtitle">El plazo de pago termin&oacute; y liberamos el stock reservado.</p>
</div>
<hr class="status-content__divider" />
<div class="status-content__section status-content__section--secondary">
<p class="status-content__message">Pod&eacute;s volver a la tienda e iniciar una nueva compra.</p>
</div>
} @else if (status() === 'rejected') {
<div class="status-content__section status-content__section--primary">
<div class="status-content__icon status-content__icon--error">

View File

@@ -5,7 +5,7 @@ import { CheckoutService, PurchaseStatusResponse } from '../../../../core/servic
import { TenantService } from '../../../../core/services/tenant.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component';
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'error';
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
@Component({
selector: 'app-purchase-status-page',
@@ -93,6 +93,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'rejected';
}
if (purchase.status === 'expired') {
return 'expired';
}
return 'pending';
}

View File

@@ -0,0 +1,106 @@
<header class="recover-password-code-page__header text-center mb-4">
<h1 id="recover-password-code-title" class="auth-title mb-4">Ingresá el código</h1>
<p class="recover-password-code-page__description mb-0">
Te enviamos un código a <strong>{{ email }}</strong>
</p>
<p class="recover-password-code-page__description fst-italic mb-0">
Recordá revisar en Correo no deseado.
</p>
</header>
<form
class="recover-password-code-page__form d-grid gap-4"
novalidate
aria-labelledby="recover-password-code-title"
[formGroup]="form"
(ngSubmit)="onSubmit()"
>
<div>
<fieldset class="border-0 p-0 m-0">
<legend class="visually-hidden">Código de recuperación de cuatro dígitos</legend>
<div class="recover-password-code-page__inputs d-flex justify-content-center gap-2">
<app-input
id="recover-password-code-digit-1"
type="text"
[maxlength]="1"
[value]="form.controls.digit1.value"
[invalid]="isCodeInvalid()"
(valueChange)="updateDigit('digit1', $event)"
(pasteEvent)="pasteCode($event)"
/>
<app-input
id="recover-password-code-digit-2"
type="text"
[maxlength]="1"
[value]="form.controls.digit2.value"
[invalid]="isCodeInvalid()"
(valueChange)="updateDigit('digit2', $event)"
(pasteEvent)="pasteCode($event)"
/>
<app-input
id="recover-password-code-digit-3"
type="text"
[maxlength]="1"
[value]="form.controls.digit3.value"
[invalid]="isCodeInvalid()"
(valueChange)="updateDigit('digit3', $event)"
(pasteEvent)="pasteCode($event)"
/>
<app-input
id="recover-password-code-digit-4"
type="text"
[maxlength]="1"
[value]="form.controls.digit4.value"
[invalid]="isCodeInvalid()"
(valueChange)="updateDigit('digit4', $event)"
(pasteEvent)="pasteCode($event)"
/>
</div>
</fieldset>
@if (isCodeInvalid()) {
<small class="text-danger d-block text-center mt-2">
Ingresá los cuatro dígitos del código.
</small>
}
@if (serverError(); as errorMessage) {
<small class="text-danger d-block text-center mt-2" role="alert">
{{ errorMessage }}
</small>
}
<div class="text-center">
<app-button
type="button"
variant="borderless"
buttonClass="recover-password-code-page__resend-action px-3 py-2"
[disabled]="isResending()"
(click)="resendCode()"
>
{{ isResending() ? 'Reenviando...' : 'Reenviar Código' }}
</app-button>
</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() ? 'Validando...' : 'Validar' }}
</app-button>
<app-button
type="button"
variant="borderless"
hostClass="w-100 d-block text-center"
buttonClass="recover-password-code-page__back-action px-3 py-2"
(click)="goBack()"
>
Volver
</app-button>
</div>
</form>

View File

@@ -0,0 +1,65 @@
:host {
display: block;
}
.recover-password-code-page__description {
color: #a0a0a0;
font-size: 12px;
font-weight: 325;
}
.recover-password-code-page__form {
width: 100%;
}
.recover-password-code-page__inputs app-input {
width: 52px;
}
:host ::ng-deep .recover-password-code-page__inputs .form-control {
min-height: 52px;
padding: 0.5rem;
text-align: center;
font-size: 20px;
}
:host ::ng-deep .recover-password-code-page__resend-action {
min-height: 36px;
color: #a0a0a0 !important;
font-size: 12px !important;
font-weight: 400 !important;
transition:
color 0.15s ease,
transform 0.1s ease;
}
:host ::ng-deep .recover-password-code-page__resend-action:hover,
:host ::ng-deep .recover-password-code-page__resend-action:focus-visible {
color: #8a8a8a !important;
}
:host ::ng-deep .recover-password-code-page__resend-action:hover {
transform: translateY(-1px);
}
:host ::ng-deep .recover-password-code-page__resend-action:active {
color: #666666 !important;
transform: translateY(1px);
}
:host ::ng-deep .recover-password-code-page__back-action {
min-height: 40px;
transition:
color 0.15s ease,
transform 0.1s ease;
}
:host ::ng-deep .recover-password-code-page__back-action:hover,
:host ::ng-deep .recover-password-code-page__back-action:focus-visible {
transform: translateY(-1px);
}
:host ::ng-deep .recover-password-code-page__back-action:active {
opacity: 0.75;
transform: translateY(1px);
}

View File

@@ -0,0 +1,313 @@
import { HttpResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap, provideRouter, Router } from '@angular/router';
import { of, throwError } from 'rxjs';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { ToastService } from '../../../../core/services/toast.service';
import { RecoverPasswordCodePageComponent } from './recover-password-code-page.component';
describe('RecoverPasswordCodePageComponent', () => {
let validatePasswordResetCode: ReturnType<typeof vi.fn>;
let requestPasswordReset: ReturnType<typeof vi.fn>;
let showDangerToast: ReturnType<typeof vi.fn>;
let showSuccessToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
TestBed.resetTestingModule();
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
validatePasswordResetCode = vi.fn(() => of(new HttpResponse({
body: {
message: 'Código validado correctamente.',
status: 'validated' as const,
},
status: 200,
})));
requestPasswordReset = vi.fn(() => of(new HttpResponse({
body: {
message: 'Solicitud aceptada.',
status: 'pending' as const,
},
status: 202,
})));
showDangerToast = vi.fn();
showSuccessToast = vi.fn();
});
afterEach(() => {
vi.restoreAllMocks();
});
function authProviders() {
return [
{
provide: AuthService,
useValue: { requestPasswordReset, validatePasswordResetCode },
},
{
provide: ToastService,
useValue: { danger: showDangerToast, success: showSuccessToast },
},
];
}
it('shows the email received from the recovery flow', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('ada@example.com');
});
it('moves focus to the next input after entering a digit', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
fixture.detectChanges();
const inputs = fixture.nativeElement.querySelectorAll('input');
inputs[0].focus();
component.updateDigit('digit1', '1');
expect(document.activeElement).toBe(inputs[1]);
});
it('distributes a pasted four-digit code across all inputs', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
fixture.detectChanges();
const inputs = fixture.nativeElement.querySelectorAll('input');
const pasteEvent = new Event('paste', {
bubbles: true,
cancelable: true,
});
Object.defineProperty(pasteEvent, 'clipboardData', {
value: {
getData: () => '01 23',
},
});
inputs[0].dispatchEvent(pasteEvent);
fixture.detectChanges();
expect(pasteEvent.defaultPrevented).toBe(true);
expect(component.form.getRawValue()).toEqual({
digit1: '0',
digit2: '1',
digit3: '2',
digit4: '3',
});
expect(component.form.valid).toBe(true);
expect(document.activeElement).toBe(inputs[3]);
});
it('accepts only a complete four-digit code and navigates back preserving the email', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.updateDigit('digit1', '1');
component.updateDigit('digit2', 'a2');
component.updateDigit('digit3', '3');
component.updateDigit('digit4', '4');
expect(component.form.getRawValue()).toEqual({
digit1: '1',
digit2: '2',
digit3: '3',
digit4: '4',
});
expect(component.form.valid).toBe(true);
component.goBack();
expect(navigateSpy).toHaveBeenCalledWith(['/recuperar-contrasena'], {
queryParams: { email: 'ada@example.com' },
});
});
it('continues to the reset password page with the email and code', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.setValue({
digit1: '1',
digit2: '2',
digit3: '3',
digit4: '4',
});
component.onSubmit();
expect(validatePasswordResetCode).toHaveBeenCalledWith('ada@example.com', '1234');
expect(navigateSpy).toHaveBeenCalledWith(['/recuperar-contrasena/restablecer'], {
queryParams: {
email: 'ada@example.com',
code: '1234',
},
});
});
it('shows the validation error and stays on the code page', async () => {
validatePasswordResetCode.mockReturnValue(throwError(() => ({
error: {
errors: {
codigo: ['El código ingresado es inválido.'],
},
},
})));
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.setValue({
digit1: '9',
digit2: '9',
digit3: '9',
digit4: '9',
});
component.onSubmit();
expect(navigateSpy).not.toHaveBeenCalled();
expect(component.serverError()).toBe('El código ingresado es inválido.');
expect(showDangerToast).toHaveBeenCalledWith('El código ingresado es inválido.');
});
it('requests a new code and clears the previous digits', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordCodePageComponent],
providers: [
provideRouter([]),
...authProviders(),
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({ email: 'ada@example.com' }),
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordCodePageComponent);
const component = fixture.componentInstance as any;
fixture.detectChanges();
component.form.setValue({
digit1: '1',
digit2: '2',
digit3: '3',
digit4: '4',
});
component.resendCode();
expect(requestPasswordReset).toHaveBeenCalledWith('ada@example.com');
expect(component.form.getRawValue()).toEqual({
digit1: '',
digit2: '',
digit3: '',
digit4: '',
});
expect(showSuccessToast).toHaveBeenCalledWith('Código reenviado correctamente.');
});
});

View File

@@ -0,0 +1,191 @@
import { ChangeDetectionStrategy, Component, inject, signal, viewChildren } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component';
import { InputComponent } from '../../../../shared/components/input/input.component';
type CodeControlName = 'digit1' | 'digit2' | 'digit3' | 'digit4';
const CODE_CONTROL_NAMES: CodeControlName[] = ['digit1', 'digit2', 'digit3', 'digit4'];
@Component({
selector: 'app-recover-password-code-page',
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
templateUrl: './recover-password-code-page.component.html',
styleUrl: './recover-password-code-page.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RecoverPasswordCodePageComponent {
private readonly formBuilder = inject(FormBuilder);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly authService = inject(AuthService);
private readonly toastService = inject(ToastService);
private readonly submittedState = signal(false);
private readonly isSubmittingState = signal(false);
private readonly isResendingState = signal(false);
private readonly serverErrorState = signal<string | null>(null);
private readonly digitInputs = viewChildren(InputComponent);
protected readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
protected readonly form = this.formBuilder.nonNullable.group({
digit1: ['', [Validators.required, Validators.pattern(/^\d$/)]],
digit2: ['', [Validators.required, Validators.pattern(/^\d$/)]],
digit3: ['', [Validators.required, Validators.pattern(/^\d$/)]],
digit4: ['', [Validators.required, Validators.pattern(/^\d$/)]],
});
protected readonly submitted = this.submittedState.asReadonly();
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
protected readonly isResending = this.isResendingState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly();
protected updateDigit(controlName: CodeControlName, value: string | number): void {
const digit = String(value).replace(/\D/g, '').slice(-1);
this.form.controls[controlName].setValue(digit);
const currentIndex = CODE_CONTROL_NAMES.indexOf(controlName);
if (digit && currentIndex < CODE_CONTROL_NAMES.length - 1) {
this.digitInputs()[currentIndex + 1]?.focus();
}
}
protected pasteCode(event: ClipboardEvent): void {
event.preventDefault();
const pastedText = event.clipboardData?.getData('text') ?? '';
const digits = pastedText.replace(/\D/g, '');
if (digits.length !== CODE_CONTROL_NAMES.length) {
console.warn('Password reset code paste was rejected because it did not contain four digits.', {
digitCount: digits.length,
});
this.showServerError('Pegá un código de cuatro dígitos.');
return;
}
CODE_CONTROL_NAMES.forEach((controlName, index) => {
this.form.controls[controlName].setValue(digits[index]);
});
this.submittedState.set(false);
this.serverErrorState.set(null);
this.digitInputs()[CODE_CONTROL_NAMES.length - 1]?.focus();
}
protected isCodeInvalid(): boolean {
return this.form.invalid && this.submitted();
}
protected onSubmit(): void {
this.submittedState.set(true);
this.serverErrorState.set(null);
if (this.form.invalid || this.isSubmitting()) {
this.form.markAllAsTouched();
return;
}
const code = Object.values(this.form.getRawValue()).join('');
if (!this.email) {
console.warn('Password reset code validation cannot start without an email.');
this.showServerError('No se pudo identificar la solicitud de recuperación.');
return;
}
this.isSubmittingState.set(true);
this.authService.validatePasswordResetCode(this.email, code).subscribe({
next: (response) => {
this.isSubmittingState.set(false);
if (response.status !== 200 || response.body?.status !== 'validated') {
console.warn('Password reset code validation returned an unexpected status.', {
httpStatus: response.status,
attemptStatus: response.body?.status ?? null,
});
this.showServerError('No se pudo validar el código. Intenta nuevamente.');
return;
}
void this.router.navigate(['/recuperar-contrasena/restablecer'], {
queryParams: {
email: this.email,
code,
},
});
},
error: (error: unknown) => {
this.isSubmittingState.set(false);
console.error('Password reset code validation request failed.', error);
this.showServerError(this.resolveErrorMessage(error));
},
});
}
protected resendCode(): void {
if (!this.email || this.isResending()) {
return;
}
this.serverErrorState.set(null);
this.isResendingState.set(true);
this.authService.requestPasswordReset(this.email).subscribe({
next: (response) => {
this.isResendingState.set(false);
if (response.status !== 202 || response.body?.status !== 'pending') {
console.warn('Password reset code resend returned an unexpected status.', {
httpStatus: response.status,
attemptStatus: response.body?.status ?? null,
});
this.showServerError('No se pudo reenviar el código. Intenta nuevamente.');
return;
}
this.submittedState.set(false);
this.form.reset();
this.digitInputs()[0]?.focus();
this.toastService.success('Código reenviado correctamente.');
},
error: (error: unknown) => {
this.isResendingState.set(false);
console.error('Password reset code resend request failed.', error);
this.showServerError(this.resolveErrorMessage(error));
},
});
}
protected goBack(): void {
void this.router.navigate(['/recuperar-contrasena'], {
queryParams: this.email ? { email: this.email } : undefined,
});
}
private showServerError(message: string): void {
this.serverErrorState.set(message);
this.toastService.danger(message);
}
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 codeMessages = errorPayload?.errors?.['codigo'];
const codeError = Array.isArray(codeMessages) ? codeMessages[0] : null;
if (typeof codeError === 'string' && codeError.trim()) {
return codeError;
}
if (typeof errorPayload?.message === 'string' && errorPayload.message.trim()) {
return errorPayload.message;
}
return 'No se pudo validar el código. Intenta nuevamente.';
}
}

View File

@@ -0,0 +1,53 @@
<header class="recover-password-page__header text-center mb-4">
<h1 id="recover-password-title" class="auth-title mb-3">Recuperar contraseña</h1>
<p class="recover-password-page__description mb-0">
Ingresá tu Email para restablecer tu Contraseña.
</p>
</header>
<form
class="recover-password-page__form d-grid gap-3"
novalidate
aria-labelledby="recover-password-title"
[formGroup]="form"
(ngSubmit)="onSubmit()"
>
<div class="d-grid gap-1">
<label class="visually-hidden" for="recover-password-email">Email</label>
<app-input
id="recover-password-email"
type="email"
placeholder="Email"
[value]="form.controls.email.value"
[invalid]="showEmailError()"
(valueChange)="updateEmail($event)"
/>
@if (getEmailError(); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small>
}
@if (serverError(); as errorMessage) {
<small class="text-danger" role="alert">{{ errorMessage }}</small>
}
</div>
<div class="d-grid gap-2 text-center">
<app-button
type="submit"
hostClass="w-100 d-block"
buttonClass="w-100"
[disabled]="isSubmitting()"
>
{{ isSubmitting() ? 'Enviando...' : 'Recuperar acceso' }}
</app-button>
<app-button
type="button"
variant="borderless"
hostClass="w-100 d-block text-center"
buttonClass="recover-password-page__back-action px-3 py-2"
(click)="goToLogin()"
>
Volver
</app-button>
</div>
</form>

View File

@@ -0,0 +1,17 @@
:host {
display: block;
}
.recover-password-page__description {
color: #a0a0a0;
font-size: 12px;
font-weight: 325;
}
.recover-password-page__form {
width: 100%;
}
.recover-password-page__back-action {
min-height: 40px;
}

View File

@@ -0,0 +1,139 @@
import { HttpResponse } from '@angular/common/http';
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 { ToastService } from '../../../../core/services/toast.service';
import { RecoverPasswordPageComponent } from './recover-password-page.component';
describe('RecoverPasswordPageComponent', () => {
let requestPasswordReset: ReturnType<typeof vi.fn>;
let showDangerToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
TestBed.resetTestingModule();
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
requestPasswordReset = vi.fn(() => of(new HttpResponse({
body: {
message: 'Solicitud aceptada.',
status: 'pending' as const
},
status: 202
})));
showDangerToast = vi.fn();
});
afterEach(() => {
vi.restoreAllMocks();
});
function authProviders() {
return [
{ provide: AuthService, useValue: { requestPasswordReset } },
{ provide: ToastService, useValue: { danger: showDangerToast } }
];
}
it('validates the email before submitting', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordPageComponent],
providers: [provideRouter([]), ...authProviders()],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordPageComponent);
const component = fixture.componentInstance as any;
component.form.controls.email.setValue('invalid-email');
component.onSubmit();
expect(component.form.invalid).toBe(true);
expect(component.getEmailError()).toBe('Ingresa un email válido.');
});
it('navigates back to login', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordPageComponent],
providers: [provideRouter([]), ...authProviders()],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.goToLogin();
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
});
it('continues to the code page with the entered email', async () => {
await TestBed.configureTestingModule({
imports: [RecoverPasswordPageComponent],
providers: [provideRouter([]), ...authProviders()],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.controls.email.setValue('ada@example.com');
component.onSubmit();
expect(requestPasswordReset).toHaveBeenCalledWith('ada@example.com');
expect(navigateSpy).toHaveBeenCalledWith(['/recuperar-contrasena/codigo'], {
queryParams: { email: 'ada@example.com' },
});
});
it('stays on the page when the endpoint does not finish as pending', async () => {
requestPasswordReset.mockReturnValue(of(new HttpResponse({
body: null,
status: 200
})));
await TestBed.configureTestingModule({
imports: [RecoverPasswordPageComponent],
providers: [provideRouter([]), ...authProviders()],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.controls.email.setValue('ada@example.com');
component.onSubmit();
expect(navigateSpy).not.toHaveBeenCalled();
expect(component.serverError()).toBe(
'No se pudo iniciar la recuperación. Intenta nuevamente.',
);
expect(showDangerToast).toHaveBeenCalled();
});
it('shows the API error and does not navigate when the request fails', async () => {
requestPasswordReset.mockReturnValue(throwError(() => ({
error: { message: 'Servicio temporalmente no disponible.' }
})));
await TestBed.configureTestingModule({
imports: [RecoverPasswordPageComponent],
providers: [provideRouter([]), ...authProviders()],
}).compileComponents();
const fixture = TestBed.createComponent(RecoverPasswordPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.controls.email.setValue('ada@example.com');
component.onSubmit();
expect(navigateSpy).not.toHaveBeenCalled();
expect(component.serverError()).toBe('Servicio temporalmente no disponible.');
expect(showDangerToast).toHaveBeenCalledWith('Servicio temporalmente no disponible.');
});
});

View File

@@ -0,0 +1,135 @@
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../../../core/services/auth/auth.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 EMAIL_MAX_LENGTH = 255;
@Component({
selector: 'app-recover-password-page',
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
templateUrl: './recover-password-page.component.html',
styleUrl: './recover-password-page.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RecoverPasswordPageComponent {
private readonly formBuilder = inject(FormBuilder);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly authService = inject(AuthService);
private readonly toastService = inject(ToastService);
private readonly submittedState = signal(false);
private readonly isSubmittingState = signal(false);
private readonly serverErrorState = signal<string | null>(null);
protected readonly form = this.formBuilder.nonNullable.group({
email: [
this.route.snapshot.queryParamMap.get('email') ?? '',
[Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)],
],
});
protected readonly submitted = this.submittedState.asReadonly();
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly();
protected updateEmail(value: string | number): void {
this.form.controls.email.setValue(String(value));
}
protected showEmailError(): boolean {
const email = this.form.controls.email;
return email.invalid && (email.touched || this.submitted());
}
protected getEmailError(): string | null {
const email = this.form.controls.email;
if (!this.showEmailError()) {
return null;
}
if (email.hasError('required')) {
return 'Este campo es obligatorio.';
}
if (email.hasError('maxlength')) {
return `No puede superar los ${EMAIL_MAX_LENGTH} caracteres.`;
}
if (email.hasError('email')) {
return 'Ingresa un email válido.';
}
return 'El valor ingresado no es válido.';
}
protected onSubmit(): void {
this.submittedState.set(true);
this.serverErrorState.set(null);
if (this.form.invalid || this.isSubmitting()) {
this.form.markAllAsTouched();
return;
}
const email = this.form.controls.email.value;
this.isSubmittingState.set(true);
this.authService.requestPasswordReset(email).subscribe({
next: (response) => {
this.isSubmittingState.set(false);
if (response.status !== 202 || response.body?.status !== 'pending') {
console.warn('Password reset attempt returned an unexpected status.', {
httpStatus: response.status,
attemptStatus: response.body?.status ?? null,
});
this.showServerError('No se pudo iniciar la recuperación. Intenta nuevamente.');
return;
}
void this.router.navigate(['/recuperar-contrasena/codigo'], {
queryParams: { email },
});
},
error: (error: unknown) => {
this.isSubmittingState.set(false);
console.error('Password reset attempt request failed.', error);
this.showServerError(this.resolveErrorMessage(error));
},
});
}
protected goToLogin(): void {
void this.router.navigate(['/login']);
}
private showServerError(message: string): void {
this.serverErrorState.set(message);
this.toastService.danger(message);
}
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 emailMessages = errorPayload?.errors?.['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 la recuperación. Intenta nuevamente.';
}
}

View File

@@ -0,0 +1,56 @@
<header class="reset-password-page__header text-center mb-4">
<h1 id="reset-password-title" class="auth-title">Restablecer contraseña</h1>
</header>
<form
class="reset-password-page__form d-grid gap-3"
novalidate
aria-labelledby="reset-password-title"
[formGroup]="form"
(ngSubmit)="onSubmit()"
>
<div class="d-grid gap-1">
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
<app-input
id="reset-password-new"
type="password"
placeholder="Nueva Contraseña"
[value]="form.controls.password.value"
[invalid]="showControlError('password')"
(valueChange)="updatePassword('password', $event)"
/>
@if (getControlError('password'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small>
}
</div>
<div class="d-grid gap-1">
<label class="visually-hidden" for="reset-password-confirmation">
Repetir Nueva Contraseña
</label>
<app-input
id="reset-password-confirmation"
type="password"
placeholder="Repetir Nueva Contraseña"
[value]="form.controls.password_confirmation.value"
[invalid]="showControlError('password_confirmation')"
(valueChange)="updatePassword('password_confirmation', $event)"
/>
@if (getControlError('password_confirmation'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small>
}
</div>
@if (serverError(); as errorMessage) {
<small class="text-danger" role="alert">{{ errorMessage }}</small>
}
<app-button
type="submit"
hostClass="w-100 d-block"
buttonClass="w-100"
[disabled]="isSubmitting()"
>
{{ isSubmitting() ? 'Guardando...' : 'Guardar' }}
</app-button>
</form>

View File

@@ -0,0 +1,7 @@
:host {
display: block;
}
.reset-password-page__form {
width: 100%;
}

View File

@@ -0,0 +1,148 @@
import { HttpResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap, 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 { ResetPasswordPageComponent } from './reset-password-page.component';
describe('ResetPasswordPageComponent', () => {
let resetPassword: ReturnType<typeof vi.fn>;
let showDangerToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
TestBed.resetTestingModule();
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
resetPassword = vi.fn(() => of(new HttpResponse({
body: {
message: 'Contraseña modificada correctamente.',
status: 'used' as const,
},
status: 200,
})));
showDangerToast = vi.fn();
});
afterEach(() => {
vi.restoreAllMocks();
});
function resetProviders(modalService: { openSimple: ReturnType<typeof vi.fn> }) {
return [
provideRouter([]),
{ provide: AuthService, useValue: { resetPassword } },
{ provide: ModalService, useValue: modalService },
{ provide: ToastService, useValue: { danger: showDangerToast } },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParamMap: convertToParamMap({
email: 'ada@example.com',
code: '1234',
}),
},
},
},
];
}
it('rejects passwords that do not match', async () => {
const modalService = {
openSimple: vi.fn(),
};
await TestBed.configureTestingModule({
imports: [ResetPasswordPageComponent],
providers: resetProviders(modalService),
}).compileComponents();
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
const component = fixture.componentInstance as any;
component.form.setValue({
password: 'Secret!123',
password_confirmation: 'Different!123',
});
component.onSubmit();
expect(component.form.hasError('passwordMismatch')).toBe(true);
expect(component.getControlError('password_confirmation')).toBe(
'Las contraseñas no coinciden.',
);
expect(modalService.openSimple).not.toHaveBeenCalled();
expect(resetPassword).not.toHaveBeenCalled();
});
it('shows the success modal and returns to login for matching passwords', async () => {
const modalService = {
openSimple: vi.fn().mockReturnValue(of(undefined)),
};
await TestBed.configureTestingModule({
imports: [ResetPasswordPageComponent],
providers: resetProviders(modalService),
}).compileComponents();
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
component.form.setValue({
password: 'Secret!123',
password_confirmation: 'Secret!123',
});
component.onSubmit();
expect(component.form.valid).toBe(true);
expect(component.getControlError('password_confirmation')).toBeNull();
expect(resetPassword).toHaveBeenCalledWith({
email: 'ada@example.com',
codigo: '1234',
password: 'Secret!123',
password_confirmation: 'Secret!123',
});
expect(modalService.openSimple).toHaveBeenCalledWith({
content: 'Contraseña modificada correctamente',
buttonLabel: 'Cerrar',
});
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
});
it('shows the API error without opening the success modal', async () => {
resetPassword.mockReturnValue(throwError(() => ({
error: {
errors: {
codigo: ['La solicitud de recuperación es inválida o ya fue utilizada.'],
},
},
})));
const modalService = {
openSimple: vi.fn(),
};
await TestBed.configureTestingModule({
imports: [ResetPasswordPageComponent],
providers: resetProviders(modalService),
}).compileComponents();
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
const component = fixture.componentInstance as any;
component.form.setValue({
password: 'Secret!123',
password_confirmation: 'Secret!123',
});
component.onSubmit();
expect(modalService.openSimple).not.toHaveBeenCalled();
expect(component.serverError()).toBe(
'La solicitud de recuperación es inválida o ya fue utilizada.',
);
expect(showDangerToast).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,193 @@
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import {
AbstractControl,
FormBuilder,
ReactiveFormsModule,
ValidationErrors,
ValidatorFn,
Validators,
} from '@angular/forms';
import { ActivatedRoute, 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 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 };
};
type PasswordControlName = 'password' | 'password_confirmation';
@Component({
selector: 'app-reset-password-page',
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
templateUrl: './reset-password-page.component.html',
styleUrl: './reset-password-page.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ResetPasswordPageComponent {
private readonly formBuilder = inject(FormBuilder);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly authService = inject(AuthService);
private readonly modalService = inject(ModalService);
private readonly toastService = inject(ToastService);
private readonly submittedState = signal(false);
private readonly isSubmittingState = signal(false);
private readonly serverErrorState = signal<string | null>(null);
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
protected readonly form = this.formBuilder.nonNullable.group(
{
password: [
'',
[
Validators.required,
Validators.minLength(PASSWORD_MIN_LENGTH),
Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).+$/),
],
],
password_confirmation: ['', [Validators.required]],
},
{
validators: [passwordsMatchValidator],
},
);
protected readonly submitted = this.submittedState.asReadonly();
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly();
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
this.form.controls[controlName].setValue(String(value));
}
protected showControlError(controlName: PasswordControlName): 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: PasswordControlName): 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('minlength')) {
return `Debe tener al menos ${PASSWORD_MIN_LENGTH} caracteres.`;
}
if (controlName === 'password' && control.hasError('pattern')) {
return 'Debe contener mayúscula, minúscula y un carácter especial.';
}
if (controlName === 'password_confirmation' && this.form.hasError('passwordMismatch')) {
return 'Las contraseñas no coinciden.';
}
return 'El valor ingresado no es válido.';
}
protected onSubmit(): void {
this.submittedState.set(true);
this.serverErrorState.set(null);
if (this.form.invalid || this.isSubmitting()) {
this.form.markAllAsTouched();
return;
}
if (!this.email || !/^\d{4}$/.test(this.code)) {
console.warn('Password reset cannot start without a validated recovery request.');
this.showServerError('La solicitud de recuperación es inválida.');
return;
}
this.isSubmittingState.set(true);
this.authService.resetPassword({
email: this.email,
codigo: this.code,
...this.form.getRawValue(),
}).subscribe({
next: (response) => {
this.isSubmittingState.set(false);
if (response.status !== 200 || response.body?.status !== 'used') {
console.warn('Password reset returned an unexpected status.', {
httpStatus: response.status,
attemptStatus: response.body?.status ?? null,
});
this.showServerError('No se pudo modificar la contraseña. Intenta nuevamente.');
return;
}
this.modalService
.openSimple({
content: 'Contraseña modificada correctamente',
buttonLabel: 'Cerrar',
})
.subscribe(() => {
void this.router.navigate(['/login']);
});
},
error: (error: unknown) => {
this.isSubmittingState.set(false);
console.error('Password reset request failed.', error);
this.showServerError(this.resolveErrorMessage(error));
},
});
}
private showServerError(message: string): void {
this.serverErrorState.set(message);
this.toastService.danger(message);
}
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 errors = errorPayload?.errors;
for (const field of ['codigo', 'password'] as const) {
const messages = errors?.[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 modificar la contraseña. Intenta nuevamente.';
}
}

View File

@@ -6,9 +6,13 @@ import { authGuard, guestOnlyGuard } from '../../core/services/auth/auth.guards'
import { LoginPageComponent } from './pages/login-page/login-page.component';
import { hasMenuGuard } from '../../core/guards/menu.guard';
import { productDetailResolver } from './pages/product-detail-page/product-detail-page.resolver';
import { RecoverPasswordCodePageComponent } from './pages/recover-password-code-page/recover-password-code-page.component';
import { RecoverPasswordPageComponent } from './pages/recover-password-page/recover-password-page.component';
import { ResetPasswordPageComponent } from './pages/reset-password-page/reset-password-page.component';
import { RegisterPageComponent } from './pages/register-page/register-page.component';
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
import { storeHomeCatalogResolver } from './pages/store-home-page/store-home-page.resolver';
import { checkoutPendingPurchaseGuard } from './pages/checkout-page/checkout-page.guard';
export const routes: Routes = [
{
@@ -45,6 +49,25 @@ export const routes: Routes = [
},
],
},
{
path: 'recuperar-contrasena',
canActivate: [guestOnlyGuard],
component: SimpleLayoutComponent,
children: [
{
path: '',
component: RecoverPasswordPageComponent,
},
{
path: 'codigo',
component: RecoverPasswordCodePageComponent,
},
{
path: 'restablecer',
component: ResetPasswordPageComponent,
},
],
},
{
path: 'buscar',
loadComponent: () =>
@@ -64,6 +87,7 @@ export const routes: Routes = [
{
path: 'checkout',
canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent,

View File

@@ -34,20 +34,25 @@
}
</div>
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
<app-quantity-selector
size="small"
[quantity]="quantity()"
(quantityChange)="onQuantityChange($event)"
(increase)="onIncrease()"
(decrease)="onDecrease()"
/>
<app-icon-button
variant="trash"
class="cart-item-remove-btn"
(click)="onRemove()"
/>
</div>
@if (!readonly()) {
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
<app-quantity-selector
size="small"
[quantity]="quantity()"
[disabled]="quantityDisabled()"
(quantityChange)="onQuantityChange($event)"
(increase)="onIncrease()"
(decrease)="onDecrease()"
/>
@if (!quantityDisabled() && showRemove()) {
<app-icon-button
variant="trash"
class="cart-item-remove-btn"
(click)="onRemove()"
/>
}
</div>
}
</div>
</article>

View File

@@ -23,6 +23,9 @@ export class CartItemComponent {
readonly discountPercentage = input<number | null>(null);
readonly attributes = input<CartItemAttribute[]>([]);
readonly quantity = input<number>(1);
readonly readonly = input<boolean>(false);
readonly quantityDisabled = input<boolean>(false);
readonly showRemove = input<boolean>(true);
readonly quantityChange = output<number>();
readonly remove = output<void>();
@@ -30,6 +33,7 @@ export class CartItemComponent {
readonly decrease = output<void>();
protected onQuantityChange(newQuantity: number): void {
if (this.quantityDisabled()) return;
this.quantityChange.emit(newQuantity);
}

View File

@@ -5,16 +5,30 @@
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
@if (showClose()) {
<button
class="btn btn-link p-0 border-0 d-inline-flex align-items-center justify-content-center cart-close-btn"
type="button"
aria-label="Cerrar carrito"
(click)="closed.emit()"
>
<i class="fa-solid fa-xmark"></i>
</button>
}
<div class="d-flex align-items-center cart-header-actions">
@if (!readonly() && allowEditing() && items().length > 0) {
<button
class="btn btn-link p-0 border-0 cart-edit-btn"
type="button"
[attr.aria-pressed]="editing()"
[disabled]="editingDisabled()"
(click)="toggleEditing()"
>
{{ editing() ? 'Listo' : 'Modificar' }}
</button>
}
@if (showClose()) {
<button
class="btn btn-link p-0 border-0 d-inline-flex align-items-center justify-content-center cart-close-btn"
type="button"
aria-label="Cerrar carrito"
(click)="closed.emit()"
>
<i class="fa-solid fa-xmark"></i>
</button>
}
</div>
</header>
<div class="d-grid w-100 flex-grow-1 overflow-y-auto cart-items-container">
@@ -31,6 +45,9 @@
[discountPercentage]="item.discountPercentage"
[attributes]="item.attributes"
[quantity]="getItemQuantity(item)"
[readonly]="readonly()"
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
[showRemove]="allowRemove()"
(quantityChange)="onItemQuantityChange(idx, $event)"
(remove)="onItemRemove(idx)"
/>

View File

@@ -21,6 +21,17 @@
color: #a0a0a0;
}
.cart-header-actions {
gap: 14px;
}
.cart-edit-btn {
color: var(--bs-primary);
font-size: 11px;
font-weight: 500;
text-decoration: none;
}
.cart-items-container {
min-height: 0;
gap: 0;

View File

@@ -306,4 +306,105 @@ describe('CartComponent', () => {
vi.useRealTimers();
});
it('enables quantity editing only while Modificar mode is active', async () => {
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
updateItemQuantity: vi.fn(),
removeItem: vi.fn(),
},
},
{ provide: ModalService, useValue: {} },
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto de prueba',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.componentRef.setInput('allowEditing', true);
const editingChange = vi.fn();
fixture.componentInstance.editing.subscribe(editingChange);
fixture.detectChanges();
const editButton = fixture.debugElement.query(By.css('.cart-edit-btn'));
expect(editButton.nativeElement.textContent.trim()).toBe('Modificar');
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(true);
editButton.nativeElement.click();
fixture.detectChanges();
expect(editButton.nativeElement.textContent.trim()).toBe('Listo');
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(false);
expect(editingChange).toHaveBeenCalledWith(true);
editButton.nativeElement.click();
fixture.detectChanges();
expect(editButton.nativeElement.textContent.trim()).toBe('Modificar');
expect(editingChange).toHaveBeenLastCalledWith(false);
});
it('allows editing directly when the optional Modificar toggle is disabled', async () => {
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
updateItemQuantity: vi.fn(),
removeItem: vi.fn(),
},
},
{ provide: ModalService, useValue: {} },
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto de prueba',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.cart-edit-btn'))).toBeNull();
expect(
fixture.debugElement.query(By.css('app-cart-item')).componentInstance.quantityDisabled(),
).toBe(false);
});
});

View File

@@ -4,6 +4,7 @@ import {
computed,
inject,
input,
model,
output,
signal,
} from '@angular/core';
@@ -48,11 +49,21 @@ export class CartComponent {
readonly discount = input<number>(0);
readonly total = input<number>(0);
readonly backgroundColor = input<string>('#ffffff');
readonly readonly = input<boolean>(false);
readonly allowEditing = input<boolean>(false);
readonly allowRemove = input<boolean>(true);
readonly persistQuantityChanges = input<boolean>(true);
readonly editingDisabled = input<boolean>(false);
readonly editing = model<boolean>(false);
readonly closed = output<void>();
readonly itemQuantityChange = output<{
item: CartItemMock;
index: number;
quantity: number;
}>();
protected readonly quantityOverrides = signal<Record<number, number>>({});
constructor() {
this.quantityUpdates$
.pipe(
@@ -103,6 +114,20 @@ export class CartComponent {
protected onItemQuantityChange(index: number, newQuantity: number): void {
const mockItem = this.items()[index];
if (!mockItem) {
return;
}
this.itemQuantityChange.emit({
item: mockItem,
index,
quantity: newQuantity,
});
if (!this.persistQuantityChanges()) {
return;
}
const cartItemId = mockItem?.cartItemId;
if (cartItemId) {
this.quantityOverrides.update((overrides) => ({
@@ -153,6 +178,15 @@ export class CartComponent {
protected readonly formattedDiscount = computed(() => this.formatCurrency(this.discount()));
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
protected toggleEditing(): void {
if (this.editingDisabled()) {
return;
}
const editing = !this.editing();
this.editing.set(editing);
}
private formatCurrency(value: number): string {
const rounded = Math.round(value);
const parts = rounded.toString().split('.');

View File

@@ -24,6 +24,7 @@
[placeholder]="placeholder()"
[value]="type() !== 'file' ? value() : null"
(input)="type() !== 'file' ? onValueChange($event) : null"
(paste)="onPaste($event)"
(change)="type() === 'file' ? onFileChange($event) : null"
[attr.maxlength]="type() !== 'file' ? maxlength() : null"
[attr.accept]="type() === 'file' ? accept() : null"

View File

@@ -85,6 +85,7 @@ export class InputComponent {
readonly disabledChange = output<boolean>();
readonly fileChange = output<File | null>();
readonly pasteEvent = output<ClipboardEvent>();
readonly visibleChange = output<boolean>();
protected readonly inputType = computed(() => {
@@ -166,6 +167,10 @@ export class InputComponent {
});
}
focus(): void {
this.inputElement()?.nativeElement.focus();
}
protected onValueChange(event: Event): void {
this.value.set((event.target as HTMLInputElement).value);
}
@@ -176,6 +181,10 @@ export class InputComponent {
this.fileChange.emit(file);
}
protected onPaste(event: ClipboardEvent): void {
this.pasteEvent.emit(event);
}
protected toggleEditableState(): void {
if (this.type() !== 'editable') {
return;

View File

@@ -1,13 +1,15 @@
<div
class="quantity-selector d-inline-flex align-items-center overflow-hidden rounded"
[class.quantity-selector--small]="size() === 'small'"
[class.quantity-selector--disabled]="disabled()"
aria-label="Selector de cantidad"
[attr.aria-disabled]="disabled()"
>
<button
type="button"
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
aria-label="Disminuir cantidad"
[disabled]="quantity() <= min()"
[disabled]="disabled() || quantity() <= min()"
(click)="onDecrease()"
>
-
@@ -22,7 +24,7 @@
type="button"
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
aria-label="Aumentar cantidad"
[disabled]="atMaximum()"
[disabled]="disabled() || atMaximum()"
(click)="onIncrease()"
>
+

View File

@@ -60,3 +60,7 @@
}
}
}
.quantity-selector--disabled {
opacity: 0.55;
}

View File

@@ -52,4 +52,21 @@ describe('QuantitySelectorComponent', () => {
expect(decreaseButton.disabled).toBe(true);
expect(fixture.componentInstance.quantity()).toBe(1);
});
it('disables both controls and ignores quantity changes when disabled', () => {
const fixture = TestBed.createComponent(QuantitySelectorComponent);
fixture.componentRef.setInput('quantity', 2);
fixture.componentRef.setInput('disabled', true);
fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>;
expect(Array.from(buttons).every((button) => button.disabled)).toBe(true);
expect(fixture.nativeElement.querySelector('[aria-disabled="true"]')).not.toBeNull();
(fixture.componentInstance as any).onIncrease();
(fixture.componentInstance as any).onDecrease();
expect(fixture.componentInstance.quantity()).toBe(2);
});
});

View File

@@ -13,6 +13,7 @@ export class QuantitySelectorComponent {
readonly min = input<number>(1);
readonly max = input<number | null>(100);
readonly size = input<'small' | 'medium'>('medium');
readonly disabled = input<boolean>(false);
protected readonly atMaximum = computed(() => {
const max = this.max();
@@ -23,14 +24,14 @@ export class QuantitySelectorComponent {
readonly decrease = output<void>();
protected onDecrease(): void {
if (this.quantity() > this.min()) {
if (!this.disabled() && this.quantity() > this.min()) {
this.quantity.set(this.quantity() - 1);
this.decrease.emit();
}
}
protected onIncrease(): void {
if (!this.atMaximum()) {
if (!this.disabled() && !this.atMaximum()) {
this.quantity.set(this.quantity() + 1);
this.increase.emit();
}