From 1362d0c1632fd634d2c03be79af3ffbbd71fd129 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:33:44 -0300 Subject: [PATCH 01/12] fix(cart): refresh state after expiration --- .../components/cart/cart.component.spec.ts | 57 +++++++++++++++++++ .../shared/components/cart/cart.component.ts | 41 ++++++++++--- 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/src/app/shared/components/cart/cart.component.spec.ts b/src/app/shared/components/cart/cart.component.spec.ts index 7aaf644..ebb46da 100644 --- a/src/app/shared/components/cart/cart.component.spec.ts +++ b/src/app/shared/components/cart/cart.component.spec.ts @@ -175,6 +175,63 @@ describe('CartComponent', () => { 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 () => { vi.useFakeTimers(); const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error'))); diff --git a/src/app/shared/components/cart/cart.component.ts b/src/app/shared/components/cart/cart.component.ts index bcd1bb1..2f57de5 100644 --- a/src/app/shared/components/cart/cart.component.ts +++ b/src/app/shared/components/cart/cart.component.ts @@ -98,11 +98,12 @@ export class CartComponent { this.clearOverride(update.cartItemId); }, 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.handleMutationError( + err, + 'Error al actualizar la cantidad del producto.', + 'Error updating cart quantity', + ); }, }), catchError(() => EMPTY), @@ -205,9 +206,12 @@ export class CartComponent { this.toastService.success(response.message || 'Variante actualizada.'); }, error: (error: HttpErrorResponse) => { - console.error('Error updating cart item variant', error); 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); }, error: (err: HttpErrorResponse) => { - console.error('Error removing item from cart', err); - const msg = err.error?.message || 'Error al eliminar el producto del carrito.'; - this.toastService.danger(msg); + this.handleMutationError( + err, + '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), + }); + } } From 8c2b738806569094456a90eb0e90de4ba9f01353 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:46:12 -0300 Subject: [PATCH 02/12] fix(checkout): show backend start errors --- .../store-layout.component.spec.ts | 29 +++++++++++++++++++ .../store-layout/store-layout.component.ts | 8 ++++- .../category-items-page.component.ts | 7 ++++- .../search-page/search-page.component.ts | 7 ++++- 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index 6dc5dea..c7551ad 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { @@ -680,6 +681,34 @@ describe('StoreLayoutComponent', () => { expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); + it('shows the backend message when starting checkout fails', async () => { + const message = 'Alcanzaste el límite de compra para este producto.'; + checkoutServiceStub.startCheckout.mockRejectedValue( + new HttpErrorResponse({ status: 422, error: { 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); + fixture.detectChanges(); + + await (fixture.componentInstance as any).onCheckoutClick(); + + expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message); + }); + it('allows modifying quantities directly in the regular cart without a toggle', () => { cartState.set({ id: 1, diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index 53e8b10..ea5dd24 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -1,3 +1,4 @@ +import { HttpErrorResponse } from '@angular/common/http'; import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { @@ -278,7 +279,12 @@ export class StoreLayoutComponent implements OnInit { }); } catch (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); + } finally { this.isCreatingPurchase.set(false); } diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index 4af5b4f..cf8d447 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -170,7 +170,12 @@ export class CategoryItemsPageComponent { 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.'); + const message = + error instanceof HttpErrorResponse && typeof error.error?.message === 'string' + ? error.error.message + : 'No se pudo iniciar la compra directa.'; + this.toastService.danger(message); + } finally { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index 8715d9c..729e387 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -202,7 +202,12 @@ export class SearchPageComponent { 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.'); + const message = + error instanceof HttpErrorResponse && typeof error.error?.message === 'string' + ? error.error.message + : 'No se pudo iniciar la compra directa.'; + this.toastService.danger(message); + } finally { this.creatingDirectPurchase.set(false); } From f4e0a9e028eb49d3812c1eaf569a5dfa860933cf Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:47:17 -0300 Subject: [PATCH 03/12] fix(checkout): refresh expired carts --- .../store-layout/store-layout.component.spec.ts | 12 +++++++++--- .../layout/store-layout/store-layout.component.ts | 10 +++++++++- src/app/core/services/checkout.service.ts | 15 +++++++++++++++ .../category-items-page.component.ts | 10 +++++++++- .../pages/search-page/search-page.component.ts | 10 +++++++++- .../store-home-page/store-home-page.component.ts | 9 +++++++++ 6 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index c7551ad..04fd5be 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -681,10 +681,13 @@ describe('StoreLayoutComponent', () => { expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); - it('shows the backend message when starting checkout fails', async () => { - const message = 'Alcanzaste el límite de compra para este producto.'; + 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: { message } }), + new HttpErrorResponse({ + status: 422, + error: { code: 'stock_reservation.expired', message }, + }), ); cartState.set({ id: 1, @@ -702,11 +705,14 @@ describe('StoreLayoutComponent', () => { }); 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', () => { diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index ea5dd24..4bf5c38 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -18,7 +18,10 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface'; import { AuthService } from '../../services/auth/auth.service'; import { findMenu } from '../../services/menu.utils'; -import { CheckoutService } from '../../services/checkout.service'; +import { + CheckoutService, + isExpiredStockReservationResponse, +} from '../../services/checkout.service'; import { ToastService } from '../../services/toast.service'; import { Category } from '../../services/tenant.interface'; @@ -285,6 +288,11 @@ export class StoreLayoutComponent implements OnInit { : '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 { this.isCreatingPurchase.set(false); } diff --git a/src/app/core/services/checkout.service.ts b/src/app/core/services/checkout.service.ts index df1a4e2..1952549 100644 --- a/src/app/core/services/checkout.service.ts +++ b/src/app/core/services/checkout.service.ts @@ -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).code === 'stock_reservation.expired' + ); +} + export type StartCheckoutPayload = | { cart_id: number; diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index cf8d447..e020300 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -23,7 +23,10 @@ import { import { AuthService } from '../../../../core/services/auth/auth.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 { CatalogGroupLayout, CategoryItemsResponse, @@ -176,6 +179,11 @@ export class CategoryItemsPageComponent { : '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 { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index 729e387..ba3bc45 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -24,7 +24,10 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CartService } from '../../../../core/services/cart/cart.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 { CatalogFeaturedItem, CatalogFeaturedItems, @@ -208,6 +211,11 @@ export class SearchPageComponent { : '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 { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/store-home-page/store-home-page.component.ts b/src/app/features/store/pages/store-home-page/store-home-page.component.ts index e9fa018..12b8605 100644 --- a/src/app/features/store/pages/store-home-page/store-home-page.component.ts +++ b/src/app/features/store/pages/store-home-page/store-home-page.component.ts @@ -21,6 +21,7 @@ import { TenantService } from '../../../../core/services/tenant.service'; import { ToastService } from '../../../../core/services/toast.service'; import { CheckoutService, + isExpiredStockReservationResponse, isInsufficientStockResponse, } from '../../../../core/services/checkout.service'; import { @@ -221,6 +222,14 @@ export class StoreHomePageComponent implements OnInit, OnDestroy { } catch (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)) { const unavailableIds = error.error.unavailable_items .map((item) => item.variant_id) From d06b146104b7f61f784180d9a40a590a78679388 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 17:05:59 -0300 Subject: [PATCH 04/12] fix(checkout): handle expired purchase exits --- .../checkout-page.component.spec.ts | 56 ++++++++++-- .../checkout-page/checkout-page.component.ts | 85 +++++++++++++++++-- .../purchase-status-page.component.spec.ts | 19 ++++- .../purchase-status-page.component.ts | 19 ++++- 4 files changed, 166 insertions(+), 13 deletions(-) diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts index 77b29a7..e7e34a2 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts @@ -460,7 +460,7 @@ describe('CheckoutPageComponent payment validation', () => { 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.'; checkoutServiceStub.cancelPurchase.mockRejectedValue({ error: { code: 'purchase.expired', message }, @@ -470,7 +470,9 @@ describe('CheckoutPageComponent payment validation', () => { await component.onModifyPurchase(); 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.stop).toHaveBeenCalledOnce(); expect(component.isCancellingPurchase()).toBe(false); @@ -587,7 +589,24 @@ describe('CheckoutPageComponent payment validation', () => { 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( new HttpErrorResponse({ status: 422, @@ -604,10 +623,35 @@ describe('CheckoutPageComponent payment validation', () => { expect(toastServiceStub.danger).toHaveBeenCalledWith( '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); }); + 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', () => { const { component } = createComponent(); component.createdPurchase.set({ @@ -635,6 +679,8 @@ describe('CheckoutPageComponent payment validation', () => { expect(toastServiceStub.danger).toHaveBeenCalledWith( 'La compra venci\u00f3. Inici\u00e1 una nueva compra.', ); - expect(routerStub.navigate).toHaveBeenCalledWith(['/']); + expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], { + queryParams: { status: 'expired' }, + }); }); }); diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.ts index e4205dd..faca4cf 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.ts @@ -296,6 +296,18 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { return true; } catch (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.'); return false; } finally { @@ -492,8 +504,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { this.navigateToPurchaseStatus(purchaseId); return; } + + if (purchase.status === 'expired') { + this.navigateToPurchaseStatus(purchaseId); + return; + } } catch (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) { @@ -575,8 +596,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { this.qrPaymentStatus.set('failed'); return; } + + if (purchase.status === 'expired') { + this.navigateToPurchaseStatus(purchaseId); + return; + } } catch (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 { if (runId === this.qrPollingRunId) { this.isCheckingQrPayment.set(false); @@ -683,15 +713,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { } } catch (error) { console.error('Failed to load purchase:', error); - this.showRequestError(error, 'No se pudo cargar la compra.'); - void this.router.navigate(['/']); + const expired = this.showRequestError(error, 'No se pudo cargar la compra.'); + if (!expired) { + void this.router.navigate(['/']); + } } } - private showRequestError(error: unknown, fallbackMessage: string): void { + private showRequestError(error: unknown, fallbackMessage: string): boolean { const payload = typeof error === 'object' && error !== null && 'error' in error - ? (error as { error?: { message?: unknown } }).error + ? (error as { error?: ApiErrorResponse }).error : undefined; const message = typeof payload?.message === 'string' && payload.message.trim() @@ -699,6 +731,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { : fallbackMessage; this.toastService.danger(message); + + if (payload?.code === 'purchase.expired') { + this.navigateToExpiredPurchaseStatus(); + return true; + } + + return false; } private handleCheckoutError(error: unknown, fallbackMessage: string): boolean { @@ -717,7 +756,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { ? response.message : 'La compra venció. Iniciá una nueva compra.', ); - void this.router.navigate(['/']); + this.navigateToExpiredPurchaseStatus(); return true; } @@ -729,6 +768,42 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { 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 { const purchase = this.createdPurchase(); diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts index a41a839..7cd36b6 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts @@ -66,7 +66,7 @@ describe('PurchaseStatusPageComponent', () => { TestBed.resetTestingModule(); }); - async function render(hasGeneratedTickets: boolean) { + async function render(hasGeneratedTickets: boolean, forcedStatus?: string) { const checkoutService = { getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)), withCustomLoading() { @@ -85,7 +85,14 @@ describe('PurchaseStatusPageComponent', () => { { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, - useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } }, + useValue: { + snapshot: { + paramMap: convertToParamMap({ id: '42' }), + queryParamMap: convertToParamMap( + forcedStatus ? { status: forcedStatus } : {}, + ), + }, + }, }, { provide: Router, useValue: router }, ], @@ -134,6 +141,14 @@ describe('PurchaseStatusPageComponent', () => { 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 () => { vi.useFakeTimers(); diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts index 2797027..216fd9e 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts @@ -72,6 +72,12 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { this.purchaseId = purchaseId; this.tenantCode = tenant.codigo; + if (this.route.snapshot.queryParamMap?.get('status') === 'expired') { + this.status.set('expired'); + this.isLoading.set(false); + return; + } + void this.loadStatus(); } @@ -107,7 +113,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { console.error('Failed to fetch purchase status:', error); if (!this.isDestroyed) { - if (isPolling) { + if (this.isPurchaseExpiredError(error)) { + this.status.set('expired'); + this.stopPolling(); + } else if (isPolling) { this.schedulePolling(); } else { this.status.set('error'); @@ -154,6 +163,14 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { 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 { const route = this.ticketsRoute(); From 2b342ec235220964a22d5e59f60ee7d38ead8c5a Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 17:06:07 -0300 Subject: [PATCH 05/12] refactor(checkout): use purchase id route segment --- src/app/app.routes.spec.ts | 46 ++++++++++++++++--- src/app/core/guards/menu.guard.spec.ts | 2 +- .../store-layout.component.spec.ts | 8 ++-- .../store-layout/store-layout.component.ts | 4 +- .../core/services/auth/auth.guards.spec.ts | 6 +-- .../category-items-page.component.ts | 2 +- .../checkout-page.component.spec.ts | 21 +++++---- .../checkout-page/checkout-page.component.ts | 2 +- .../product-detail-page.component.spec.ts | 4 +- .../product-detail-page.component.ts | 4 +- .../search-page/search-page.component.ts | 2 +- .../store-home-page.component.ts | 2 +- src/app/features/store/store.routes.ts | 18 ++++---- 13 files changed, 74 insertions(+), 47 deletions(-) diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index 55f51b7..33e9f1b 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -7,6 +7,7 @@ import { of } from 'rxjs'; import { App } from './app'; import { AuthService } from './core/services/auth/auth.service'; import { CartService } from './core/services/cart/cart.service'; +import { CheckoutService } from './core/services/checkout.service'; import { Tenant } from './core/services/tenant.interface'; import { TenantService } from './core/services/tenant.service'; import { routes } from './app.routes'; @@ -97,6 +98,21 @@ async function renderAppAt( { provide: 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(); @@ -246,15 +262,33 @@ describe('app routes', () => { expect(compiled.textContent).toContain('No encontramos una tienda para este dominio'); }); - it('redirects unauthenticated users from /checkout to /login', async () => { - const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false)); + it('redirects unauthenticated users from /checkout/:id to /login', async () => { + 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 () => { - const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true)); + it('allows authenticated users to access /checkout/:id', async () => { + 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'); }); }); diff --git a/src/app/core/guards/menu.guard.spec.ts b/src/app/core/guards/menu.guard.spec.ts index e8159e6..3bf9479 100644 --- a/src/app/core/guards/menu.guard.spec.ts +++ b/src/app/core/guards/menu.guard.spec.ts @@ -62,7 +62,7 @@ describe('hasMenuGuard', () => { }); 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(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/'); diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index 04fd5be..2f6f160 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -247,7 +247,7 @@ describe('StoreLayoutComponent', () => { it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => { tenantState.set({ ...tenant, base_path: 'fiesta' }); 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); fixture.detectChanges(); @@ -588,7 +588,7 @@ describe('StoreLayoutComponent', () => { const authService = TestBed.inject(AuthService); const cartService = TestBed.inject(CartService); 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 fixture = TestBed.createComponent(StoreLayoutComponent); @@ -675,9 +675,7 @@ describe('StoreLayoutComponent', () => { expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', { cart_id: 1, }); - expect(router.navigate).toHaveBeenCalledWith(['/checkout'], { - queryParams: { purchase: 55 }, - }); + expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]); expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index 4bf5c38..e812afc 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -277,9 +277,7 @@ export class StoreLayoutComponent implements OnInit { }); this.isCartOpen.set(false); - await this.router.navigate(['/checkout'], { - queryParams: { purchase: purchase.id }, - }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create cart purchase:', error); const message = diff --git a/src/app/core/services/auth/auth.guards.spec.ts b/src/app/core/services/auth/auth.guards.spec.ts index 485a57a..fefb63d 100644 --- a/src/app/core/services/auth/auth.guards.spec.ts +++ b/src/app/core/services/auth/auth.guards.spec.ts @@ -24,12 +24,12 @@ describe('auth guards', () => { }); 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(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(() => - authGuard(null as never, { url: '/checkout' } as never), + authGuard(null as never, { url: '/checkout/25' } as never), ); expect(result).toBe(true); diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index e020300..8150675 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -170,7 +170,7 @@ export class CategoryItemsPageComponent { ], }, ); - await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts index e7e34a2..9893f29 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts @@ -33,7 +33,7 @@ describe('CheckoutPageComponent payment validation', () => { stop: ReturnType; }; let cartServiceStub: { loadCart: ReturnType }; - let routeQueryParamMap: ReturnType; + let routeParamMap: ReturnType; let authUserState: ReturnType; let tenantState: ReturnType< typeof signal<{ @@ -76,7 +76,7 @@ describe('CheckoutPageComponent payment validation', () => { cartServiceStub = { loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })), }; - routeQueryParamMap = convertToParamMap({}); + routeParamMap = convertToParamMap({}); authUserState = signal(null); tenantState = signal({ codigo: 'tenant-test', @@ -103,8 +103,8 @@ describe('CheckoutPageComponent payment validation', () => { provide: ActivatedRoute, useValue: { snapshot: { - get queryParamMap() { - return routeQueryParamMap; + get paramMap() { + return routeParamMap; }, }, }, @@ -317,7 +317,7 @@ describe('CheckoutPageComponent payment validation', () => { subtotal: '2501.00', total: '2501.00', }; - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue(purchase); authUserState.set({ id: 7, @@ -354,7 +354,7 @@ describe('CheckoutPageComponent payment validation', () => { it('keeps the checkout hidden while the purchase is loading', async () => { let resolvePurchase!: (purchase: any) => void; - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockReturnValue( new Promise((resolve) => { resolvePurchase = resolve; @@ -375,12 +375,13 @@ describe('CheckoutPageComponent payment validation', () => { }); await Promise.resolve(); + expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(component.isLoadingPurchase()).toBe(false); expect(component.checkoutStepIndex()).toBe(0); }); 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({ id: 25, status: 'pending_payment', @@ -400,7 +401,7 @@ describe('CheckoutPageComponent payment validation', () => { }); it('generates a new QR when reopening a pending QR purchase', async () => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status: 'pending_payment', @@ -424,7 +425,7 @@ describe('CheckoutPageComponent payment validation', () => { it.each(['paid', 'cancelled', 'rejected', 'expired'])( 'redirects a %s purchase to its status page', async (status) => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status, @@ -442,7 +443,7 @@ describe('CheckoutPageComponent payment validation', () => { ); it('redirects a submitted pending payment purchase to its status page', async () => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status: 'pending_payment', diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.ts index faca4cf..d15bf71 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.ts @@ -161,7 +161,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { } 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) { void this.router.navigate(['/']); return; diff --git a/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts b/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts index 5e020c8..e1c7350 100644 --- a/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts +++ b/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts @@ -507,9 +507,7 @@ describe('ProductDetailPageComponent', () => { }, ], }); - expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], { - queryParams: { purchase: 44 }, - }); + expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]); }); it('shows the backend purchase-limit message for a direct checkout', async () => { diff --git a/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts b/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts index 0e869a6..9729331 100644 --- a/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts +++ b/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts @@ -358,9 +358,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy { ], }); - await this.router.navigate(['/checkout'], { - queryParams: { purchase: purchase.id }, - }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index ba3bc45..ab84859 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -202,7 +202,7 @@ export class SearchPageComponent { ], }, ); - await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/store-home-page/store-home-page.component.ts b/src/app/features/store/pages/store-home-page/store-home-page.component.ts index 12b8605..bb4a236 100644 --- a/src/app/features/store/pages/store-home-page/store-home-page.component.ts +++ b/src/app/features/store/pages/store-home-page/store-home-page.component.ts @@ -218,7 +218,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy { tenant.codigo, 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) { console.error('Failed to create direct purchase:', error); diff --git a/src/app/features/store/store.routes.ts b/src/app/features/store/store.routes.ts index a78e899..dc5719e 100644 --- a/src/app/features/store/store.routes.ts +++ b/src/app/features/store/store.routes.ts @@ -91,15 +91,6 @@ export const routes: Routes = [ (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', 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', canActivate: [hasMenuGuard('help')], From 6f4aa3b1bd3c35ed4d86e31d17c066bf56f8e2fa Mon Sep 17 00:00:00 2001 From: ncoronel Date: Wed, 26 Aug 2026 10:02:26 -0300 Subject: [PATCH 06/12] fix(purchase-status): clear cart on approved purchase --- .../purchase-status-page.component.spec.ts | 16 +++++++++++++++- .../purchase-status-page.component.ts | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts index 7cd36b6..6dcf23c 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts @@ -5,6 +5,7 @@ import { CheckoutService, PurchaseDetailResponse, } from '../../../../core/services/checkout.service'; +import { CartService } from '../../../../core/services/cart/cart.service'; import { Tenant } from '../../../../core/services/tenant.interface'; import { TenantService } from '../../../../core/services/tenant.service'; import { PurchaseStatusPageComponent } from './purchase-status-page.component'; @@ -77,11 +78,13 @@ describe('PurchaseStatusPageComponent', () => { navigate: vi.fn().mockResolvedValue(true), navigateByUrl: vi.fn().mockResolvedValue(true), }; + const cartService = { clearCart: vi.fn() }; await TestBed.configureTestingModule({ imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: cartService }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, @@ -107,15 +110,22 @@ describe('PurchaseStatusPageComponent', () => { fixture, element: fixture.nativeElement as HTMLElement, checkoutService, + cartService, 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 () => { const { element, checkoutService, router } = await render(true); expect(checkoutService.getPurchase).toHaveBeenCalledOnce(); - expect(element.textContent).toContain('Ver mis tickets'); + expect(element.textContent).toContain('Mis tickets'); expect(element.textContent).not.toContain('WhatsApp'); element.querySelector('app-button button')?.click(); @@ -162,11 +172,13 @@ describe('PurchaseStatusPageComponent', () => { return this; }, }; + const cartService = { clearCart: vi.fn() }; await TestBed.configureTestingModule({ imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: cartService }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, @@ -189,6 +201,7 @@ describe('PurchaseStatusPageComponent', () => { expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!'); + expect(cartService.clearCart).toHaveBeenCalledOnce(); await vi.advanceTimersByTimeAsync(10_000); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); @@ -212,6 +225,7 @@ describe('PurchaseStatusPageComponent', () => { imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: { clearCart: vi.fn() } }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts index 216fd9e..f04a492 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts @@ -15,6 +15,7 @@ import { CheckoutService, PurchaseStatusResponse, } from '../../../../core/services/checkout.service'; +import { CartService } from '../../../../core/services/cart/cart.service'; import { findMenu } from '../../../../core/services/menu.utils'; import { TenantService } from '../../../../core/services/tenant.service'; 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 router = inject(Router); private readonly checkoutService = inject(CheckoutService); + private readonly cartService = inject(CartService); private readonly tenantService = inject(TenantService); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); @@ -104,6 +106,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { this.status.set(status); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); + if (status === 'approved') { + this.cartService.clearCart(); + } + if (status === 'pending') { this.schedulePolling(); } else { From 9d3754c2d85834abf5b0456d4fe7e3a893bd9a44 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:33:44 -0300 Subject: [PATCH 07/12] fix(cart): refresh state after expiration --- .../components/cart/cart.component.spec.ts | 57 +++++++++++++++++++ .../shared/components/cart/cart.component.ts | 41 ++++++++++--- 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/src/app/shared/components/cart/cart.component.spec.ts b/src/app/shared/components/cart/cart.component.spec.ts index 7aaf644..ebb46da 100644 --- a/src/app/shared/components/cart/cart.component.spec.ts +++ b/src/app/shared/components/cart/cart.component.spec.ts @@ -175,6 +175,63 @@ describe('CartComponent', () => { 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 () => { vi.useFakeTimers(); const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error'))); diff --git a/src/app/shared/components/cart/cart.component.ts b/src/app/shared/components/cart/cart.component.ts index bcd1bb1..2f57de5 100644 --- a/src/app/shared/components/cart/cart.component.ts +++ b/src/app/shared/components/cart/cart.component.ts @@ -98,11 +98,12 @@ export class CartComponent { this.clearOverride(update.cartItemId); }, 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.handleMutationError( + err, + 'Error al actualizar la cantidad del producto.', + 'Error updating cart quantity', + ); }, }), catchError(() => EMPTY), @@ -205,9 +206,12 @@ export class CartComponent { this.toastService.success(response.message || 'Variante actualizada.'); }, error: (error: HttpErrorResponse) => { - console.error('Error updating cart item variant', error); 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); }, error: (err: HttpErrorResponse) => { - console.error('Error removing item from cart', err); - const msg = err.error?.message || 'Error al eliminar el producto del carrito.'; - this.toastService.danger(msg); + this.handleMutationError( + err, + '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), + }); + } } From eeb245209b10a347bdc4a6245abf59bcef3a3f86 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:46:12 -0300 Subject: [PATCH 08/12] fix(checkout): show backend start errors --- .../store-layout.component.spec.ts | 29 +++++++++++++++++++ .../store-layout/store-layout.component.ts | 8 ++++- .../category-items-page.component.ts | 7 ++++- .../search-page/search-page.component.ts | 7 ++++- 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index 6dc5dea..c7551ad 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { @@ -680,6 +681,34 @@ describe('StoreLayoutComponent', () => { expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); + it('shows the backend message when starting checkout fails', async () => { + const message = 'Alcanzaste el límite de compra para este producto.'; + checkoutServiceStub.startCheckout.mockRejectedValue( + new HttpErrorResponse({ status: 422, error: { 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); + fixture.detectChanges(); + + await (fixture.componentInstance as any).onCheckoutClick(); + + expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message); + }); + it('allows modifying quantities directly in the regular cart without a toggle', () => { cartState.set({ id: 1, diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index 53e8b10..ea5dd24 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -1,3 +1,4 @@ +import { HttpErrorResponse } from '@angular/common/http'; import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { @@ -278,7 +279,12 @@ export class StoreLayoutComponent implements OnInit { }); } catch (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); + } finally { this.isCreatingPurchase.set(false); } diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index 4af5b4f..cf8d447 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -170,7 +170,12 @@ export class CategoryItemsPageComponent { 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.'); + const message = + error instanceof HttpErrorResponse && typeof error.error?.message === 'string' + ? error.error.message + : 'No se pudo iniciar la compra directa.'; + this.toastService.danger(message); + } finally { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index 8715d9c..729e387 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -202,7 +202,12 @@ export class SearchPageComponent { 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.'); + const message = + error instanceof HttpErrorResponse && typeof error.error?.message === 'string' + ? error.error.message + : 'No se pudo iniciar la compra directa.'; + this.toastService.danger(message); + } finally { this.creatingDirectPurchase.set(false); } From d89d01b511a2dc231d3bf52fdece4b49b1c8e354 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 16:47:17 -0300 Subject: [PATCH 09/12] fix(checkout): refresh expired carts --- .../store-layout/store-layout.component.spec.ts | 12 +++++++++--- .../layout/store-layout/store-layout.component.ts | 10 +++++++++- src/app/core/services/checkout.service.ts | 15 +++++++++++++++ .../category-items-page.component.ts | 10 +++++++++- .../pages/search-page/search-page.component.ts | 10 +++++++++- .../store-home-page/store-home-page.component.ts | 9 +++++++++ 6 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index c7551ad..04fd5be 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -681,10 +681,13 @@ describe('StoreLayoutComponent', () => { expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); - it('shows the backend message when starting checkout fails', async () => { - const message = 'Alcanzaste el límite de compra para este producto.'; + 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: { message } }), + new HttpErrorResponse({ + status: 422, + error: { code: 'stock_reservation.expired', message }, + }), ); cartState.set({ id: 1, @@ -702,11 +705,14 @@ describe('StoreLayoutComponent', () => { }); 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', () => { diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index ea5dd24..4bf5c38 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -18,7 +18,10 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface'; import { AuthService } from '../../services/auth/auth.service'; import { findMenu } from '../../services/menu.utils'; -import { CheckoutService } from '../../services/checkout.service'; +import { + CheckoutService, + isExpiredStockReservationResponse, +} from '../../services/checkout.service'; import { ToastService } from '../../services/toast.service'; import { Category } from '../../services/tenant.interface'; @@ -285,6 +288,11 @@ export class StoreLayoutComponent implements OnInit { : '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 { this.isCreatingPurchase.set(false); } diff --git a/src/app/core/services/checkout.service.ts b/src/app/core/services/checkout.service.ts index df1a4e2..1952549 100644 --- a/src/app/core/services/checkout.service.ts +++ b/src/app/core/services/checkout.service.ts @@ -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).code === 'stock_reservation.expired' + ); +} + export type StartCheckoutPayload = | { cart_id: number; diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index cf8d447..e020300 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -23,7 +23,10 @@ import { import { AuthService } from '../../../../core/services/auth/auth.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 { CatalogGroupLayout, CategoryItemsResponse, @@ -176,6 +179,11 @@ export class CategoryItemsPageComponent { : '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 { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index 729e387..ba3bc45 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -24,7 +24,10 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CartService } from '../../../../core/services/cart/cart.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 { CatalogFeaturedItem, CatalogFeaturedItems, @@ -208,6 +211,11 @@ export class SearchPageComponent { : '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 { this.creatingDirectPurchase.set(false); } diff --git a/src/app/features/store/pages/store-home-page/store-home-page.component.ts b/src/app/features/store/pages/store-home-page/store-home-page.component.ts index e9fa018..12b8605 100644 --- a/src/app/features/store/pages/store-home-page/store-home-page.component.ts +++ b/src/app/features/store/pages/store-home-page/store-home-page.component.ts @@ -21,6 +21,7 @@ import { TenantService } from '../../../../core/services/tenant.service'; import { ToastService } from '../../../../core/services/toast.service'; import { CheckoutService, + isExpiredStockReservationResponse, isInsufficientStockResponse, } from '../../../../core/services/checkout.service'; import { @@ -221,6 +222,14 @@ export class StoreHomePageComponent implements OnInit, OnDestroy { } catch (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)) { const unavailableIds = error.error.unavailable_items .map((item) => item.variant_id) From 643d43adea752f639bac9b85a7c0713d717c6b1a Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 17:05:59 -0300 Subject: [PATCH 10/12] fix(checkout): handle expired purchase exits --- .../checkout-page.component.spec.ts | 56 ++++++++++-- .../checkout-page/checkout-page.component.ts | 85 +++++++++++++++++-- .../purchase-status-page.component.spec.ts | 19 ++++- .../purchase-status-page.component.ts | 19 ++++- 4 files changed, 166 insertions(+), 13 deletions(-) diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts index 77b29a7..e7e34a2 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts @@ -460,7 +460,7 @@ describe('CheckoutPageComponent payment validation', () => { 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.'; checkoutServiceStub.cancelPurchase.mockRejectedValue({ error: { code: 'purchase.expired', message }, @@ -470,7 +470,9 @@ describe('CheckoutPageComponent payment validation', () => { await component.onModifyPurchase(); 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.stop).toHaveBeenCalledOnce(); expect(component.isCancellingPurchase()).toBe(false); @@ -587,7 +589,24 @@ describe('CheckoutPageComponent payment validation', () => { 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( new HttpErrorResponse({ status: 422, @@ -604,10 +623,35 @@ describe('CheckoutPageComponent payment validation', () => { expect(toastServiceStub.danger).toHaveBeenCalledWith( '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); }); + 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', () => { const { component } = createComponent(); component.createdPurchase.set({ @@ -635,6 +679,8 @@ describe('CheckoutPageComponent payment validation', () => { expect(toastServiceStub.danger).toHaveBeenCalledWith( 'La compra venci\u00f3. Inici\u00e1 una nueva compra.', ); - expect(routerStub.navigate).toHaveBeenCalledWith(['/']); + expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], { + queryParams: { status: 'expired' }, + }); }); }); diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.ts index e4205dd..faca4cf 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.ts @@ -296,6 +296,18 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { return true; } catch (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.'); return false; } finally { @@ -492,8 +504,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { this.navigateToPurchaseStatus(purchaseId); return; } + + if (purchase.status === 'expired') { + this.navigateToPurchaseStatus(purchaseId); + return; + } } catch (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) { @@ -575,8 +596,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { this.qrPaymentStatus.set('failed'); return; } + + if (purchase.status === 'expired') { + this.navigateToPurchaseStatus(purchaseId); + return; + } } catch (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 { if (runId === this.qrPollingRunId) { this.isCheckingQrPayment.set(false); @@ -683,15 +713,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { } } catch (error) { console.error('Failed to load purchase:', error); - this.showRequestError(error, 'No se pudo cargar la compra.'); - void this.router.navigate(['/']); + const expired = this.showRequestError(error, 'No se pudo cargar la compra.'); + if (!expired) { + void this.router.navigate(['/']); + } } } - private showRequestError(error: unknown, fallbackMessage: string): void { + private showRequestError(error: unknown, fallbackMessage: string): boolean { const payload = typeof error === 'object' && error !== null && 'error' in error - ? (error as { error?: { message?: unknown } }).error + ? (error as { error?: ApiErrorResponse }).error : undefined; const message = typeof payload?.message === 'string' && payload.message.trim() @@ -699,6 +731,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { : fallbackMessage; this.toastService.danger(message); + + if (payload?.code === 'purchase.expired') { + this.navigateToExpiredPurchaseStatus(); + return true; + } + + return false; } private handleCheckoutError(error: unknown, fallbackMessage: string): boolean { @@ -717,7 +756,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { ? response.message : 'La compra venció. Iniciá una nueva compra.', ); - void this.router.navigate(['/']); + this.navigateToExpiredPurchaseStatus(); return true; } @@ -729,6 +768,42 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { 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 { const purchase = this.createdPurchase(); diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts index a41a839..7cd36b6 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts @@ -66,7 +66,7 @@ describe('PurchaseStatusPageComponent', () => { TestBed.resetTestingModule(); }); - async function render(hasGeneratedTickets: boolean) { + async function render(hasGeneratedTickets: boolean, forcedStatus?: string) { const checkoutService = { getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)), withCustomLoading() { @@ -85,7 +85,14 @@ describe('PurchaseStatusPageComponent', () => { { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, - useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } }, + useValue: { + snapshot: { + paramMap: convertToParamMap({ id: '42' }), + queryParamMap: convertToParamMap( + forcedStatus ? { status: forcedStatus } : {}, + ), + }, + }, }, { provide: Router, useValue: router }, ], @@ -134,6 +141,14 @@ describe('PurchaseStatusPageComponent', () => { 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 () => { vi.useFakeTimers(); diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts index 2797027..216fd9e 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts @@ -72,6 +72,12 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { this.purchaseId = purchaseId; this.tenantCode = tenant.codigo; + if (this.route.snapshot.queryParamMap?.get('status') === 'expired') { + this.status.set('expired'); + this.isLoading.set(false); + return; + } + void this.loadStatus(); } @@ -107,7 +113,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { console.error('Failed to fetch purchase status:', error); if (!this.isDestroyed) { - if (isPolling) { + if (this.isPurchaseExpiredError(error)) { + this.status.set('expired'); + this.stopPolling(); + } else if (isPolling) { this.schedulePolling(); } else { this.status.set('error'); @@ -154,6 +163,14 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { 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 { const route = this.ticketsRoute(); From e171b9a233c32e0d32a63a24f2748bd5be625443 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 25 Aug 2026 17:06:07 -0300 Subject: [PATCH 11/12] refactor(checkout): use purchase id route segment --- src/app/app.routes.spec.ts | 46 ++++++++++++++++--- src/app/core/guards/menu.guard.spec.ts | 2 +- .../store-layout.component.spec.ts | 8 ++-- .../store-layout/store-layout.component.ts | 4 +- .../core/services/auth/auth.guards.spec.ts | 6 +-- .../category-items-page.component.ts | 2 +- .../checkout-page.component.spec.ts | 21 +++++---- .../checkout-page/checkout-page.component.ts | 2 +- .../product-detail-page.component.spec.ts | 4 +- .../product-detail-page.component.ts | 4 +- .../search-page/search-page.component.ts | 2 +- .../store-home-page.component.ts | 2 +- src/app/features/store/store.routes.ts | 18 ++++---- 13 files changed, 74 insertions(+), 47 deletions(-) diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index 55f51b7..33e9f1b 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -7,6 +7,7 @@ import { of } from 'rxjs'; import { App } from './app'; import { AuthService } from './core/services/auth/auth.service'; import { CartService } from './core/services/cart/cart.service'; +import { CheckoutService } from './core/services/checkout.service'; import { Tenant } from './core/services/tenant.interface'; import { TenantService } from './core/services/tenant.service'; import { routes } from './app.routes'; @@ -97,6 +98,21 @@ async function renderAppAt( { provide: 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(); @@ -246,15 +262,33 @@ describe('app routes', () => { expect(compiled.textContent).toContain('No encontramos una tienda para este dominio'); }); - it('redirects unauthenticated users from /checkout to /login', async () => { - const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false)); + it('redirects unauthenticated users from /checkout/:id to /login', async () => { + 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 () => { - const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true)); + it('allows authenticated users to access /checkout/:id', async () => { + 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'); }); }); diff --git a/src/app/core/guards/menu.guard.spec.ts b/src/app/core/guards/menu.guard.spec.ts index e8159e6..3bf9479 100644 --- a/src/app/core/guards/menu.guard.spec.ts +++ b/src/app/core/guards/menu.guard.spec.ts @@ -62,7 +62,7 @@ describe('hasMenuGuard', () => { }); 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(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/'); diff --git a/src/app/core/layout/store-layout/store-layout.component.spec.ts b/src/app/core/layout/store-layout/store-layout.component.spec.ts index 04fd5be..2f6f160 100644 --- a/src/app/core/layout/store-layout/store-layout.component.spec.ts +++ b/src/app/core/layout/store-layout/store-layout.component.spec.ts @@ -247,7 +247,7 @@ describe('StoreLayoutComponent', () => { it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => { tenantState.set({ ...tenant, base_path: 'fiesta' }); 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); fixture.detectChanges(); @@ -588,7 +588,7 @@ describe('StoreLayoutComponent', () => { const authService = TestBed.inject(AuthService); const cartService = TestBed.inject(CartService); 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 fixture = TestBed.createComponent(StoreLayoutComponent); @@ -675,9 +675,7 @@ describe('StoreLayoutComponent', () => { expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', { cart_id: 1, }); - expect(router.navigate).toHaveBeenCalledWith(['/checkout'], { - queryParams: { purchase: 55 }, - }); + expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]); expect((fixture.componentInstance as any).isCartOpen()).toBe(false); }); diff --git a/src/app/core/layout/store-layout/store-layout.component.ts b/src/app/core/layout/store-layout/store-layout.component.ts index 4bf5c38..e812afc 100644 --- a/src/app/core/layout/store-layout/store-layout.component.ts +++ b/src/app/core/layout/store-layout/store-layout.component.ts @@ -277,9 +277,7 @@ export class StoreLayoutComponent implements OnInit { }); this.isCartOpen.set(false); - await this.router.navigate(['/checkout'], { - queryParams: { purchase: purchase.id }, - }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create cart purchase:', error); const message = diff --git a/src/app/core/services/auth/auth.guards.spec.ts b/src/app/core/services/auth/auth.guards.spec.ts index 485a57a..fefb63d 100644 --- a/src/app/core/services/auth/auth.guards.spec.ts +++ b/src/app/core/services/auth/auth.guards.spec.ts @@ -24,12 +24,12 @@ describe('auth guards', () => { }); 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(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(() => - authGuard(null as never, { url: '/checkout' } as never), + authGuard(null as never, { url: '/checkout/25' } as never), ); expect(result).toBe(true); diff --git a/src/app/features/store/pages/category-items-page/category-items-page.component.ts b/src/app/features/store/pages/category-items-page/category-items-page.component.ts index e020300..8150675 100644 --- a/src/app/features/store/pages/category-items-page/category-items-page.component.ts +++ b/src/app/features/store/pages/category-items-page/category-items-page.component.ts @@ -170,7 +170,7 @@ export class CategoryItemsPageComponent { ], }, ); - await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts index e7e34a2..9893f29 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.spec.ts @@ -33,7 +33,7 @@ describe('CheckoutPageComponent payment validation', () => { stop: ReturnType; }; let cartServiceStub: { loadCart: ReturnType }; - let routeQueryParamMap: ReturnType; + let routeParamMap: ReturnType; let authUserState: ReturnType; let tenantState: ReturnType< typeof signal<{ @@ -76,7 +76,7 @@ describe('CheckoutPageComponent payment validation', () => { cartServiceStub = { loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })), }; - routeQueryParamMap = convertToParamMap({}); + routeParamMap = convertToParamMap({}); authUserState = signal(null); tenantState = signal({ codigo: 'tenant-test', @@ -103,8 +103,8 @@ describe('CheckoutPageComponent payment validation', () => { provide: ActivatedRoute, useValue: { snapshot: { - get queryParamMap() { - return routeQueryParamMap; + get paramMap() { + return routeParamMap; }, }, }, @@ -317,7 +317,7 @@ describe('CheckoutPageComponent payment validation', () => { subtotal: '2501.00', total: '2501.00', }; - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue(purchase); authUserState.set({ id: 7, @@ -354,7 +354,7 @@ describe('CheckoutPageComponent payment validation', () => { it('keeps the checkout hidden while the purchase is loading', async () => { let resolvePurchase!: (purchase: any) => void; - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockReturnValue( new Promise((resolve) => { resolvePurchase = resolve; @@ -375,12 +375,13 @@ describe('CheckoutPageComponent payment validation', () => { }); await Promise.resolve(); + expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(component.isLoadingPurchase()).toBe(false); expect(component.checkoutStepIndex()).toBe(0); }); 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({ id: 25, status: 'pending_payment', @@ -400,7 +401,7 @@ describe('CheckoutPageComponent payment validation', () => { }); it('generates a new QR when reopening a pending QR purchase', async () => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status: 'pending_payment', @@ -424,7 +425,7 @@ describe('CheckoutPageComponent payment validation', () => { it.each(['paid', 'cancelled', 'rejected', 'expired'])( 'redirects a %s purchase to its status page', async (status) => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status, @@ -442,7 +443,7 @@ describe('CheckoutPageComponent payment validation', () => { ); it('redirects a submitted pending payment purchase to its status page', async () => { - routeQueryParamMap = convertToParamMap({ purchase: 25 }); + routeParamMap = convertToParamMap({ id: 25 }); checkoutServiceStub.getPurchase.mockResolvedValue({ id: 25, status: 'pending_payment', diff --git a/src/app/features/store/pages/checkout-page/checkout-page.component.ts b/src/app/features/store/pages/checkout-page/checkout-page.component.ts index faca4cf..d15bf71 100644 --- a/src/app/features/store/pages/checkout-page/checkout-page.component.ts +++ b/src/app/features/store/pages/checkout-page/checkout-page.component.ts @@ -161,7 +161,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy { } 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) { void this.router.navigate(['/']); return; diff --git a/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts b/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts index 5e020c8..e1c7350 100644 --- a/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts +++ b/src/app/features/store/pages/product-detail-page/product-detail-page.component.spec.ts @@ -507,9 +507,7 @@ describe('ProductDetailPageComponent', () => { }, ], }); - expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], { - queryParams: { purchase: 44 }, - }); + expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]); }); it('shows the backend purchase-limit message for a direct checkout', async () => { diff --git a/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts b/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts index 0e869a6..9729331 100644 --- a/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts +++ b/src/app/features/store/pages/product-detail-page/product-detail-page.component.ts @@ -358,9 +358,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy { ], }); - await this.router.navigate(['/checkout'], { - queryParams: { purchase: purchase.id }, - }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/search-page/search-page.component.ts b/src/app/features/store/pages/search-page/search-page.component.ts index ba3bc45..ab84859 100644 --- a/src/app/features/store/pages/search-page/search-page.component.ts +++ b/src/app/features/store/pages/search-page/search-page.component.ts @@ -202,7 +202,7 @@ export class SearchPageComponent { ], }, ); - await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } }); + await this.router.navigate(['/checkout', purchase.id]); } catch (error) { console.error('Failed to create direct purchase:', error); const message = diff --git a/src/app/features/store/pages/store-home-page/store-home-page.component.ts b/src/app/features/store/pages/store-home-page/store-home-page.component.ts index 12b8605..bb4a236 100644 --- a/src/app/features/store/pages/store-home-page/store-home-page.component.ts +++ b/src/app/features/store/pages/store-home-page/store-home-page.component.ts @@ -218,7 +218,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy { tenant.codigo, 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) { console.error('Failed to create direct purchase:', error); diff --git a/src/app/features/store/store.routes.ts b/src/app/features/store/store.routes.ts index a78e899..dc5719e 100644 --- a/src/app/features/store/store.routes.ts +++ b/src/app/features/store/store.routes.ts @@ -91,15 +91,6 @@ export const routes: Routes = [ (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', 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', canActivate: [hasMenuGuard('help')], From 8e987d0ce6c024c25059778d20acd36d6d3704cf Mon Sep 17 00:00:00 2001 From: ncoronel Date: Wed, 26 Aug 2026 10:02:26 -0300 Subject: [PATCH 12/12] fix(purchase-status): clear cart on approved purchase --- .../purchase-status-page.component.spec.ts | 16 +++++++++++++++- .../purchase-status-page.component.ts | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts index 7cd36b6..6dcf23c 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.spec.ts @@ -5,6 +5,7 @@ import { CheckoutService, PurchaseDetailResponse, } from '../../../../core/services/checkout.service'; +import { CartService } from '../../../../core/services/cart/cart.service'; import { Tenant } from '../../../../core/services/tenant.interface'; import { TenantService } from '../../../../core/services/tenant.service'; import { PurchaseStatusPageComponent } from './purchase-status-page.component'; @@ -77,11 +78,13 @@ describe('PurchaseStatusPageComponent', () => { navigate: vi.fn().mockResolvedValue(true), navigateByUrl: vi.fn().mockResolvedValue(true), }; + const cartService = { clearCart: vi.fn() }; await TestBed.configureTestingModule({ imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: cartService }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, @@ -107,15 +110,22 @@ describe('PurchaseStatusPageComponent', () => { fixture, element: fixture.nativeElement as HTMLElement, checkoutService, + cartService, 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 () => { const { element, checkoutService, router } = await render(true); expect(checkoutService.getPurchase).toHaveBeenCalledOnce(); - expect(element.textContent).toContain('Ver mis tickets'); + expect(element.textContent).toContain('Mis tickets'); expect(element.textContent).not.toContain('WhatsApp'); element.querySelector('app-button button')?.click(); @@ -162,11 +172,13 @@ describe('PurchaseStatusPageComponent', () => { return this; }, }; + const cartService = { clearCart: vi.fn() }; await TestBed.configureTestingModule({ imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: cartService }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, @@ -189,6 +201,7 @@ describe('PurchaseStatusPageComponent', () => { expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!'); + expect(cartService.clearCart).toHaveBeenCalledOnce(); await vi.advanceTimersByTimeAsync(10_000); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); @@ -212,6 +225,7 @@ describe('PurchaseStatusPageComponent', () => { imports: [PurchaseStatusPageComponent], providers: [ { provide: CheckoutService, useValue: checkoutService }, + { provide: CartService, useValue: { clearCart: vi.fn() } }, { provide: TenantService, useValue: { tenant: () => tenant } }, { provide: ActivatedRoute, diff --git a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts index 216fd9e..f04a492 100644 --- a/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts +++ b/src/app/features/store/pages/purchase-status-page/purchase-status-page.component.ts @@ -15,6 +15,7 @@ import { CheckoutService, PurchaseStatusResponse, } from '../../../../core/services/checkout.service'; +import { CartService } from '../../../../core/services/cart/cart.service'; import { findMenu } from '../../../../core/services/menu.utils'; import { TenantService } from '../../../../core/services/tenant.service'; 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 router = inject(Router); private readonly checkoutService = inject(CheckoutService); + private readonly cartService = inject(CartService); private readonly tenantService = inject(TenantService); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); @@ -104,6 +106,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy { this.status.set(status); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); + if (status === 'approved') { + this.cartService.clearCart(); + } + if (status === 'pending') { this.schedulePolling(); } else {