16 Commits

Author SHA1 Message Date
38d03588b1 Merge branch 'fix/cart-expiration-notification' of https://gitea.quo.ar/tbianchini/shopit-front into fix/cart-expiration-notification 2026-08-26 10:25:23 -03:00
8e987d0ce6 fix(purchase-status): clear cart on approved purchase 2026-08-26 10:25:16 -03:00
e171b9a233 refactor(checkout): use purchase id route segment 2026-08-26 10:25:16 -03:00
643d43adea fix(checkout): handle expired purchase exits 2026-08-26 10:25:16 -03:00
d89d01b511 fix(checkout): refresh expired carts 2026-08-26 10:25:16 -03:00
eeb245209b fix(checkout): show backend start errors 2026-08-26 10:25:16 -03:00
9d3754c2d8 fix(cart): refresh state after expiration 2026-08-26 10:25:16 -03:00
85529f40f2 fix(register-page): implement password visibility toggle for registration fields 2026-08-26 10:02:56 -03:00
6f4aa3b1bd fix(purchase-status): clear cart on approved purchase 2026-08-26 10:02:26 -03:00
2b342ec235 refactor(checkout): use purchase id route segment 2026-08-25 17:06:07 -03:00
d06b146104 fix(checkout): handle expired purchase exits 2026-08-25 17:05:59 -03:00
f4e0a9e028 fix(checkout): refresh expired carts 2026-08-25 16:47:17 -03:00
8c2b738806 fix(checkout): show backend start errors 2026-08-25 16:46:12 -03:00
1362d0c163 fix(cart): refresh state after expiration 2026-08-25 16:33:44 -03:00
4a952af784 fix(favicon): update favicon handling to use a default SVG icon 2026-08-25 11:44:24 -03:00
b1d4c4d13d fix(reset-password): implement password visibility toggle for input fields 2026-08-25 11:26:56 -03:00
28 changed files with 564 additions and 84 deletions

View File

@@ -7,6 +7,7 @@ import { of } from 'rxjs';
import { App } from './app'; import { App } from './app';
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 { Tenant } from './core/services/tenant.interface'; import { Tenant } from './core/services/tenant.interface';
import { TenantService } from './core/services/tenant.service'; import { TenantService } from './core/services/tenant.service';
import { routes } from './app.routes'; import { routes } from './app.routes';
@@ -97,6 +98,21 @@ async function renderAppAt(
{ {
provide: AuthService, provide: AuthService,
useValue: authService useValue: authService
},
{
provide: CheckoutService,
useValue: {
withCustomLoading() {
return this;
},
getPurchase: vi.fn().mockResolvedValue({
id: 25,
status: 'created',
items: [],
subtotal: '0.00',
total: '0.00'
})
}
} }
] ]
}).compileComponents(); }).compileComponents();
@@ -246,15 +262,33 @@ describe('app routes', () => {
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio'); expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
}); });
it('redirects unauthenticated users from /checkout to /login', async () => { it('redirects unauthenticated users from /checkout/:id to /login', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false)); const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
expect(router.url).toBe('/login?returnUrl=%2Fcheckout'); expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
}); });
it('allows authenticated users to access /checkout', async () => { it('allows authenticated users to access /checkout/:id', async () => {
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true)); const checkoutTenant = {
...tenant,
menues: [
{
id: 1,
code: 'checkout',
label: 'Checkout',
parent_menu_code: null,
content_type: 'dynamic' as const,
route: '/checkout',
submenues: []
}
]
};
const { router } = await renderAppAt(
'/checkout/25',
createTenantServiceStub('ready', checkoutTenant),
createAuthServiceStub(true)
);
expect(router.url).toBe('/checkout'); expect(router.url).toBe('/checkout/25');
}); });
}); });

View File

@@ -115,6 +115,6 @@ describe('App', () => {
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio'); expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
expect(document.title).toBe('ShopitFront'); expect(document.title).toBe('ShopitFront');
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href')) expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
.toBe('favicon.ico'); .toBe("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E");
}); });
}); });

View File

