Compare commits
2 Commits
565bc769ed
...
902f65d8d0
| Author | SHA1 | Date | |
|---|---|---|---|
| 902f65d8d0 | |||
| 9dcedc9382 |
@@ -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 () => {
|
it('redirects authenticated users away from /login', async () => {
|
||||||
const { router } = await renderAppAt('/login', createTenantServiceStub(), createAuthServiceStub(true));
|
const { router } = await renderAppAt('/login', createTenantServiceStub(), createAuthServiceStub(true));
|
||||||
|
|
||||||
@@ -186,7 +235,7 @@ describe('app routes', () => {
|
|||||||
it('redirects unauthenticated users from /checkout to /login', async () => {
|
it('redirects unauthenticated users from /checkout to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
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 () => {
|
it('allows authenticated users to access /checkout', async () => {
|
||||||
|
|||||||
@@ -14,7 +14,10 @@
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
@if (isCartOpen()) {
|
@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">
|
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
||||||
<app-cart
|
<app-cart
|
||||||
[showClose]="true"
|
[showClose]="true"
|
||||||
@@ -25,12 +28,20 @@
|
|||||||
[backgroundColor]="'#ffffff'"
|
[backgroundColor]="'#ffffff'"
|
||||||
(closed)="isCartOpen.set(false)"
|
(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
|
>Seguir comprando</app-button
|
||||||
>
|
>
|
||||||
<app-button variant="primary" class="flex-grow-1" (click)="onCheckoutClick()"
|
<app-button
|
||||||
>Comprar</app-button
|
variant="primary"
|
||||||
|
class="flex-grow-1"
|
||||||
|
[disabled]="isCreatingPurchase()"
|
||||||
|
(click)="onCheckoutClick()"
|
||||||
>
|
>
|
||||||
|
Comprar
|
||||||
|
</app-button>
|
||||||
</app-cart>
|
</app-cart>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { AuthService } from '../../services/auth/auth.service';
|
|||||||
import { AuthUser } from '../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../services/auth/auth.interfaces';
|
||||||
import { StoreLayoutComponent } from './store-layout.component';
|
import { StoreLayoutComponent } from './store-layout.component';
|
||||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||||
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -127,12 +128,17 @@ const tenant: Tenant = {
|
|||||||
describe('StoreLayoutComponent', () => {
|
describe('StoreLayoutComponent', () => {
|
||||||
let tenantState = signal<Tenant | null>(tenant);
|
let tenantState = signal<Tenant | null>(tenant);
|
||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
const authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
|
checkoutServiceStub = {
|
||||||
|
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||||
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
@@ -156,6 +162,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
.fn()
|
.fn()
|
||||||
.mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
|
.mockReturnValue(of({ data: { id: 1, items: [], subtotal: '0' } })),
|
||||||
removeItem: vi.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)),
|
logout: vi.fn().mockReturnValue(of(void 0)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: CheckoutService,
|
||||||
|
useValue: checkoutServiceStub,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
@@ -394,8 +405,9 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(router.navigate).not.toHaveBeenCalled();
|
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 authService = TestBed.inject(AuthService);
|
||||||
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'navigate');
|
vi.spyOn(router, 'navigate');
|
||||||
|
|
||||||
@@ -424,11 +436,13 @@ describe('StoreLayoutComponent', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(authService.logout).toHaveBeenCalled();
|
expect(authService.logout).toHaveBeenCalled();
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
expect(cartService.clearCart).toHaveBeenCalled();
|
||||||
|
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('provides account actions from the footer', () => {
|
it('provides account actions from the footer', () => {
|
||||||
const authService = TestBed.inject(AuthService);
|
const authService = TestBed.inject(AuthService);
|
||||||
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'navigate');
|
vi.spyOn(router, 'navigate');
|
||||||
|
|
||||||
@@ -455,7 +469,28 @@ describe('StoreLayoutComponent', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(authService.logout).toHaveBeenCalled();
|
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', () => {
|
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');
|
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);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'navigate');
|
vi.spyOn(router, 'navigate');
|
||||||
cartState.set({
|
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);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
(fixture.componentInstance as any).isCartOpen.set(true);
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const compiled = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
const buyButton = Array.from(compiled.querySelectorAll('app-button button')).find(
|
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
|
||||||
(button) => button.textContent?.trim() === 'Comprar',
|
const buyButton = Array.from(
|
||||||
) as HTMLButtonElement | undefined;
|
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();
|
expect(buyButton).toBeDefined();
|
||||||
buyButton!.click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/checkout']);
|
|
||||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
|
|||||||
import { CartItem } from '../../services/cart/cart.interface';
|
import { CartItem } from '../../services/cart/cart.interface';
|
||||||
import { AuthService } from '../../services/auth/auth.service';
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { findMenu } from '../../services/menu.utils';
|
import { findMenu } from '../../services/menu.utils';
|
||||||
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
|
import { ToastService } from '../../services/toast.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -26,9 +28,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const cart = this.cartService.cart();
|
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({
|
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),
|
error: (err) => console.error('Error logging out', err),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onCheckoutClick(): void {
|
protected async onCheckoutClick(): Promise<void> {
|
||||||
this.isCartOpen.set(false);
|
if (this.isCreatingPurchase()) {
|
||||||
void this.router.navigate(['/checkout']);
|
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[]>(() => {
|
protected readonly footerSections = computed<StoreFooterSection[]>(() => {
|
||||||
|
|||||||
@@ -23,10 +23,14 @@ describe('auth guards', () => {
|
|||||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
|
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(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', () => {
|
it('allows authenticated users through authGuard', () => {
|
||||||
@@ -34,7 +38,9 @@ describe('auth guards', () => {
|
|||||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
|
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);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,11 +3,15 @@ import { CanActivateFn, Router } from '@angular/router';
|
|||||||
|
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
export const authGuard: CanActivateFn = () => {
|
export const authGuard: CanActivateFn = (_route, state) => {
|
||||||
const authService = inject(AuthService);
|
const authService = inject(AuthService);
|
||||||
const router = inject(Router);
|
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 = () => {
|
export const guestOnlyGuard: CanActivateFn = () => {
|
||||||
|
|||||||
@@ -37,3 +37,25 @@ export interface RegisterResponse {
|
|||||||
message: string;
|
message: string;
|
||||||
data: AuthUser;
|
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';
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,8 +19,12 @@ describe('AuthService', () => {
|
|||||||
function createCookieServiceStub() {
|
function createCookieServiceStub() {
|
||||||
return {
|
return {
|
||||||
get: (name: string) => cookieStore[name] || null,
|
get: (name: string) => cookieStore[name] || null,
|
||||||
set: (name: string, value: string) => { cookieStore[name] = value; },
|
set: (name: string, value: string) => {
|
||||||
delete: (name: string) => { delete cookieStore[name]; }
|
cookieStore[name] = value;
|
||||||
|
},
|
||||||
|
delete: (name: string) => {
|
||||||
|
delete cookieStore[name];
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,6 +35,10 @@ describe('AuthService', () => {
|
|||||||
provideHttpClientTesting(),
|
provideHttpClientTesting(),
|
||||||
AuthService,
|
AuthService,
|
||||||
{ provide: CookieService, useValue: createCookieServiceStub() },
|
{ provide: CookieService, useValue: createCookieServiceStub() },
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
|
||||||
|
},
|
||||||
TransferState
|
TransferState
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
@@ -44,6 +52,12 @@ describe('AuthService', () => {
|
|||||||
|
|
||||||
const request = httpController.expectOne(`${environment.url}login`);
|
const request = httpController.expectOne(`${environment.url}login`);
|
||||||
expect(request.request.method).toBe('POST');
|
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({
|
request.flush({
|
||||||
message: 'Sesion iniciada correctamente.',
|
message: 'Sesion iniciada correctamente.',
|
||||||
token: 'plain-text-token',
|
token: 'plain-text-token',
|
||||||
@@ -96,6 +110,47 @@ describe('AuthService', () => {
|
|||||||
httpController.verify();
|
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 () => {
|
it('clears an expired session when /me returns 401', async () => {
|
||||||
cookieStore['shopit.auth.token'] = 'expired-token';
|
cookieStore['shopit.auth.token'] = 'expired-token';
|
||||||
|
|
||||||
@@ -174,6 +229,121 @@ describe('AuthService', () => {
|
|||||||
httpController.verify();
|
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', () => {
|
it('propagates logout errors without clearing the local session', () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
@@ -181,6 +351,10 @@ describe('AuthService', () => {
|
|||||||
provideHttpClientTesting(),
|
provideHttpClientTesting(),
|
||||||
AuthService,
|
AuthService,
|
||||||
{ provide: CookieService, useValue: createCookieServiceStub() },
|
{ provide: CookieService, useValue: createCookieServiceStub() },
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: { getTenant: () => ({ codigo: 'tenant-test' }) }
|
||||||
|
},
|
||||||
TransferState
|
TransferState
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { DOCUMENT } from '@angular/common';
|
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 { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||||
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
||||||
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
||||||
@@ -11,7 +11,11 @@ import {
|
|||||||
LoginResponse,
|
LoginResponse,
|
||||||
RegisterPayload,
|
RegisterPayload,
|
||||||
RegisterResponse,
|
RegisterResponse,
|
||||||
UpdateProfilePayload
|
ResetPasswordPayload,
|
||||||
|
ResetPasswordAttemptResponse,
|
||||||
|
ResetPasswordResponse,
|
||||||
|
UpdateProfilePayload,
|
||||||
|
ValidateResetPasswordAttemptResponse
|
||||||
} from './auth.interfaces';
|
} from './auth.interfaces';
|
||||||
import { CookieService } from '../cookie/cookie.service';
|
import { CookieService } from '../cookie/cookie.service';
|
||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
@@ -38,10 +42,21 @@ export class AuthService {
|
|||||||
readonly isAuthenticated = computed(() => this.tokenState() !== null);
|
readonly isAuthenticated = computed(() => this.tokenState() !== null);
|
||||||
|
|
||||||
login(payload: LoginPayload): Observable<AuthUser> {
|
login(payload: LoginPayload): Observable<AuthUser> {
|
||||||
return this.http.post<LoginResponse>(`${environment.url}login`, payload).pipe(
|
const tenant = this.tenantService.getTenant();
|
||||||
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
|
if (!tenant) {
|
||||||
map((response) => response.user)
|
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> {
|
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 {
|
loginWithGoogle(): void {
|
||||||
const tenant = this.tenantService.getTenant();
|
const tenant = this.tenantService.getTenant();
|
||||||
if (!tenant) {
|
if (!tenant) {
|
||||||
@@ -68,16 +113,25 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
completeGoogleLogin(oauthCode: string): Observable<AuthUser> {
|
completeGoogleLogin(oauthCode: string): Observable<AuthUser> {
|
||||||
return this.http.post<LoginResponse>(`${environment.url}auth/google/exchange`, { oauth_code: oauthCode }).pipe(
|
const tenant = this.tenantService.getTenant();
|
||||||
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
|
if (!tenant) {
|
||||||
map((response) => response.user)
|
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> {
|
updateProfile(payload: UpdateProfilePayload): Observable<AuthUser> {
|
||||||
return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe(
|
return this.http.put<AuthUser>(`${environment.url}me`, payload).pipe(tap((user) => this.userState.set(user)));
|
||||||
tap((user) => this.userState.set(user))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logout(): Observable<void> {
|
logout(): Observable<void> {
|
||||||
@@ -86,9 +140,7 @@ export class AuthService {
|
|||||||
return of(void 0);
|
return of(void 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.http.post<void>(`${environment.url}logout`, {}).pipe(
|
return this.http.post<void>(`${environment.url}logout`, {}).pipe(tap(() => this.clearSession()));
|
||||||
tap(() => this.clearSession())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async bootstrap(): Promise<void> {
|
async bootstrap(): Promise<void> {
|
||||||
@@ -127,9 +179,7 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadCurrentUser(): Observable<AuthUser> {
|
loadCurrentUser(): Observable<AuthUser> {
|
||||||
return this.http.get<AuthUser>(`${environment.url}me`).pipe(
|
return this.http.get<AuthUser>(`${environment.url}me`).pipe(tap((user) => this.userState.set(user)));
|
||||||
tap((user) => this.userState.set(user))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hydrateSession(): void {
|
hydrateSession(): void {
|
||||||
|
|||||||
@@ -4,14 +4,25 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
export interface CreatePurchasePayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
cart_id: number;
|
|
||||||
dni: string;
|
dni: string;
|
||||||
telefono: string;
|
telefono: string;
|
||||||
nombre_apellido: string;
|
nombre_apellido: string;
|
||||||
email: string;
|
email: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type StartCheckoutPayload =
|
||||||
|
| {
|
||||||
|
cart_id: number;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
direct_item: {
|
||||||
|
catalog_item_id: number;
|
||||||
|
variant_id: number | null;
|
||||||
|
cantidad: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export interface PurchaseStatusResponse {
|
export interface PurchaseStatusResponse {
|
||||||
status: string | null;
|
status: string | null;
|
||||||
}
|
}
|
||||||
@@ -62,17 +73,23 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CheckoutService {
|
export class CheckoutService {
|
||||||
private readonly http = inject(HttpClient);
|
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(
|
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) {
|
if (!purchase?.id) {
|
||||||
throw new Error('Error al crear la compra.');
|
throw new Error('Error al crear la compra.');
|
||||||
@@ -81,13 +98,21 @@ export class CheckoutService {
|
|||||||
return purchase;
|
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 };
|
const payload: any = { method };
|
||||||
if (payerDni) {
|
if (payerDni) {
|
||||||
payload.transfer_payer_dni = payerDni;
|
payload.transfer_payer_dni = payerDni;
|
||||||
}
|
}
|
||||||
const response = await firstValueFrom(
|
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) {
|
if (!response) {
|
||||||
throw new Error('Error al generar la intención de pago.');
|
throw new Error('Error al generar la intención de pago.');
|
||||||
@@ -95,9 +120,72 @@ export class CheckoutService {
|
|||||||
return response;
|
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> {
|
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
const response = await firstValueFrom(
|
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);
|
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
||||||
@@ -107,27 +195,49 @@ export class CheckoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
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`;
|
let url = `${environment.url}tenants/${tenantCode}/compras`;
|
||||||
if (status) {
|
if (status) {
|
||||||
url += `?status=${status}`;
|
url += `?status=${status}`;
|
||||||
}
|
}
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
|
||||||
this.http.get<{ data: PurchaseSummaryResponse[] }>(url)
|
|
||||||
);
|
|
||||||
if (!response) {
|
if (!response) {
|
||||||
throw new Error('Error al obtener las compras.');
|
throw new Error('Error al obtener las compras.');
|
||||||
}
|
}
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPurchase(tenantCode: string, purchaseId: string | number): Promise<PurchaseDetailResponse> {
|
async getPurchase(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: string | number,
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
const response = await firstValueFrom(
|
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);
|
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
|
<div class="checkout-page">
|
||||||
<div class="checkout-page">
|
<div
|
||||||
<div class="checkout-page__stepper-col ">
|
class="checkout-page__stepper-col"
|
||||||
<app-stepper #stepper>
|
[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-step label="Datos" [isValid]="isStep1Valid()">
|
||||||
<app-checkout-data-step
|
<app-checkout-data-step
|
||||||
[form]="form"
|
[form]="form"
|
||||||
@@ -30,16 +34,32 @@
|
|||||||
(retryQrPolling)="retryQrPolling()"
|
(retryQrPolling)="retryQrPolling()"
|
||||||
/>
|
/>
|
||||||
</app-step>
|
</app-step>
|
||||||
</app-stepper>
|
</app-stepper>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="checkout-page__cart-col">
|
|
||||||
<app-cart
|
|
||||||
[items]="mappedCartItems()"
|
|
||||||
[subtotal]="cartSubtotal()"
|
|
||||||
[discount]="cartDiscount()"
|
|
||||||
[total]="cartTotal()"
|
|
||||||
backgroundColor="transparent"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</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>
|
||||||
|
|||||||
@@ -12,6 +12,27 @@
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
min-height: 420px;
|
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 {
|
&__cart-col {
|
||||||
|
|||||||
@@ -1,18 +1,24 @@
|
|||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/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 { of } from 'rxjs';
|
||||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
describe('CheckoutPageComponent payment validation', () => {
|
describe('CheckoutPageComponent payment validation', () => {
|
||||||
let checkoutServiceStub: {
|
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>;
|
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
||||||
getPurchase: ReturnType<typeof vi.fn>;
|
getPurchase: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
@@ -23,6 +29,8 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
clearCart: ReturnType<typeof vi.fn>;
|
clearCart: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
|
let authUserState: ReturnType<typeof signal>;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
@@ -36,6 +44,16 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
checkoutServiceStub = {
|
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({
|
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||||
qr_data: { qr_code: 'qr-value' },
|
qr_data: { qr_code: 'qr-value' },
|
||||||
}),
|
}),
|
||||||
@@ -63,14 +81,27 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
routerStub = { navigate: vi.fn() };
|
routerStub = { navigate: vi.fn() };
|
||||||
|
routeQueryParamMap = convertToParamMap({});
|
||||||
|
authUserState = signal(null);
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CheckoutPageComponent],
|
imports: [CheckoutPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
||||||
|
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
|
||||||
{ provide: CartService, useValue: cartServiceStub },
|
{ provide: CartService, useValue: cartServiceStub },
|
||||||
{ provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } },
|
{ 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 },
|
{ provide: Router, useValue: routerStub },
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -87,6 +118,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
const fixture = TestBed.createComponent(CheckoutPageComponent);
|
const fixture = TestBed.createComponent(CheckoutPageComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
fixture.componentInstance['createdPurchaseId'].set(25);
|
fixture.componentInstance['createdPurchaseId'].set(25);
|
||||||
|
routerStub.navigate.mockClear();
|
||||||
return { fixture, component: fixture.componentInstance as any };
|
return { fixture, component: fixture.componentInstance as any };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +137,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(5_000);
|
await vi.advanceTimersByTimeAsync(5_000);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
|
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
@@ -181,7 +213,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
|
|
||||||
expect(cartServiceStub.clearCart).toHaveBeenCalledOnce();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -197,4 +229,175 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,24 +2,25 @@ import {
|
|||||||
ChangeDetectionStrategy,
|
ChangeDetectionStrategy,
|
||||||
Component,
|
Component,
|
||||||
computed,
|
computed,
|
||||||
effect,
|
|
||||||
inject,
|
inject,
|
||||||
OnDestroy,
|
OnDestroy,
|
||||||
OnInit,
|
OnInit,
|
||||||
signal,
|
signal,
|
||||||
untracked,
|
|
||||||
ViewChild,
|
ViewChild,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { FormBuilder, Validators } from '@angular/forms';
|
import { FormBuilder, Validators } from '@angular/forms';
|
||||||
import { Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { startWith } from 'rxjs';
|
import { firstValueFrom, startWith } from 'rxjs';
|
||||||
|
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
|
||||||
import { TenantService } from '../../../../core/services/tenant.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 { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { BankAccount } from '../../../../core/services/tenant.interface';
|
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 { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||||
@@ -51,11 +52,12 @@ import {
|
|||||||
})
|
})
|
||||||
export class CheckoutPageComponent implements OnInit, OnDestroy {
|
export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||||
private readonly formBuilder = inject(FormBuilder);
|
private readonly formBuilder = inject(FormBuilder);
|
||||||
private readonly cartService = inject(CartService);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly cartService = inject(CartService);
|
||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
private readonly qrPollingMaxAttempts = 60;
|
private readonly qrPollingMaxAttempts = 60;
|
||||||
|
|
||||||
@@ -74,19 +76,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
telefono: ['', [Validators.required]],
|
telefono: ['', [Validators.required]],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const cart = this.cartService.cart();
|
const purchase = this.createdPurchase();
|
||||||
return cart ? parseFloat(cart.subtotal) : 0;
|
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
protected readonly cartDiscount = computed(() => 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[]>(() => {
|
protected readonly mappedCartItems = computed<CartItemMock[]>(() => {
|
||||||
const cart = this.cartService.cart();
|
const purchase = this.createdPurchase();
|
||||||
if (!cart || !cart.items) return [];
|
return purchase ? purchase.items.map((item) => this.mapPurchaseItemToMock(item)) : [];
|
||||||
return cart.items.map((item) => this.mapCartItemToMock(item));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
protected readonly isStep1Valid = signal(this.form.valid);
|
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 transferAccount = signal<TransferAccount | null>(null);
|
||||||
protected readonly transferDni = signal<string>('');
|
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 createdPurchaseId = signal<number | null>(null);
|
||||||
protected readonly isGeneratingIntent = signal(false);
|
protected readonly isGeneratingIntent = signal(false);
|
||||||
protected readonly isPaymentLoading = computed(
|
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
|
||||||
() => this.isGeneratingIntent() || this.cartService.isUpdating(),
|
|
||||||
);
|
|
||||||
protected readonly qrData = signal<string | null>(null);
|
protected readonly qrData = signal<string | null>(null);
|
||||||
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
||||||
protected readonly isCheckingQrPayment = signal(false);
|
protected readonly isCheckingQrPayment = signal(false);
|
||||||
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
||||||
|
|
||||||
constructor() {
|
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
|
this.form.statusChanges
|
||||||
.pipe(startWith(this.form.status))
|
.pipe(startWith(this.form.status))
|
||||||
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
||||||
@@ -144,68 +137,126 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
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 {
|
ngOnDestroy(): void {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapCartItemToMock(item: CartItem): CartItemMock {
|
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): 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() };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cartItemId: item.id,
|
cartItemId: item.id,
|
||||||
imageUrl: item.product?.imagen ?? null,
|
imageUrl: item.item_details.imagen,
|
||||||
product,
|
product: item.item_details.nombre,
|
||||||
originalPrice: null,
|
originalPrice: null,
|
||||||
discountedPrice: parseFloat(item.precio_unitario),
|
discountedPrice: parseFloat(item.unit_price),
|
||||||
discountPercentage: null,
|
discountPercentage: null,
|
||||||
attributes,
|
attributes: item.item_details.attributes.map((attribute) => ({
|
||||||
quantity: item.cantidad,
|
label: attribute.name,
|
||||||
|
value: attribute.value === null ? '' : String(attribute.value),
|
||||||
|
})),
|
||||||
|
quantity: item.quantity,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async onStep1Continue(): Promise<void> {
|
protected async onEditingItemsChange(editing: boolean): Promise<void> {
|
||||||
if (this.form.invalid) return;
|
if (this.isUpdatingItem() || this.isPreparingItemEdit()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const tenant = this.tenantService.tenant();
|
if (!editing) {
|
||||||
if (!tenant) return;
|
this.isEditingItems.set(false);
|
||||||
|
|
||||||
this.isCreatingPurchase.set(true);
|
if (this.stepper?.currentStepIndex() === 1) {
|
||||||
|
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
||||||
try {
|
|
||||||
const cart = this.cartService.cart();
|
|
||||||
if (!cart?.id) {
|
|
||||||
throw new Error('No hay un carrito activo para finalizar la compra.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 formValue = this.form.getRawValue();
|
||||||
const payload: CreatePurchasePayload = {
|
const purchase = await this.checkoutService.updateCustomerData(tenant.codigo, purchaseId, {
|
||||||
cart_id: cart.id,
|
|
||||||
dni: formValue.dni,
|
dni: formValue.dni,
|
||||||
telefono: formValue.telefono,
|
telefono: formValue.telefono,
|
||||||
email: formValue.email,
|
email: formValue.email,
|
||||||
nombre_apellido: formValue.nombre,
|
nombre_apellido: formValue.nombre,
|
||||||
};
|
});
|
||||||
|
this.createdPurchase.set(purchase);
|
||||||
const response = await this.checkoutService.createPurchase(tenant.codigo, payload);
|
|
||||||
this.createdPurchaseId.set(response.id);
|
|
||||||
|
|
||||||
this.stepper.next();
|
this.stepper.next();
|
||||||
|
|
||||||
@@ -215,17 +266,50 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
console.error('Failed to create purchase:', error);
|
console.error('Failed to create purchase:', error);
|
||||||
// Here we could show an alert or toast
|
// Here we could show an alert or toast
|
||||||
} finally {
|
} 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();
|
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> {
|
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||||
if (this.navigationStarted) {
|
if (this.navigationStarted || this.isEditingItems()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,6 +350,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.qrData.set(response.qr_data.qr_code);
|
this.qrData.set(response.qr_data.qr_code);
|
||||||
|
this.markPurchasePendingPayment();
|
||||||
this.startQrPolling();
|
this.startQrPolling();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -276,6 +361,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async generateTransferIntent(dni: string): Promise<void> {
|
protected async generateTransferIntent(dni: string): Promise<void> {
|
||||||
|
if (this.isEditingItems()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
@@ -291,10 +380,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
tenant.codigo,
|
tenant.codigo,
|
||||||
purchaseId,
|
purchaseId,
|
||||||
'transfer',
|
'transfer',
|
||||||
dni
|
dni,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.transfer_data) {
|
if (response.transfer_data) {
|
||||||
|
this.markPurchasePendingPayment();
|
||||||
this.transferAccount.set({
|
this.transferAccount.set({
|
||||||
titular: response.transfer_data.titular,
|
titular: response.transfer_data.titular,
|
||||||
entidad: response.transfer_data.entidad,
|
entidad: response.transfer_data.entidad,
|
||||||
@@ -334,6 +424,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
!purchaseId ||
|
!purchaseId ||
|
||||||
!tenant ||
|
!tenant ||
|
||||||
this.navigationStarted ||
|
this.navigationStarted ||
|
||||||
|
this.isEditingItems() ||
|
||||||
this.transferValidationStatus() === 'checking'
|
this.transferValidationStatus() === 'checking'
|
||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
@@ -448,11 +539,22 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleConfirmedPayment(purchaseId: number): void {
|
private markPurchasePendingPayment(): void {
|
||||||
this.navigateToPurchaseStatus(purchaseId, true);
|
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) {
|
if (this.navigationStarted) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -460,10 +562,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
|
||||||
if (clearCart) {
|
|
||||||
this.cartService.clearCart();
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
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(['/']);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { CanDeactivateFn } from '@angular/router';
|
||||||
|
|
||||||
|
interface PendingCheckoutComponent {
|
||||||
|
canDeactivate(): Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const checkoutPendingPurchaseGuard: CanDeactivateFn<PendingCheckoutComponent> = (component) =>
|
||||||
|
component.canDeactivate();
|
||||||
@@ -40,7 +40,11 @@
|
|||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
}
|
}
|
||||||
<div class="text-end">
|
<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
|
Olvide mi contraseña
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -56,7 +60,7 @@
|
|||||||
>
|
>
|
||||||
{{ isSubmitting() ? 'Ingresando...' : 'Ingresar' }}
|
{{ isSubmitting() ? 'Ingresando...' : 'Ingresar' }}
|
||||||
</app-button>
|
</app-button>
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
variant="borderless"
|
variant="borderless"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { InputComponent } from '../../../../shared/components/input/input.compon
|
|||||||
|
|
||||||
const PASSWORD_MIN_LENGTH = 8;
|
const PASSWORD_MIN_LENGTH = 8;
|
||||||
const EMAIL_MAX_LENGTH = 255;
|
const EMAIL_MAX_LENGTH = 255;
|
||||||
|
const POST_LOGIN_RETURN_URL_KEY = 'shopit.auth.return-url';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-login-page',
|
selector: 'app-login-page',
|
||||||
@@ -53,6 +54,10 @@ export class LoginPageComponent {
|
|||||||
void this.router.navigate(['/register']);
|
void this.router.navigate(['/register']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
goToRecoverPassword(): void {
|
||||||
|
void this.router.navigate(['/recuperar-contrasena']);
|
||||||
|
}
|
||||||
|
|
||||||
onSubmit(): void {
|
onSubmit(): void {
|
||||||
this.submittedState.set(true);
|
this.submittedState.set(true);
|
||||||
this.serverErrorState.set(null);
|
this.serverErrorState.set(null);
|
||||||
@@ -80,6 +85,10 @@ export class LoginPageComponent {
|
|||||||
this.serverErrorState.set(null);
|
this.serverErrorState.set(null);
|
||||||
|
|
||||||
try {
|
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();
|
this.authService.loginWithGoogle();
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
this.serverErrorState.set(this.resolveErrorMessage(error));
|
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||||
@@ -127,8 +136,16 @@ export class LoginPageComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected redirectToHome(): void {
|
protected redirectToHome(): void {
|
||||||
const homeUrl = this.router.serializeUrl(this.router.createUrlTree(['/']));
|
const requestedUrl =
|
||||||
this.document.location.assign(homeUrl);
|
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 {
|
private completeGoogleLogin(oauthCode: string): void {
|
||||||
|
|||||||
@@ -73,9 +73,12 @@
|
|||||||
<app-button
|
<app-button
|
||||||
class="product-detail__cta"
|
class="product-detail__cta"
|
||||||
type="button"
|
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>
|
<div class="spinner-border spinner-border-sm" role="status"></div>
|
||||||
} @else {
|
} @else {
|
||||||
Comprar
|
Comprar
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
|
import { signal } from '@angular/core';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { By } from '@angular/platform-browser';
|
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 { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { ProductDetailPageComponent } from './product-detail-page.component';
|
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 {
|
import {
|
||||||
PRODUCT_DETAIL_ERROR_MESSAGE,
|
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
ProductDetailResolvedData,
|
ProductDetailResolvedData,
|
||||||
@@ -41,6 +45,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
let routerStub: any;
|
let routerStub: any;
|
||||||
let cartServiceStub: any;
|
let cartServiceStub: any;
|
||||||
let toastServiceStub: any;
|
let toastServiceStub: any;
|
||||||
|
let checkoutServiceStub: any;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
@@ -72,6 +77,9 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
danger: vi.fn(),
|
danger: vi.fn(),
|
||||||
info: vi.fn(),
|
info: vi.fn(),
|
||||||
};
|
};
|
||||||
|
checkoutServiceStub = {
|
||||||
|
startCheckout: vi.fn().mockResolvedValue({ id: 44 }),
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
async function configureTestingModule() {
|
async function configureTestingModule() {
|
||||||
@@ -100,6 +108,26 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
provide: ToastService,
|
provide: ToastService,
|
||||||
useValue: toastServiceStub,
|
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();
|
}).compileComponents();
|
||||||
}
|
}
|
||||||
@@ -364,7 +392,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
|
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();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -380,8 +408,18 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
buttons[0].click();
|
buttons[0].click();
|
||||||
buttons[1].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 () => {
|
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ import { ButtonComponent } from '../../../../shared/components/button/button.com
|
|||||||
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
|
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
|
||||||
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
|
||||||
import { ProductDetailResolvedData } from './product-detail-page.resolver';
|
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({
|
@Component({
|
||||||
selector: 'app-product-detail-page',
|
selector: 'app-product-detail-page',
|
||||||
@@ -50,6 +53,9 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly catalogService = inject(CatalogService);
|
private readonly catalogService = inject(CatalogService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly cartService = inject(CartService);
|
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 attributeSelector = viewChild(ProductAttributeSelectorComponent);
|
||||||
private readonly carouselHost = viewChild<ElementRef<HTMLElement>>('carouselHost');
|
private readonly carouselHost = viewChild<ElementRef<HTMLElement>>('carouselHost');
|
||||||
private readonly descriptionBody = viewChild<ElementRef<HTMLElement>>('descriptionBody');
|
private readonly descriptionBody = viewChild<ElementRef<HTMLElement>>('descriptionBody');
|
||||||
@@ -77,6 +83,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly loading = signal(false);
|
protected readonly loading = signal(false);
|
||||||
protected readonly variantLoading = signal(false);
|
protected readonly variantLoading = signal(false);
|
||||||
protected readonly addingToCart = signal(false);
|
protected readonly addingToCart = signal(false);
|
||||||
|
protected readonly creatingDirectPurchase = signal(false);
|
||||||
protected readonly error = signal<string | null>(null);
|
protected readonly error = signal<string | null>(null);
|
||||||
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
|
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
|
||||||
protected readonly quantity = signal(1);
|
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 {
|
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
|
||||||
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,20 @@
|
|||||||
Actualizar estado
|
Actualizar estado
|
||||||
</app-button>
|
</app-button>
|
||||||
</div>
|
</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Ó</h2>
|
||||||
|
<p class="status-content__subtitle">El plazo de pago terminó 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és volver a la tienda e iniciar una nueva compra.</p>
|
||||||
|
</div>
|
||||||
} @else if (status() === 'rejected') {
|
} @else if (status() === 'rejected') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
<div class="status-content__icon status-content__icon--error">
|
<div class="status-content__icon status-content__icon--error">
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { CheckoutService, PurchaseStatusResponse } from '../../../../core/servic
|
|||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
|
||||||
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'error';
|
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-status-page',
|
selector: 'app-purchase-status-page',
|
||||||
@@ -93,6 +93,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
return 'rejected';
|
return 'rejected';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
return 'expired';
|
||||||
|
}
|
||||||
|
|
||||||
return 'pending';
|
return 'pending';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.reset-password-page__form {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,9 +6,13 @@ import { authGuard, guestOnlyGuard } from '../../core/services/auth/auth.guards'
|
|||||||
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
||||||
import { hasMenuGuard } from '../../core/guards/menu.guard';
|
import { hasMenuGuard } from '../../core/guards/menu.guard';
|
||||||
import { productDetailResolver } from './pages/product-detail-page/product-detail-page.resolver';
|
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 { RegisterPageComponent } from './pages/register-page/register-page.component';
|
||||||
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
||||||
import { storeHomeCatalogResolver } from './pages/store-home-page/store-home-page.resolver';
|
import { storeHomeCatalogResolver } from './pages/store-home-page/store-home-page.resolver';
|
||||||
|
import { checkoutPendingPurchaseGuard } from './pages/checkout-page/checkout-page.guard';
|
||||||
|
|
||||||
export const routes: Routes = [
|
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',
|
path: 'buscar',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
@@ -64,6 +87,7 @@ export const routes: Routes = [
|
|||||||
{
|
{
|
||||||
path: 'checkout',
|
path: 'checkout',
|
||||||
canActivate: [authGuard, hasMenuGuard('checkout')],
|
canActivate: [authGuard, hasMenuGuard('checkout')],
|
||||||
|
canDeactivate: [checkoutPendingPurchaseGuard],
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
import('./pages/checkout-page/checkout-page.component').then(
|
import('./pages/checkout-page/checkout-page.component').then(
|
||||||
(m) => m.CheckoutPageComponent,
|
(m) => m.CheckoutPageComponent,
|
||||||
|
|||||||
@@ -34,20 +34,25 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
|
@if (!readonly()) {
|
||||||
<app-quantity-selector
|
<div class="d-flex justify-content-end align-items-center mt-auto cart-item-actions">
|
||||||
size="small"
|
<app-quantity-selector
|
||||||
[quantity]="quantity()"
|
size="small"
|
||||||
(quantityChange)="onQuantityChange($event)"
|
[quantity]="quantity()"
|
||||||
(increase)="onIncrease()"
|
[disabled]="quantityDisabled()"
|
||||||
(decrease)="onDecrease()"
|
(quantityChange)="onQuantityChange($event)"
|
||||||
/>
|
(increase)="onIncrease()"
|
||||||
<app-icon-button
|
(decrease)="onDecrease()"
|
||||||
variant="trash"
|
/>
|
||||||
class="cart-item-remove-btn"
|
@if (!quantityDisabled() && showRemove()) {
|
||||||
(click)="onRemove()"
|
<app-icon-button
|
||||||
/>
|
variant="trash"
|
||||||
</div>
|
class="cart-item-remove-btn"
|
||||||
|
(click)="onRemove()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ export class CartItemComponent {
|
|||||||
readonly discountPercentage = input<number | null>(null);
|
readonly discountPercentage = input<number | null>(null);
|
||||||
readonly attributes = input<CartItemAttribute[]>([]);
|
readonly attributes = input<CartItemAttribute[]>([]);
|
||||||
readonly quantity = input<number>(1);
|
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 quantityChange = output<number>();
|
||||||
readonly remove = output<void>();
|
readonly remove = output<void>();
|
||||||
@@ -30,6 +33,7 @@ export class CartItemComponent {
|
|||||||
readonly decrease = output<void>();
|
readonly decrease = output<void>();
|
||||||
|
|
||||||
protected onQuantityChange(newQuantity: number): void {
|
protected onQuantityChange(newQuantity: number): void {
|
||||||
|
if (this.quantityDisabled()) return;
|
||||||
this.quantityChange.emit(newQuantity);
|
this.quantityChange.emit(newQuantity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,16 +5,30 @@
|
|||||||
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
<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>
|
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||||
|
|
||||||
@if (showClose()) {
|
<div class="d-flex align-items-center cart-header-actions">
|
||||||
<button
|
@if (!readonly() && allowEditing() && items().length > 0) {
|
||||||
class="btn btn-link p-0 border-0 d-inline-flex align-items-center justify-content-center cart-close-btn"
|
<button
|
||||||
type="button"
|
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||||
aria-label="Cerrar carrito"
|
type="button"
|
||||||
(click)="closed.emit()"
|
[attr.aria-pressed]="editing()"
|
||||||
>
|
[disabled]="editingDisabled()"
|
||||||
<i class="fa-solid fa-xmark"></i>
|
(click)="toggleEditing()"
|
||||||
</button>
|
>
|
||||||
}
|
{{ 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>
|
</header>
|
||||||
|
|
||||||
<div class="d-grid w-100 flex-grow-1 overflow-y-auto cart-items-container">
|
<div class="d-grid w-100 flex-grow-1 overflow-y-auto cart-items-container">
|
||||||
@@ -31,6 +45,9 @@
|
|||||||
[discountPercentage]="item.discountPercentage"
|
[discountPercentage]="item.discountPercentage"
|
||||||
[attributes]="item.attributes"
|
[attributes]="item.attributes"
|
||||||
[quantity]="getItemQuantity(item)"
|
[quantity]="getItemQuantity(item)"
|
||||||
|
[readonly]="readonly()"
|
||||||
|
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
|
||||||
|
[showRemove]="allowRemove()"
|
||||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||||
(remove)="onItemRemove(idx)"
|
(remove)="onItemRemove(idx)"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -21,6 +21,17 @@
|
|||||||
color: #a0a0a0;
|
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 {
|
.cart-items-container {
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
gap: 0;
|
gap: 0;
|
||||||
|
|||||||
@@ -306,4 +306,105 @@ describe('CartComponent', () => {
|
|||||||
|
|
||||||
vi.useRealTimers();
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
computed,
|
computed,
|
||||||
inject,
|
inject,
|
||||||
input,
|
input,
|
||||||
|
model,
|
||||||
output,
|
output,
|
||||||
signal,
|
signal,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
@@ -48,11 +49,21 @@ export class CartComponent {
|
|||||||
readonly discount = input<number>(0);
|
readonly discount = input<number>(0);
|
||||||
readonly total = input<number>(0);
|
readonly total = input<number>(0);
|
||||||
readonly backgroundColor = input<string>('#ffffff');
|
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 closed = output<void>();
|
||||||
|
readonly itemQuantityChange = output<{
|
||||||
|
item: CartItemMock;
|
||||||
|
index: number;
|
||||||
|
quantity: number;
|
||||||
|
}>();
|
||||||
|
|
||||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.quantityUpdates$
|
this.quantityUpdates$
|
||||||
.pipe(
|
.pipe(
|
||||||
@@ -103,6 +114,20 @@ export class CartComponent {
|
|||||||
|
|
||||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||||
const mockItem = this.items()[index];
|
const mockItem = this.items()[index];
|
||||||
|
if (!mockItem) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.itemQuantityChange.emit({
|
||||||
|
item: mockItem,
|
||||||
|
index,
|
||||||
|
quantity: newQuantity,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!this.persistQuantityChanges()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const cartItemId = mockItem?.cartItemId;
|
const cartItemId = mockItem?.cartItemId;
|
||||||
if (cartItemId) {
|
if (cartItemId) {
|
||||||
this.quantityOverrides.update((overrides) => ({
|
this.quantityOverrides.update((overrides) => ({
|
||||||
@@ -153,6 +178,15 @@ export class CartComponent {
|
|||||||
protected readonly formattedDiscount = computed(() => this.formatCurrency(this.discount()));
|
protected readonly formattedDiscount = computed(() => this.formatCurrency(this.discount()));
|
||||||
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
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 {
|
private formatCurrency(value: number): string {
|
||||||
const rounded = Math.round(value);
|
const rounded = Math.round(value);
|
||||||
const parts = rounded.toString().split('.');
|
const parts = rounded.toString().split('.');
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
[placeholder]="placeholder()"
|
[placeholder]="placeholder()"
|
||||||
[value]="type() !== 'file' ? value() : null"
|
[value]="type() !== 'file' ? value() : null"
|
||||||
(input)="type() !== 'file' ? onValueChange($event) : null"
|
(input)="type() !== 'file' ? onValueChange($event) : null"
|
||||||
|
(paste)="onPaste($event)"
|
||||||
(change)="type() === 'file' ? onFileChange($event) : null"
|
(change)="type() === 'file' ? onFileChange($event) : null"
|
||||||
[attr.maxlength]="type() !== 'file' ? maxlength() : null"
|
[attr.maxlength]="type() !== 'file' ? maxlength() : null"
|
||||||
[attr.accept]="type() === 'file' ? accept() : null"
|
[attr.accept]="type() === 'file' ? accept() : null"
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export class InputComponent {
|
|||||||
|
|
||||||
readonly disabledChange = output<boolean>();
|
readonly disabledChange = output<boolean>();
|
||||||
readonly fileChange = output<File | null>();
|
readonly fileChange = output<File | null>();
|
||||||
|
readonly pasteEvent = output<ClipboardEvent>();
|
||||||
readonly visibleChange = output<boolean>();
|
readonly visibleChange = output<boolean>();
|
||||||
|
|
||||||
protected readonly inputType = computed(() => {
|
protected readonly inputType = computed(() => {
|
||||||
@@ -166,6 +167,10 @@ export class InputComponent {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
focus(): void {
|
||||||
|
this.inputElement()?.nativeElement.focus();
|
||||||
|
}
|
||||||
|
|
||||||
protected onValueChange(event: Event): void {
|
protected onValueChange(event: Event): void {
|
||||||
this.value.set((event.target as HTMLInputElement).value);
|
this.value.set((event.target as HTMLInputElement).value);
|
||||||
}
|
}
|
||||||
@@ -176,6 +181,10 @@ export class InputComponent {
|
|||||||
this.fileChange.emit(file);
|
this.fileChange.emit(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected onPaste(event: ClipboardEvent): void {
|
||||||
|
this.pasteEvent.emit(event);
|
||||||
|
}
|
||||||
|
|
||||||
protected toggleEditableState(): void {
|
protected toggleEditableState(): void {
|
||||||
if (this.type() !== 'editable') {
|
if (this.type() !== 'editable') {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
<div
|
<div
|
||||||
class="quantity-selector d-inline-flex align-items-center overflow-hidden rounded"
|
class="quantity-selector d-inline-flex align-items-center overflow-hidden rounded"
|
||||||
[class.quantity-selector--small]="size() === 'small'"
|
[class.quantity-selector--small]="size() === 'small'"
|
||||||
|
[class.quantity-selector--disabled]="disabled()"
|
||||||
aria-label="Selector de cantidad"
|
aria-label="Selector de cantidad"
|
||||||
|
[attr.aria-disabled]="disabled()"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
|
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
|
||||||
aria-label="Disminuir cantidad"
|
aria-label="Disminuir cantidad"
|
||||||
[disabled]="quantity() <= min()"
|
[disabled]="disabled() || quantity() <= min()"
|
||||||
(click)="onDecrease()"
|
(click)="onDecrease()"
|
||||||
>
|
>
|
||||||
-
|
-
|
||||||
@@ -22,7 +24,7 @@
|
|||||||
type="button"
|
type="button"
|
||||||
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
|
class="quantity-selector__button border-0 p-0 fw-bold lh-1"
|
||||||
aria-label="Aumentar cantidad"
|
aria-label="Aumentar cantidad"
|
||||||
[disabled]="atMaximum()"
|
[disabled]="disabled() || atMaximum()"
|
||||||
(click)="onIncrease()"
|
(click)="onIncrease()"
|
||||||
>
|
>
|
||||||
+
|
+
|
||||||
|
|||||||
@@ -60,3 +60,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.quantity-selector--disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|||||||
@@ -52,4 +52,21 @@ describe('QuantitySelectorComponent', () => {
|
|||||||
expect(decreaseButton.disabled).toBe(true);
|
expect(decreaseButton.disabled).toBe(true);
|
||||||
expect(fixture.componentInstance.quantity()).toBe(1);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export class QuantitySelectorComponent {
|
|||||||
readonly min = input<number>(1);
|
readonly min = input<number>(1);
|
||||||
readonly max = input<number | null>(100);
|
readonly max = input<number | null>(100);
|
||||||
readonly size = input<'small' | 'medium'>('medium');
|
readonly size = input<'small' | 'medium'>('medium');
|
||||||
|
readonly disabled = input<boolean>(false);
|
||||||
|
|
||||||
protected readonly atMaximum = computed(() => {
|
protected readonly atMaximum = computed(() => {
|
||||||
const max = this.max();
|
const max = this.max();
|
||||||
@@ -23,14 +24,14 @@ export class QuantitySelectorComponent {
|
|||||||
readonly decrease = output<void>();
|
readonly decrease = output<void>();
|
||||||
|
|
||||||
protected onDecrease(): void {
|
protected onDecrease(): void {
|
||||||
if (this.quantity() > this.min()) {
|
if (!this.disabled() && this.quantity() > this.min()) {
|
||||||
this.quantity.set(this.quantity() - 1);
|
this.quantity.set(this.quantity() - 1);
|
||||||
this.decrease.emit();
|
this.decrease.emit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onIncrease(): void {
|
protected onIncrease(): void {
|
||||||
if (!this.atMaximum()) {
|
if (!this.disabled() && !this.atMaximum()) {
|
||||||
this.quantity.set(this.quantity() + 1);
|
this.quantity.set(this.quantity() + 1);
|
||||||
this.increase.emit();
|
this.increase.emit();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user