@@ -9,6 +9,8 @@ import { GlobalLoadingComponent } from './shared/components/global-loading/globa
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component'; import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component'; import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
const EMPTY_FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";
function hexToRgb(hex: string): string { function hexToRgb(hex: string): string {
const cleanHex = hex.replace('#', '').trim(); const cleanHex = hex.replace('#', '').trim();
let r = 0, g = 0, b = 0; let r = 0, g = 0, b = 0;
@@ -66,7 +68,7 @@ export class App {
effect(() => { effect(() => {
const tenant = this.tenantService.tenant(); const tenant = this.tenantService.tenant();
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront'; const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
const faviconHref = tenant?.favicon || 'favicon.ico'; const faviconHref = tenant?.favicon || EMPTY_FAVICON;
this.title.setTitle(siteTitle); this.title.setTitle(siteTitle);

View File

@@ -62,7 +62,7 @@ describe('hasMenuGuard', () => {
}); });
it('redirects a missing menu route to the store root', () => { it('redirects a missing menu route to the store root', () => {
const result = runGuard('checkout', '/checkout', tenant); const result = runGuard('checkout', '/checkout/25', tenant);
expect(result instanceof UrlTree).toBe(true); expect(result instanceof UrlTree).toBe(true);
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/'); expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');

View File

@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'; import { describe, it, expect, beforeEach, vi } from 'vitest';
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { import {
@@ -246,7 +247,7 @@ describe('StoreLayoutComponent', () => {
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => { it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
tenantState.set({ ...tenant, base_path: 'fiesta' }); tenantState.set({ ...tenant, base_path: 'fiesta' });
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25'); vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
const fixture = TestBed.createComponent(StoreLayoutComponent); const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges(); fixture.detectChanges();
@@ -587,7 +588,7 @@ describe('StoreLayoutComponent', () => {
const authService = TestBed.inject(AuthService); const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService); const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25'); vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true); const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
const fixture = TestBed.createComponent(StoreLayoutComponent); const fixture = TestBed.createComponent(StoreLayoutComponent);
@@ -674,12 +675,44 @@ describe('StoreLayoutComponent', () => {
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', { expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1, cart_id: 1,
}); });
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], { expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
queryParams: { purchase: 55 },
});
expect((fixture.componentInstance as any).isCartOpen()).toBe(false); expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
}); });
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
checkoutServiceStub.startCheckout.mockRejectedValue(
new HttpErrorResponse({
status: 422,
error: { code: 'stock_reservation.expired', message },
}),
);
cartState.set({
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [],
});
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const fixture = TestBed.createComponent(StoreLayoutComponent);
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
fixture.detectChanges();
loadCart.mockClear();
await (fixture.componentInstance as any).onCheckoutClick();
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
expect(loadCart).toHaveBeenCalledOnce();
});
it('allows modifying quantities directly in the regular cart without a toggle', () => { it('allows modifying quantities directly in the regular cart without a toggle', () => {
cartState.set({ cartState.set({
id: 1, id: 1,

View File

@@ -1,3 +1,4 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core'; import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { import {
@@ -17,7 +18,10 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface'; import { CartItem, CartItemVariantValue } 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 {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service'; import { ToastService } from '../../services/toast.service';
import { Category } from '../../services/tenant.interface'; import { Category } from '../../services/tenant.interface';
@@ -273,12 +277,20 @@ export class StoreLayoutComponent implements OnInit {
}); });
this.isCartOpen.set(false); this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], { await this.router.navigate(['/checkout', purchase.id]);
queryParams: { purchase: purchase.id },
});
} catch (error) { } catch (error) {
console.error('Failed to create cart purchase:', error); console.error('Failed to create cart purchase:', error);
this.toastService.danger('No se pudo iniciar la compra.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra.';
this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} finally { } finally {
this.isCreatingPurchase.set(false); this.isCreatingPurchase.set(false);
} }

View File

@@ -24,12 +24,12 @@ describe('auth guards', () => {
}); });
const result = TestBed.runInInjectionContext(() => const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout?mode=direct' } as never), authGuard(null as never, { url: '/checkout/25' } as never),
); );
expect(result instanceof UrlTree).toBe(true); expect(result instanceof UrlTree).toBe(true);
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe( expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect', '/login?returnUrl=%2Fcheckout%2F25',
); );
}); });
@@ -39,7 +39,7 @@ describe('auth guards', () => {
}); });
const result = TestBed.runInInjectionContext(() => const result = TestBed.runInInjectionContext(() =>
authGuard(null as never, { url: '/checkout' } as never), authGuard(null as never, { url: '/checkout/25' } as never),
); );
expect(result).toBe(true); expect(result).toBe(true);

View File

@@ -45,6 +45,21 @@ export function isInsufficientStockResponse(value: unknown): value is Insufficie
); );
} }
export interface ExpiredStockReservationResponse {
code: 'stock_reservation.expired';
message: string;
}
export function isExpiredStockReservationResponse(
value: unknown,
): value is ExpiredStockReservationResponse {
return (
typeof value === 'object' &&
value !== null &&
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
);
}
export type StartCheckoutPayload = export type StartCheckoutPayload =
| { | {
cart_id: number; cart_id: number;

View File

@@ -23,7 +23,10 @@ import {
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,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import { import {
CatalogGroupLayout, CatalogGroupLayout,
CategoryItemsResponse, CategoryItemsResponse,
@@ -167,10 +170,20 @@ export class CategoryItemsPageComponent {
], ],
}, },
); );
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', purchase.id]);
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra directa.';
this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} finally { } finally {
this.creatingDirectPurchase.set(false); this.creatingDirectPurchase.set(false);
} }

View File

@@ -33,7 +33,7 @@ describe('CheckoutPageComponent payment validation', () => {
stop: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn>;
}; };
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> }; let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>; let routeParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>; let authUserState: ReturnType<typeof signal>;
let tenantState: ReturnType< let tenantState: ReturnType<
typeof signal<{ typeof signal<{
@@ -76,7 +76,7 @@ describe('CheckoutPageComponent payment validation', () => {
cartServiceStub = { cartServiceStub = {
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })), loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
}; };
routeQueryParamMap = convertToParamMap({}); routeParamMap = convertToParamMap({});
authUserState = signal(null); authUserState = signal(null);
tenantState = signal({ tenantState = signal({
codigo: 'tenant-test', codigo: 'tenant-test',
@@ -103,8 +103,8 @@ describe('CheckoutPageComponent payment validation', () => {
provide: ActivatedRoute, provide: ActivatedRoute,
useValue: { useValue: {
snapshot: { snapshot: {
get queryParamMap() { get paramMap() {
return routeQueryParamMap; return routeParamMap;
}, },
}, },
}, },
@@ -317,7 +317,7 @@ describe('CheckoutPageComponent payment validation', () => {
subtotal: '2501.00', subtotal: '2501.00',
total: '2501.00', total: '2501.00',
}; };
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue(purchase); checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
authUserState.set({ authUserState.set({
id: 7, id: 7,
@@ -354,7 +354,7 @@ describe('CheckoutPageComponent payment validation', () => {
it('keeps the checkout hidden while the purchase is loading', async () => { it('keeps the checkout hidden while the purchase is loading', async () => {
let resolvePurchase!: (purchase: any) => void; let resolvePurchase!: (purchase: any) => void;
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockReturnValue( checkoutServiceStub.getPurchase.mockReturnValue(
new Promise((resolve) => { new Promise((resolve) => {
resolvePurchase = resolve; resolvePurchase = resolve;
@@ -375,12 +375,13 @@ describe('CheckoutPageComponent payment validation', () => {
}); });
await Promise.resolve(); await Promise.resolve();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(component.isLoadingPurchase()).toBe(false); expect(component.isLoadingPurchase()).toBe(false);
expect(component.checkoutStepIndex()).toBe(0); expect(component.checkoutStepIndex()).toBe(0);
}); });
it('opens a pending purchase on the payment step and restores its payment method', async () => { it('opens a pending purchase on the payment step and restores its payment method', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -400,7 +401,7 @@ describe('CheckoutPageComponent payment validation', () => {
}); });
it('generates a new QR when reopening a pending QR purchase', async () => { it('generates a new QR when reopening a pending QR purchase', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -424,7 +425,7 @@ describe('CheckoutPageComponent payment validation', () => {
it.each(['paid', 'cancelled', 'rejected', 'expired'])( it.each(['paid', 'cancelled', 'rejected', 'expired'])(
'redirects a %s purchase to its status page', 'redirects a %s purchase to its status page',
async (status) => { async (status) => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status, status,
@@ -442,7 +443,7 @@ describe('CheckoutPageComponent payment validation', () => {
); );
it('redirects a submitted pending payment purchase to its status page', async () => { it('redirects a submitted pending payment purchase to its status page', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@@ -460,7 +461,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
it('shows the API error in a toast when cancelling the purchase fails', async () => { it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
const message = 'La compra venció. Iniciá una nueva compra.'; const message = 'La compra venció. Iniciá una nueva compra.';
checkoutServiceStub.cancelPurchase.mockRejectedValue({ checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { code: 'purchase.expired', message }, error: { code: 'purchase.expired', message },
@@ -470,7 +471,9 @@ describe('CheckoutPageComponent payment validation', () => {
await component.onModifyPurchase(); await component.onModifyPurchase();
expect(toastServiceStub.danger).toHaveBeenCalledWith(message); expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
expect(component.isCancellingPurchase()).toBe(false); expect(component.isCancellingPurchase()).toBe(false);
@@ -587,7 +590,24 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.createdPurchaseId()).toBe(25); expect(component.createdPurchaseId()).toBe(25);
}); });
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => { it('allows leaving checkout when cancellation finds an expired stock reservation', async () => {
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { code: 'stock_reservation.expired', message },
});
const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true);
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(component.createdPurchaseId()).toBeNull();
expect(component.createdPurchase()).toBeNull();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
});
it('shows the API message and redirects to status when a checkout operation finds an expired purchase', async () => {
checkoutServiceStub.generatePaymentIntent.mockRejectedValue( checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
new HttpErrorResponse({ new HttpErrorResponse({
status: 422, status: 422,
@@ -604,10 +624,35 @@ describe('CheckoutPageComponent payment validation', () => {
expect(toastServiceStub.danger).toHaveBeenCalledWith( expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.', 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
); );
expect(routerStub.navigate).toHaveBeenCalledWith(['/']); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(component.isGeneratingIntent()).toBe(false); expect(component.isGeneratingIntent()).toBe(false);
}); });
it('redirects to status when QR polling receives a purchase-expired response', async () => {
checkoutServiceStub.getPurchase.mockRejectedValue(
new HttpErrorResponse({
status: 422,
error: {
code: 'purchase.expired',
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
},
}),
);
const { component } = createComponent();
await component.selectPaymentMethod('qr');
await vi.advanceTimersByTimeAsync(5_000);
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
);
});
it('treats a generic customer-data error as expired when the local deadline passed', () => { it('treats a generic customer-data error as expired when the local deadline passed', () => {
const { component } = createComponent(); const { component } = createComponent();
component.createdPurchase.set({ component.createdPurchase.set({
@@ -635,6 +680,8 @@ describe('CheckoutPageComponent payment validation', () => {
expect(toastServiceStub.danger).toHaveBeenCalledWith( expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.', 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
); );
expect(routerStub.navigate).toHaveBeenCalledWith(['/']); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
}); });
}); });

View File

@@ -161,7 +161,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase')); const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) { if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']); void this.router.navigate(['/']);
return; return;
@@ -296,6 +296,18 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return true; return true;
} catch (error) { } catch (error) {
console.error('Failed to cancel the current purchase:', error); console.error('Failed to cancel the current purchase:', error);
if (this.isStockReservationExpiredError(error)) {
this.showRequestError(error, 'La reserva de stock venció.');
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
this.createdPurchaseId.set(null);
this.createdPurchase.set(null);
this.navigationStarted = true;
return true;
}
this.showRequestError(error, 'No se pudo cancelar la compra.'); this.showRequestError(error, 'No se pudo cancelar la compra.');
return false; return false;
} finally { } finally {
@@ -492,8 +504,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
} }
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) { } catch (error) {
console.error('Failed to validate transfer payment:', error); console.error('Failed to validate transfer payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
} }
if (runId !== this.transferPollingRunId) { if (runId !== this.transferPollingRunId) {
@@ -575,8 +596,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.qrPaymentStatus.set('failed'); this.qrPaymentStatus.set('failed');
return; return;
} }
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) { } catch (error) {
console.error('Failed to validate QR payment:', error); console.error('Failed to validate QR payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
} finally { } finally {
if (runId === this.qrPollingRunId) { if (runId === this.qrPollingRunId) {
this.isCheckingQrPayment.set(false); this.isCheckingQrPayment.set(false);
@@ -683,15 +713,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
console.error('Failed to load purchase:', error); console.error('Failed to load purchase:', error);
this.showRequestError(error, 'No se pudo cargar la compra.'); const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
void this.router.navigate(['/']); if (!expired) {
void this.router.navigate(['/']);
}
} }
} }
private showRequestError(error: unknown, fallbackMessage: string): void { private showRequestError(error: unknown, fallbackMessage: string): boolean {
const payload = const payload =
typeof error === 'object' && error !== null && 'error' in error typeof error === 'object' && error !== null && 'error' in error
? (error as { error?: { message?: unknown } }).error ? (error as { error?: ApiErrorResponse }).error
: undefined; : undefined;
const message = const message =
typeof payload?.message === 'string' && payload.message.trim() typeof payload?.message === 'string' && payload.message.trim()
@@ -699,6 +731,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
: fallbackMessage; : fallbackMessage;
this.toastService.danger(message); this.toastService.danger(message);
if (payload?.code === 'purchase.expired') {
this.navigateToExpiredPurchaseStatus();
return true;
}
return false;
} }
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean { private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
@@ -717,7 +756,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
? response.message ? response.message
: 'La compra venció. Iniciá una nueva compra.', : 'La compra venció. Iniciá una nueva compra.',
); );
void this.router.navigate(['/']); this.navigateToExpiredPurchaseStatus();
return true; return true;
} }
@@ -729,6 +768,42 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return false; return false;
} }
private navigateToExpiredPurchaseStatus(): void {
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
if (purchaseId) {
if (this.navigationStarted) {
return;
}
this.navigationStarted = true;
this.stopQrPolling();
this.stopTransferPolling();
void this.router.navigate(['/checkout/status', purchaseId], {
queryParams: { status: 'expired' },
});
return;
}
void this.router.navigate(['/']);
}
private isPurchaseExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: ApiErrorResponse }).error?.code === 'purchase.expired';
}
private isStockReservationExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: ApiErrorResponse }).error?.code === 'stock_reservation.expired';
}
private hasExpiredPurchase(): boolean { private hasExpiredPurchase(): boolean {
const purchase = this.createdPurchase(); const purchase = this.createdPurchase();

View File

@@ -507,9 +507,7 @@ describe('ProductDetailPageComponent', () => {
}, },
], ],
}); });
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], { expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
queryParams: { purchase: 44 },
});
}); });
it('shows the backend purchase-limit message for a direct checkout', async () => { it('shows the backend purchase-limit message for a direct checkout', async () => {

View File

@@ -358,9 +358,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
], ],
}); });
await this.router.navigate(['/checkout'], { await this.router.navigate(['/checkout', purchase.id]);
queryParams: { purchase: purchase.id },
});
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
const message = const message =

View File

@@ -5,6 +5,7 @@ import {
CheckoutService, CheckoutService,
PurchaseDetailResponse, PurchaseDetailResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { Tenant } from '../../../../core/services/tenant.interface'; import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { PurchaseStatusPageComponent } from './purchase-status-page.component'; import { PurchaseStatusPageComponent } from './purchase-status-page.component';
@@ -66,7 +67,7 @@ describe('PurchaseStatusPageComponent', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
async function render(hasGeneratedTickets: boolean) { async function render(hasGeneratedTickets: boolean, forcedStatus?: string) {
const checkoutService = { const checkoutService = {
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)), getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
withCustomLoading() { withCustomLoading() {
@@ -77,15 +78,24 @@ describe('PurchaseStatusPageComponent', () => {
navigate: vi.fn().mockResolvedValue(true), navigate: vi.fn().mockResolvedValue(true),
navigateByUrl: vi.fn().mockResolvedValue(true), navigateByUrl: vi.fn().mockResolvedValue(true),
}; };
const cartService = { clearCart: vi.fn() };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: cartService },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } }, useValue: {
snapshot: {
paramMap: convertToParamMap({ id: '42' }),
queryParamMap: convertToParamMap(
forcedStatus ? { status: forcedStatus } : {},
),
},
},
}, },
{ provide: Router, useValue: router }, { provide: Router, useValue: router },
], ],
@@ -100,15 +110,22 @@ describe('PurchaseStatusPageComponent', () => {
fixture, fixture,
element: fixture.nativeElement as HTMLElement, element: fixture.nativeElement as HTMLElement,
checkoutService, checkoutService,
cartService,
router, router,
}; };
} }
it('clears the cart when the purchase is approved', async () => {
const { cartService } = await render(true);
expect(cartService.clearCart).toHaveBeenCalledOnce();
});
it('shows the tickets action when this purchase generated tickets', async () => { it('shows the tickets action when this purchase generated tickets', async () => {
const { element, checkoutService, router } = await render(true); const { element, checkoutService, router } = await render(true);
expect(checkoutService.getPurchase).toHaveBeenCalledOnce(); expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
expect(element.textContent).toContain('Ver mis tickets'); expect(element.textContent).toContain('Mis tickets');
expect(element.textContent).not.toContain('WhatsApp'); expect(element.textContent).not.toContain('WhatsApp');
element.querySelector<HTMLButtonElement>('app-button button')?.click(); element.querySelector<HTMLButtonElement>('app-button button')?.click();
@@ -134,6 +151,14 @@ describe('PurchaseStatusPageComponent', () => {
openSpy.mockRestore(); openSpy.mockRestore();
}); });
it('shows the expired result without polling when checkout redirects after expiration', async () => {
const { element, checkoutService } = await render(false, 'expired');
expect(element.textContent).toContain('LA COMPRA VENCIÓ');
expect(element.textContent).not.toContain('ESTAMOS VERIFICANDO TU PAGO');
expect(checkoutService.getPurchase).not.toHaveBeenCalled();
});
it('polls every five seconds while the payment is pending and shows the confirmation', async () => { it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
@@ -147,11 +172,13 @@ describe('PurchaseStatusPageComponent', () => {
return this; return this;
}, },
}; };
const cartService = { clearCart: vi.fn() };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: cartService },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,
@@ -174,6 +201,7 @@ describe('PurchaseStatusPageComponent', () => {
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!'); expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
expect(cartService.clearCart).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(10_000); await vi.advanceTimersByTimeAsync(10_000);
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
@@ -197,6 +225,7 @@ describe('PurchaseStatusPageComponent', () => {
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: { clearCart: vi.fn() } },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,

View File

@@ -15,6 +15,7 @@ import {
CheckoutService, CheckoutService,
PurchaseStatusResponse, PurchaseStatusResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { findMenu } from '../../../../core/services/menu.utils'; import { findMenu } from '../../../../core/services/menu.utils';
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';
@@ -35,6 +36,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly cartService = inject(CartService);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
@@ -72,6 +74,12 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
this.purchaseId = purchaseId; this.purchaseId = purchaseId;
this.tenantCode = tenant.codigo; this.tenantCode = tenant.codigo;
if (this.route.snapshot.queryParamMap?.get('status') === 'expired') {
this.status.set('expired');
this.isLoading.set(false);
return;
}
void this.loadStatus(); void this.loadStatus();
} }
@@ -98,6 +106,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
this.status.set(status); this.status.set(status);
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
if (status === 'approved') {
this.cartService.clearCart();
}
if (status === 'pending') { if (status === 'pending') {
this.schedulePolling(); this.schedulePolling();
} else { } else {
@@ -107,7 +119,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
console.error('Failed to fetch purchase status:', error); console.error('Failed to fetch purchase status:', error);
if (!this.isDestroyed) { if (!this.isDestroyed) {
if (isPolling) { if (this.isPurchaseExpiredError(error)) {
this.status.set('expired');
this.stopPolling();
} else if (isPolling) {
this.schedulePolling(); this.schedulePolling();
} else { } else {
this.status.set('error'); this.status.set('error');
@@ -154,6 +169,14 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'pending'; return 'pending';
} }
private isPurchaseExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: { code?: string } }).error?.code === 'purchase.expired';
}
protected goToTickets(): void { protected goToTickets(): void {
const route = this.ticketsRoute(); const route = this.ticketsRoute();

View File

@@ -38,11 +38,13 @@
<label class="visually-hidden" for="register-password">Contraseña</label> <label class="visually-hidden" for="register-password">Contraseña</label>
<app-input <app-input
id="register-password" id="register-password"
type="password" type="password-toggle"
placeholder="Contraseña" placeholder="Contraseña"
[value]="form.controls.password.value" [value]="form.controls.password.value"
[invalid]="showControlError('password')" [invalid]="showControlError('password')"
[visible]="passwordVisible()"
(valueChange)="updateField('password', $event)" (valueChange)="updateField('password', $event)"
(visibleChange)="setPasswordVisibility($event)"
/> />
@if (getControlError('password'); as errorMessage) { @if (getControlError('password'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small> <small class="text-danger">{{ errorMessage }}</small>
@@ -51,11 +53,13 @@
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label> <label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
<app-input <app-input
id="register-password-repeat" id="register-password-repeat"
type="password" type="password-toggle"
placeholder="Repetir Contraseña" placeholder="Repetir Contraseña"
[value]="form.controls.password_confirmation.value" [value]="form.controls.password_confirmation.value"
[invalid]="showControlError('password_confirmation')" [invalid]="showControlError('password_confirmation')"
[visible]="passwordVisible()"
(valueChange)="updateField('password_confirmation', $event)" (valueChange)="updateField('password_confirmation', $event)"
(visibleChange)="setPasswordVisibility($event)"
/> />
@if (getControlError('password_confirmation'); as errorMessage) { @if (getControlError('password_confirmation'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small> <small class="text-danger">{{ errorMessage }}</small>

View File

@@ -12,6 +12,48 @@ describe('RegisterPageComponent', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
it('shows and hides both password fields with either visibility control', async () => {
await TestBed.configureTestingModule({
imports: [RegisterPageComponent],
providers: [
provideRouter([]),
{ provide: AuthService, useValue: { register: vi.fn() } },
{ provide: ModalService, useValue: { openSimple: vi.fn() } },
{ provide: ToastService, useValue: { danger: vi.fn() } }
]
}).compileComponents();
const fixture = TestBed.createComponent(RegisterPageComponent);
fixture.detectChanges();
const getPasswordInputs = () =>
Array.from(
fixture.nativeElement.querySelectorAll(
'input#register-password, input#register-password-repeat'
)
) as HTMLInputElement[];
const getVisibilityButtons = () =>
Array.from(
fixture.nativeElement.querySelectorAll('button[aria-label]')
) as HTMLButtonElement[];
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
getVisibilityButtons()[0].click();
fixture.detectChanges();
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
'Ocultar contraseña',
'Ocultar contraseña'
]);
getVisibilityButtons()[1].click();
fixture.detectChanges();
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
});
it('submits registration data and redirects to /login on success', async () => { it('submits registration data and redirects to /login on success', async () => {
const authService = { const authService = {
register: vi.fn().mockReturnValue( register: vi.fn().mockReturnValue(

View File

@@ -48,6 +48,7 @@ export class RegisterPageComponent {
private readonly submittedState = signal(false); private readonly submittedState = signal(false);
private readonly serverErrorState = signal<string | null>(null); private readonly serverErrorState = signal<string | null>(null);
private readonly isSubmittingState = signal(false); private readonly isSubmittingState = signal(false);
private readonly passwordVisibleState = signal(false);
protected readonly form = this.formBuilder.nonNullable.group({ protected readonly form = this.formBuilder.nonNullable.group({
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]], nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
@@ -67,6 +68,11 @@ export class RegisterPageComponent {
protected readonly submitted = this.submittedState.asReadonly(); protected readonly submitted = this.submittedState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly(); protected readonly serverError = this.serverErrorState.asReadonly();
protected readonly isSubmitting = this.isSubmittingState.asReadonly(); protected readonly isSubmitting = this.isSubmittingState.asReadonly();
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
protected setPasswordVisibility(visible: boolean): void {
this.passwordVisibleState.set(visible);
}
goToLogin(): void { goToLogin(): void {
void this.router.navigate(['/login']); void this.router.navigate(['/login']);

View File

@@ -13,11 +13,13 @@
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label> <label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
<app-input <app-input
id="reset-password-new" id="reset-password-new"
type="password" type="password-toggle"
placeholder="Nueva Contraseña" placeholder="Nueva Contraseña"
[value]="form.controls.password.value" [value]="form.controls.password.value"
[invalid]="showControlError('password')" [invalid]="showControlError('password')"
[visible]="passwordVisible()"
(valueChange)="updatePassword('password', $event)" (valueChange)="updatePassword('password', $event)"
(visibleChange)="setPasswordVisibility($event)"
/> />
@if (getControlError('password'); as errorMessage) { @if (getControlError('password'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small> <small class="text-danger">{{ errorMessage }}</small>
@@ -30,11 +32,13 @@
</label> </label>
<app-input <app-input
id="reset-password-confirmation" id="reset-password-confirmation"
type="password" type="password-toggle"
placeholder="Repetir Nueva Contraseña" placeholder="Repetir Nueva Contraseña"
[value]="form.controls.password_confirmation.value" [value]="form.controls.password_confirmation.value"
[invalid]="showControlError('password_confirmation')" [invalid]="showControlError('password_confirmation')"
[visible]="passwordVisible()"
(valueChange)="updatePassword('password_confirmation', $event)" (valueChange)="updatePassword('password_confirmation', $event)"
(visibleChange)="setPasswordVisibility($event)"
/> />
@if (getControlError('password_confirmation'); as errorMessage) { @if (getControlError('password_confirmation'); as errorMessage) {
<small class="text-danger">{{ errorMessage }}</small> <small class="text-danger">{{ errorMessage }}</small>

View File

@@ -50,6 +50,43 @@ describe('ResetPasswordPageComponent', () => {
]; ];
} }
it('shows and hides both password fields with either visibility control', async () => {
const modalService = {
openSimple: vi.fn(),
};
await TestBed.configureTestingModule({
imports: [ResetPasswordPageComponent],
providers: resetProviders(modalService),
}).compileComponents();
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
fixture.detectChanges();
const getPasswordInputs = () =>
Array.from(fixture.nativeElement.querySelectorAll('input')) as HTMLInputElement[];
const getVisibilityButtons = () =>
Array.from(
fixture.nativeElement.querySelectorAll('button[aria-label]'),
) as HTMLButtonElement[];
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
getVisibilityButtons()[0].click();
fixture.detectChanges();
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
'Ocultar contraseña',
'Ocultar contraseña',
]);
getVisibilityButtons()[1].click();
fixture.detectChanges();
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
});
it('rejects passwords that do not match', async () => { it('rejects passwords that do not match', async () => {
const modalService = { const modalService = {
openSimple: vi.fn(), openSimple: vi.fn(),

View File

@@ -49,6 +49,7 @@ export class ResetPasswordPageComponent {
private readonly submittedState = signal(false); private readonly submittedState = signal(false);
private readonly isSubmittingState = signal(false); private readonly isSubmittingState = signal(false);
private readonly serverErrorState = signal<string | null>(null); private readonly serverErrorState = signal<string | null>(null);
private readonly passwordVisibleState = signal(false);
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? ''; private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? ''; private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
@@ -72,6 +73,11 @@ export class ResetPasswordPageComponent {
protected readonly submitted = this.submittedState.asReadonly(); protected readonly submitted = this.submittedState.asReadonly();
protected readonly isSubmitting = this.isSubmittingState.asReadonly(); protected readonly isSubmitting = this.isSubmittingState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly(); protected readonly serverError = this.serverErrorState.asReadonly();
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
protected setPasswordVisibility(visible: boolean): void {
this.passwordVisibleState.set(visible);
}
protected updatePassword(controlName: PasswordControlName, value: string | number): void { protected updatePassword(controlName: PasswordControlName, value: string | number): void {
this.form.controls[controlName].setValue(String(value)); this.form.controls[controlName].setValue(String(value));

View File

@@ -24,7 +24,10 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CheckoutService } from '../../../../core/services/checkout.service'; import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import { import {
CatalogFeaturedItem, CatalogFeaturedItem,
CatalogFeaturedItems, CatalogFeaturedItems,
@@ -199,10 +202,20 @@ export class SearchPageComponent {
], ],
}, },
); );
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', purchase.id]);
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
this.toastService.danger('No se pudo iniciar la compra directa.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra directa.';
this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} finally { } finally {
this.creatingDirectPurchase.set(false); this.creatingDirectPurchase.set(false);
} }

View File

@@ -21,6 +21,7 @@ import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { import {
CheckoutService, CheckoutService,
isExpiredStockReservationResponse,
isInsufficientStockResponse, isInsufficientStockResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { import {
@@ -217,10 +218,18 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
tenant.codigo, tenant.codigo,
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems }, reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
); );
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); await this.router.navigate(['/checkout', purchase.id]);
} catch (error) { } catch (error) {
console.error('Failed to create direct purchase:', error); console.error('Failed to create direct purchase:', error);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.toastService.danger(error.error.message);
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
return;
}
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) { if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
const unavailableIds = error.error.unavailable_items const unavailableIds = error.error.unavailable_items
.map((item) => item.variant_id) .map((item) => item.variant_id)

View File

@@ -91,15 +91,6 @@ export const routes: Routes = [
(m) => m.ProductDetailPageComponent, (m) => m.ProductDetailPageComponent,
), ),
}, },
{
path: 'checkout',
canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent,
),
},
{ {
path: 'checkout/status', path: 'checkout/status',
component: SimpleLayoutComponent, component: SimpleLayoutComponent,
@@ -113,6 +104,15 @@ export const routes: Routes = [
}, },
], ],
}, },
{
path: 'checkout/:id',
canActivate: [authGuard, hasMenuGuard('checkout')],
canDeactivate: [checkoutPendingPurchaseGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent,
),
},
{ {
path: 'ayuda', path: 'ayuda',
canActivate: [hasMenuGuard('help')], canActivate: [hasMenuGuard('help')],

View File

@@ -175,6 +175,63 @@ describe('CartComponent', () => {
expect(removeItem).not.toHaveBeenCalled(); expect(removeItem).not.toHaveBeenCalled();
}); });
it('notifies the user and refreshes the cart when a mutation reports expiration', async () => {
const expirationMessage = 'La reserva de stock venció. Usá el carrito activo para continuar.';
const removeItem = vi.fn().mockReturnValue(
throwError(() => ({
error: {
code: 'stock_reservation.expired',
message: expirationMessage,
},
})),
);
const loadCart = vi.fn().mockReturnValue(of({}));
const danger = vi.fn();
await TestBed.configureTestingModule({
imports: [CartComponent],
providers: [
{
provide: CartService,
useValue: {
cart: signal(null).asReadonly(),
loadCart,
updateItemQuantity: vi.fn(),
removeItem,
},
},
{
provide: ModalService,
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
},
{
provide: ToastService,
useValue: { success: vi.fn(), info: vi.fn(), danger },
},
],
}).compileComponents();
const fixture = TestBed.createComponent(CartComponent);
fixture.componentRef.setInput('items', [
{
cartItemId: 10,
imageUrl: null,
product: 'Producto vencido',
originalPrice: null,
discountedPrice: 1000,
discountPercentage: null,
attributes: [],
quantity: 1,
},
]);
fixture.detectChanges();
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('remove');
expect(danger).toHaveBeenCalledWith(expirationMessage);
expect(loadCart).toHaveBeenCalledOnce();
});
it('optimistically updates quantity and rolls back on error', async () => { it('optimistically updates quantity and rolls back on error', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error'))); const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));

View File

@@ -98,11 +98,12 @@ export class CartComponent {
this.clearOverride(update.cartItemId); this.clearOverride(update.cartItemId);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
console.error('Error updating cart quantity', err);
const msg =
err.error?.message || 'Error al actualizar la cantidad del producto.';
this.toastService.danger(msg);
this.clearOverride(update.cartItemId); this.clearOverride(update.cartItemId);
this.handleMutationError(
err,
'Error al actualizar la cantidad del producto.',
'Error updating cart quantity',
);
}, },
}), }),
catchError(() => EMPTY), catchError(() => EMPTY),
@@ -205,9 +206,12 @@ export class CartComponent {
this.toastService.success(response.message || 'Variante actualizada.'); this.toastService.success(response.message || 'Variante actualizada.');
}, },
error: (error: HttpErrorResponse) => { error: (error: HttpErrorResponse) => {
console.error('Error updating cart item variant', error);
this.clearVariantOverride(cartItemId); this.clearVariantOverride(cartItemId);
this.toastService.danger(error.error?.message || 'No se pudo actualizar la variante.'); this.handleMutationError(
error,
'No se pudo actualizar la variante.',
'Error updating cart item variant',
);
}, },
}); });
} }
@@ -305,10 +309,29 @@ export class CartComponent {
this.toastService.info(msg); this.toastService.info(msg);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
console.error('Error removing item from cart', err); this.handleMutationError(
const msg = err.error?.message || 'Error al eliminar el producto del carrito.'; err,
this.toastService.danger(msg); 'Error al eliminar el producto del carrito.',
'Error removing item from cart',
);
}, },
}); });
} }
private handleMutationError(
error: HttpErrorResponse,
fallbackMessage: string,
logMessage: string,
): void {
console.error(logMessage, error);
this.toastService.danger(error.error?.message || fallbackMessage);
if (error.error?.code !== 'stock_reservation.expired') {
return;
}
this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} }

View File

@@ -1,5 +1,5 @@
export const environment = { export const environment = {
production: false, production: true,
nombre:"Homologación - activo", nombre:"Homologación - activo",
url:"https://backend.qa.shopit.com.ar/api/", url:"https://backend.qa.shopit.com.ar/api/",
urlDescarga:"url/" urlDescarga:"url/"

View File

@@ -5,7 +5,7 @@
<title>ShopitFront</title> <title>ShopitFront</title>
<base href="/"> <base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E">
</head> </head>
<body> <body>
<app-root></app-root> <app-root></app-root>