Compare commits

...

23 Commits

Author SHA1 Message Date
ncoronel 1ec48f7e21 Merge branch 'homo_experimental' into develop 2026-08-28 12:39:01 -03:00
ncoronel 07972760fc Merge branch 'fix/TL-1860' into homo_experimental 2026-08-28 11:28:13 -03:00
ncoronel 848c3b280f fix(product-vertical-with-cart-card): change overflow to visible for improved layout 2026-08-28 11:26:32 -03:00
ncoronel c387a01d62 Merge branch 'fix/TL-1860' into develop 2026-08-28 09:27:59 -03:00
ncoronel 5d9adc0494 Merge branch 'fix/TL-1860' into homo_experimental 2026-08-28 09:27:30 -03:00
ncoronel 593580d648 fix(store-layout): ensure full width and minimum width for layout components 2026-08-28 09:23:27 -03:00
ncoronel eb524c7d99 feat(checkout): show transfer candidate reason after polling 2026-08-27 16:55:21 -03:00
ncoronel 65e8436ae1 refactor(checkout): rename transfer candidate reasons 2026-08-27 16:55:13 -03:00
ncoronel 07500f699d feat(checkout): show candidate DNI distance 2026-08-27 16:04:13 -03:00
ncoronel 4997665da6 feat(checkout): show transfer candidate issue 2026-08-27 15:38:23 -03:00
ncoronel dbfadf417a refactor(checkout): remove unused completion request 2026-08-27 12:11:16 -03:00
ncoronel dddb086cd8 refactor(catalog): remove obsolete products request 2026-08-27 12:11:16 -03:00
ncoronel a825b3693b fix(catalog): refresh after expired cart replacement 2026-08-27 09:54:21 -03:00
ncoronel 679342ec8d fix(checkout): defer catalog refresh for expired reservations 2026-08-27 09:54:15 -03:00
ncoronel a5420e6a42 feat(checkout): refresh catalog availability on checkout failure 2026-08-27 09:50:33 -03:00
ncoronel 91b8788c91 feat(checkout): implement mobile countdown display and logic 2026-08-27 09:20:24 -03:00
ncoronel b6a52ceb8c feat(checkout): enhance countdown synchronization and cleanup logic 2026-08-27 09:03:38 -03:00
ncoronel 51d051733c fix(store-layout): update checkout countdown logic and test description 2026-08-27 08:59:41 -03:00
ncoronel f62cd08807 feat(store-header): display checkout countdown 2026-08-27 08:52:57 -03:00
ncoronel d61b1e4b0a feat(checkout): synchronize purchase countdown 2026-08-27 08:52:42 -03:00
ncoronel 1bffefece3 fix(store-header): adjust category menu structure and set height for categories 2026-08-27 08:46:53 -03:00
ncoronel b0d2cd05bc feat(checkout): add completePurchase method and update PurchaseStatusResponse 2026-08-26 17:00:35 -03:00
ncoronel 591f53c102 Squashed commit of the following:
commit 38d03588b1
Merge: 8e987d0 6f4aa3b
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:25:23 2026 -0300

    Merge branch 'fix/cart-expiration-notification' of https://gitea.quo.ar/tbianchini/shopit-front into fix/cart-expiration-notification

commit 8e987d0ce6
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:02:26 2026 -0300

    fix(purchase-status): clear cart on approved purchase

commit e171b9a233
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:06:07 2026 -0300

    refactor(checkout): use purchase id route segment

commit 643d43adea
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:05:59 2026 -0300

    fix(checkout): handle expired purchase exits

commit d89d01b511
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:47:17 2026 -0300

    fix(checkout): refresh expired carts

commit eeb245209b
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:46:12 2026 -0300

    fix(checkout): show backend start errors

commit 9d3754c2d8
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:33:44 2026 -0300

    fix(cart): refresh state after expiration

commit 6f4aa3b1bd
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 26 10:02:26 2026 -0300

    fix(purchase-status): clear cart on approved purchase

commit 2b342ec235
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:06:07 2026 -0300

    refactor(checkout): use purchase id route segment

commit d06b146104
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 17:05:59 2026 -0300

    fix(checkout): handle expired purchase exits

commit f4e0a9e028
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:47:17 2026 -0300

    fix(checkout): refresh expired carts

commit 8c2b738806
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:46:12 2026 -0300

    fix(checkout): show backend start errors

commit 1362d0c163
Author: ncoronel <ncoronel@quo.ar>
Date:   Tue Aug 25 16:33:44 2026 -0300

    fix(cart): refresh state after expiration
2026-08-26 10:29:23 -03:00
41 changed files with 1131 additions and 147 deletions

View File

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

View File

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

View File

@ -152,9 +152,9 @@
</div> </div>
</div> </div>
@if (displayCategories()) {
<div class="store-layout__categories d-none d-md-block"> <div class="store-layout__categories d-none d-md-block">
<div class="container-xl px-3 px-md-4"> <div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
@if (displayCategories()) {
<div class="store-layout__category-menu"> <div class="store-layout__category-menu">
<button <button
type="button" type="button"
@ -175,7 +175,18 @@
(categorySelect)="onCategorySelect($event)" (categorySelect)="onCategorySelect($event)"
/> />
</div> </div>
</div> }
@if (checkoutRemainingTime(); as remainingTime) {
<div
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
role="timer"
aria-label="Tiempo restante de compra"
>
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
</div> </div>
} }
</div>
</div>
</header> </header>

View File

@ -10,6 +10,26 @@
border-bottom: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color);
} }
.store-layout__categories {
height: 3.5rem;
}
.store-layout__checkout-timer {
color: var(--tenant-primary);
font-weight: 700;
white-space: nowrap;
}
.store-layout__checkout-timer-label {
font-size: 13px;
}
.store-layout__checkout-timer-value {
font-size: 20px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.store-layout__brand-slot { .store-layout__brand-slot {
min-width: 150px; min-width: 150px;
} }

View File

@ -1,4 +1,13 @@
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core'; import {
Component,
computed,
ElementRef,
HostListener,
inject,
input,
output,
signal,
} from '@angular/core';
import { Router, RouterLink } from '@angular/router'; import { Router, RouterLink } from '@angular/router';
import { AuthUser } from '../../../services/auth/auth.interfaces'; import { AuthUser } from '../../../services/auth/auth.interfaces';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component'; import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
@ -40,6 +49,7 @@ export class StoreHeaderComponent {
readonly displaySeachBar = input(true); readonly displaySeachBar = input(true);
readonly displayCart = input(true); readonly displayCart = input(true);
readonly cartDisabled = input(false); readonly cartDisabled = input(false);
readonly checkoutRemainingSeconds = input<number | null>(null);
readonly cartClick = output<void>(); readonly cartClick = output<void>();
readonly ticketsClick = output<void>(); readonly ticketsClick = output<void>();
readonly loginClick = output<void>(); readonly loginClick = output<void>();
@ -53,6 +63,18 @@ export class StoreHeaderComponent {
protected readonly minSearchLength = 3; protected readonly minSearchLength = 3;
protected readonly showSearchError = signal(false); protected readonly showSearchError = signal(false);
protected readonly searchControl = new FormControl('', { nonNullable: true }); protected readonly searchControl = new FormControl('', { nonNullable: true });
protected readonly checkoutRemainingTime = computed(() => {
const remainingSeconds = this.checkoutRemainingSeconds();
if (remainingSeconds === null) {
return null;
}
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
});
protected onCartClick(): void { protected onCartClick(): void {
if (this.cartDisabled()) { if (this.cartDisabled()) {

View File

@ -13,6 +13,7 @@
[displaySeachBar]="tenant()?.display_seach_bar ?? true" [displaySeachBar]="tenant()?.display_seach_bar ?? true"
[displayCart]="displayCart()" [displayCart]="displayCart()"
[cartDisabled]="isCheckoutRoute()" [cartDisabled]="isCheckoutRoute()"
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
(cartClick)="onCartClick()" (cartClick)="onCartClick()"
(ticketsClick)="onTicketsClick()" (ticketsClick)="onTicketsClick()"
(loginClick)="onLoginClick()" (loginClick)="onLoginClick()"

View File

@ -1,5 +1,7 @@
:host { :host {
display: flex; display: flex;
width: 100%;
min-width: 0;
min-height: 100dvh; min-height: 100dvh;
background: #f5f5f5; background: #f5f5f5;
color: #202020; color: #202020;
@ -7,6 +9,8 @@
.store-layout { .store-layout {
position: relative; position: relative;
width: 100%;
min-width: 0;
} }
.store-layout__cart-overlay { .store-layout__cart-overlay {

View File

@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'; import { describe, it, expect, beforeEach, vi } from 'vitest';
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { import {
@ -23,6 +24,7 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
import { StoreLayoutComponent } from './store-layout.component'; import { StoreLayoutComponent } from './store-layout.component';
import { StoreHeaderComponent } from './store-header/store-header.component'; import { StoreHeaderComponent } from './store-header/store-header.component';
import { CheckoutService } from '../../services/checkout.service'; import { CheckoutService } from '../../services/checkout.service';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
import { TenantUrlSerializer } from '../../services/tenant-url.serializer'; import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
const tenant: Tenant = { const tenant: Tenant = {
@ -149,6 +151,7 @@ describe('StoreLayoutComponent', () => {
let tenantState = signal<Tenant | null>(tenant); let tenantState = signal<Tenant | null>(tenant);
let cartState = signal<Cart | null>(null); let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null); let authUserState = signal<AuthUser | null>(null);
let checkoutRemainingSecondsState = signal<number | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> }; let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
let queryParamMapState: BehaviorSubject<ParamMap>; let queryParamMapState: BehaviorSubject<ParamMap>;
@ -156,6 +159,7 @@ describe('StoreLayoutComponent', () => {
tenantState = signal<Tenant | null>(tenant); tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null); cartState = signal<Cart | null>(null);
authUserState = signal<AuthUser | null>(null); authUserState = signal<AuthUser | null>(null);
checkoutRemainingSecondsState = signal<number | null>(null);
queryParamMapState = new BehaviorSubject(convertToParamMap({})); queryParamMapState = new BehaviorSubject(convertToParamMap({}));
const isAuthenticatedState = signal(false); const isAuthenticatedState = signal(false);
checkoutServiceStub = { checkoutServiceStub = {
@ -214,6 +218,12 @@ describe('StoreLayoutComponent', () => {
provide: CheckoutService, provide: CheckoutService,
useValue: checkoutServiceStub, useValue: checkoutServiceStub,
}, },
{
provide: CheckoutCountdownService,
useValue: {
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
},
},
], ],
}).compileComponents(); }).compileComponents();
}); });
@ -246,7 +256,7 @@ describe('StoreLayoutComponent', () => {
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => { it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
tenantState.set({ ...tenant, base_path: 'fiesta' }); tenantState.set({ ...tenant, base_path: 'fiesta' });
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25'); vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
const fixture = TestBed.createComponent(StoreLayoutComponent); const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges(); fixture.detectChanges();
@ -270,6 +280,22 @@ describe('StoreLayoutComponent', () => {
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull(); expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
}); });
it('shows the synchronized countdown in the header whenever one is active', () => {
checkoutRemainingSecondsState.set(587);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
'Tiempo restante de compra:',
);
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
'09:47',
);
});
it('hides the configured header elements when the tenant disables them', () => { it('hides the configured header elements when the tenant disables them', () => {
tenantState.set({ tenantState.set({
...tenant, ...tenant,
@ -587,7 +613,7 @@ describe('StoreLayoutComponent', () => {
const authService = TestBed.inject(AuthService); const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService); const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25'); vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true); const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
const fixture = TestBed.createComponent(StoreLayoutComponent); const fixture = TestBed.createComponent(StoreLayoutComponent);
@ -674,12 +700,44 @@ describe('StoreLayoutComponent', () => {
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', { expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1, cart_id: 1,
}); });
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], { expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
queryParams: { purchase: 55 },
});
expect((fixture.componentInstance as any).isCartOpen()).toBe(false); expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
}); });
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
checkoutServiceStub.startCheckout.mockRejectedValue(
new HttpErrorResponse({
status: 422,
error: { code: 'stock_reservation.expired', message },
}),
);
cartState.set({
id: 1,
tenant_codigo: tenant.codigo,
status: 'active',
subtotal: '100.00',
items: [],
});
authUserState.set({
id: 7,
nombre_apellido: 'Juan Perez',
email: 'juan@example.com',
dni: '12345678',
telefono: '3415555555',
});
const fixture = TestBed.createComponent(StoreLayoutComponent);
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
fixture.detectChanges();
loadCart.mockClear();
await (fixture.componentInstance as any).onCheckoutClick();
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
expect(loadCart).toHaveBeenCalledOnce();
});
it('allows modifying quantities directly in the regular cart without a toggle', () => { it('allows modifying quantities directly in the regular cart without a toggle', () => {
cartState.set({ cartState.set({
id: 1, id: 1,

View File

@ -1,3 +1,4 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core'; import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { import {
@ -17,9 +18,13 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface'; import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
import { AuthService } from '../../services/auth/auth.service'; import { AuthService } from '../../services/auth/auth.service';
import { findMenu } from '../../services/menu.utils'; import { findMenu } from '../../services/menu.utils';
import { CheckoutService } from '../../services/checkout.service'; import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service'; import { ToastService } from '../../services/toast.service';
import { Category } from '../../services/tenant.interface'; import { Category } from '../../services/tenant.interface';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
@Component({ @Component({
selector: 'app-store-layout', selector: 'app-store-layout',
@ -38,6 +43,7 @@ export class StoreLayoutComponent implements OnInit {
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
@ -45,6 +51,7 @@ export class StoreLayoutComponent implements OnInit {
protected readonly isCartOpen = signal(false); protected readonly isCartOpen = signal(false);
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url)); protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
protected readonly isCreatingPurchase = signal(false); protected readonly isCreatingPurchase = signal(false);
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true); protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null); protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
@ -273,12 +280,20 @@ export class StoreLayoutComponent implements OnInit {
}); });
this.isCartOpen.set(false); this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], { await this.router.navigate(['/checkout', purchase.id]);
queryParams: { purchase: purchase.id },
});
} catch (error) { } catch (error) {
console.error('Failed to create cart purchase:', error); console.error('Failed to create cart purchase:', error);
this.toastService.danger('No se pudo iniciar la compra.'); const message =
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
? error.error.message
: 'No se pudo iniciar la compra.';
this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart(true).subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
}
} finally { } finally {
this.isCreatingPurchase.set(false); this.isCreatingPurchase.set(false);
} }

View File

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

View File

@ -83,6 +83,20 @@ describe('CartService', () => {
req.flush({ data: mockCart }); req.flush({ data: mockCart });
}); });
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
const availabilityChanged = vi.fn();
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
service.loadCart(true).subscribe();
expect(availabilityChanged).not.toHaveBeenCalled();
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
req.flush({ data: mockCart });
expect(service.cart()).toEqual(mockCart);
expect(availabilityChanged).toHaveBeenCalledOnce();
});
it('propagates a custom loading mode to the request context', () => { it('propagates a custom loading mode to the request context', () => {
service.withCustomLoading().loadCart().subscribe(); service.withCustomLoading().loadCart().subscribe();

View File

@ -34,14 +34,19 @@ export class CartService extends BaseApiService {
}); });
} }
loadCart(): Observable<Cart> { loadCart(refreshCatalogAvailability = false): Observable<Cart> {
return this.http return this.http
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, { .get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
withCredentials: true, withCredentials: true,
}) })
.pipe( .pipe(
map((response) => response.data), map((response) => response.data),
tap((cart) => this.cartState.set(cart)), tap((cart) => {
this.cartState.set(cart);
if (refreshCatalogAvailability) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
}),
); );
} }

View File

@ -14,7 +14,6 @@ import {
CatalogItemDetail, CatalogItemDetail,
CatalogVariantOptionsResponse, CatalogVariantOptionsResponse,
CategoryItemsResponse, CategoryItemsResponse,
Product,
} from './catalog.interface'; } from './catalog.interface';
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[]; type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
@ -33,12 +32,6 @@ export class CatalogService extends BaseApiService {
return this.tenantService.getTenantApiUrl(); return this.tenantService.getTenantApiUrl();
} }
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
params: this.buildHttpParams(params),
});
}
getCatalog(): Observable<CatalogFeaturedGroup[]> { getCatalog(): Observable<CatalogFeaturedGroup[]> {
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`); return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
} }

View File

@ -0,0 +1,69 @@
import { TestBed } from '@angular/core/testing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CheckoutCountdownService } from './checkout-countdown.service';
describe('CheckoutCountdownService', () => {
let service: CheckoutCountdownService;
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
service = TestBed.inject(CheckoutCountdownService);
});
afterEach(() => {
service.clear();
vi.useRealTimers();
});
it('counts down from the checkout server timing without depending on the client clock', () => {
service.synchronize({
expires_at: '2026-08-27T15:10:00.000Z',
expires_in_seconds: 600,
server_time: '2026-08-27T15:00:00.000Z',
});
expect(service.remainingSeconds()).toBe(600);
vi.advanceTimersByTime(1_000);
expect(service.remainingSeconds()).toBe(599);
});
it('recalculates against the deadline after a delayed browser interval', () => {
service.synchronize({
expires_at: null,
expires_in_seconds: 10,
server_time: '2026-08-27T15:00:00.000Z',
});
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
vi.advanceTimersByTime(1_000);
expect(service.remainingSeconds()).toBe(2);
});
it('clears the countdown when checkout has no expiration', () => {
service.synchronize({
expires_at: null,
expires_in_seconds: null,
server_time: '2026-08-27T15:00:00.000Z',
});
expect(service.remainingSeconds()).toBeNull();
});
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
service.synchronize({
expires_at: null,
expires_in_seconds: 10,
server_time: '2026-08-27T15:00:00.000Z',
});
service.synchronize({});
expect(service.remainingSeconds()).toBe(10);
});
});

View File

@ -0,0 +1,97 @@
import { Injectable, OnDestroy, signal } from '@angular/core';
export interface CheckoutTiming {
expires_at: string | null;
expires_in_seconds: number | null;
server_time: string;
}
@Injectable({
providedIn: 'root',
})
export class CheckoutCountdownService implements OnDestroy {
private readonly remainingSecondsState = signal<number | null>(null);
private deadlineMs: number | null = null;
private intervalId: ReturnType<typeof setInterval> | null = null;
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
synchronize(timing: Partial<CheckoutTiming>): void {
const remainingSeconds = this.resolveRemainingSeconds(timing);
if (remainingSeconds === undefined) {
return;
}
if (remainingSeconds === null) {
this.clear();
return;
}
this.stopInterval();
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
this.updateRemainingSeconds();
if (remainingSeconds > 0) {
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
}
}
clear(): void {
this.stopInterval();
this.deadlineMs = null;
this.remainingSecondsState.set(null);
}
ngOnDestroy(): void {
this.clear();
}
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
if (timing.expires_at === null && timing.expires_in_seconds === null) {
return null;
}
const expiresAt =
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
const serverTime =
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
}
if (
typeof timing.expires_in_seconds === 'number' &&
Number.isFinite(timing.expires_in_seconds)
) {
return Math.max(0, Math.ceil(timing.expires_in_seconds));
}
if (Number.isFinite(expiresAt)) {
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
}
return undefined;
}
private updateRemainingSeconds(): void {
if (this.deadlineMs === null) {
return;
}
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
this.remainingSecondsState.set(remainingSeconds);
if (remainingSeconds === 0) {
this.stopInterval();
}
}
private stopInterval(): void {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
}

View File

@ -1,9 +1,10 @@
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { environment } from '../../../environments/environment'; import { environment } from '../../../environments/environment';
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
import { CheckoutService } from './checkout.service'; import { CheckoutService } from './checkout.service';
describe('CheckoutService', () => { describe('CheckoutService', () => {
@ -38,4 +39,59 @@ describe('CheckoutService', () => {
await expect(purchasePromise).resolves.toMatchObject({ id: 55 }); await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
}); });
it('refreshes catalog availability when starting checkout fails', async () => {
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
const notifyAvailabilityChanged = vi.spyOn(
catalogAvailabilityService,
'notifyAvailabilityChanged',
);
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
request.flush(
{ message: 'No hay stock disponible.' },
{ status: 422, statusText: 'Unprocessable Entity' },
);
await expect(purchasePromise).rejects.toBeTruthy();
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
});
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
const notifyAvailabilityChanged = vi.spyOn(
catalogAvailabilityService,
'notifyAvailabilityChanged',
);
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
request.flush(
{
code: 'stock_reservation.expired',
message: 'La reserva de stock venció.',
},
{ status: 422, statusText: 'Unprocessable Entity' },
);
await expect(purchasePromise).rejects.toBeTruthy();
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
});
it('preserves checkout timing fields when completing a purchase', async () => {
const purchasePromise = service.completePurchase('desfile', 55);
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
const response = {
status: 'pending_payment',
expires_at: '2026-08-26T20:00:00.000Z',
expires_in_seconds: 900,
server_time: '2026-08-26T19:45:00.000Z',
};
expect(request.request.method).toBe('POST');
request.flush({ data: response });
await expect(purchasePromise).resolves.toEqual(response);
});
}); });

View File

@ -1,10 +1,11 @@
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { environment } from '../../../environments/environment'; import { environment } from '../../../environments/environment';
import { ApiPaginatedResponse } from './api-paginated-response.interface'; import { ApiPaginatedResponse } from './api-paginated-response.interface';
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface'; import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
import { BaseApiService } from './base-api.service'; import { BaseApiService } from './base-api.service';
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
export interface UpdatePurchaseCustomerPayload { export interface UpdatePurchaseCustomerPayload {
dni: string; dni: string;
@ -45,6 +46,21 @@ export function isInsufficientStockResponse(value: unknown): value is Insufficie
); );
} }
export interface ExpiredStockReservationResponse {
code: 'stock_reservation.expired';
message: string;
}
export function isExpiredStockReservationResponse(
value: unknown,
): value is ExpiredStockReservationResponse {
return (
typeof value === 'object' &&
value !== null &&
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
);
}
export type StartCheckoutPayload = export type StartCheckoutPayload =
| { | {
cart_id: number; cart_id: number;
@ -55,6 +71,32 @@ export type StartCheckoutPayload =
export interface PurchaseStatusResponse { export interface PurchaseStatusResponse {
status: string | null; status: string | null;
expires_at: string | null;
expires_in_seconds: number | null;
server_time: string;
payment_verification?: PurchasePaymentVerificationResponse;
}
export type PurchasePaymentCandidateReason =
| 'ambiguous_exact_match'
| 'exact_dni_near_amount'
| 'exact_amount_near_dni';
export interface PurchasePaymentCandidatePrimaryResponse {
reason: PurchasePaymentCandidateReason;
dni_distance: number | null;
payment_amount: string;
purchase_amount: string;
amount_difference: string;
confidence: 'exact' | 'high' | 'medium';
detected_at: string | null;
}
export interface PurchasePaymentVerificationResponse {
status: 'pending' | 'candidate';
candidate_count: number;
primary: PurchasePaymentCandidatePrimaryResponse | null;
reasons: PurchasePaymentCandidateReason[];
} }
export interface PurchaseSummaryResponse extends PurchaseStatusResponse { export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
@ -91,7 +133,6 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
user_id: number; user_id: number;
created_at: string | null; created_at: string | null;
payment_method: string | null; payment_method: string | null;
expires_at: string | null;
dni: string | null; dni: string | null;
transfer_payer_dni: string | null; transfer_payer_dni: string | null;
telefono: string | null; telefono: string | null;
@ -109,10 +150,13 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
providedIn: 'root', providedIn: 'root',
}) })
export class CheckoutService extends BaseApiService { export class CheckoutService extends BaseApiService {
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
async startCheckout( async startCheckout(
tenantCode: string, tenantCode: string,
payload: StartCheckoutPayload, payload: StartCheckoutPayload,
): Promise<PurchaseDetailResponse> { ): Promise<PurchaseDetailResponse> {
try {
const response = await firstValueFrom( const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>( this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`, `${environment.url}tenants/${tenantCode}/compras/start-checkout`,
@ -127,6 +171,13 @@ export class CheckoutService extends BaseApiService {
} }
return purchase; return purchase;
} catch (error) {
const responseBody = (error as { error?: unknown } | null)?.error;
if (!isExpiredStockReservationResponse(responseBody)) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
throw error;
}
} }
async generatePaymentIntent( async generatePaymentIntent(
@ -171,25 +222,6 @@ export class CheckoutService extends BaseApiService {
return purchase; return purchase;
} }
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
{},
),
);
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
if (!purchase) {
throw new Error('Error al finalizar la compra.');
}
return {
status: purchase.status ?? null,
};
}
async submitPurchaseForReview( async submitPurchaseForReview(
tenantCode: string, tenantCode: string,
purchaseId: number, purchaseId: number,
@ -206,7 +238,7 @@ export class CheckoutService extends BaseApiService {
throw new Error('Error al enviar la compra a revisi\u00f3n.'); throw new Error('Error al enviar la compra a revisi\u00f3n.');
} }
return { status: purchase.status ?? null }; return purchase;
} }
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> { async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
@ -222,7 +254,7 @@ export class CheckoutService extends BaseApiService {
throw new Error('Error al cancelar la compra.'); throw new Error('Error al cancelar la compra.');
} }
return { status: purchase.status ?? null }; return purchase;
} }
async getPurchases( async getPurchases(

View File

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

View File

@ -34,6 +34,7 @@
[qrPaymentAmount]="cartTotal()" [qrPaymentAmount]="cartTotal()"
[whatsappUrl]="whatsappUrl()" [whatsappUrl]="whatsappUrl()"
[transferValidationStatus]="transferValidationStatus()" [transferValidationStatus]="transferValidationStatus()"
[transferVerificationErrorTitle]="transferVerificationErrorTitle()"
(paymentMethodChange)="selectPaymentMethod($event)" (paymentMethodChange)="selectPaymentMethod($event)"
(copyTransferValue)="copyTransferValue($event.field, $event.value)" (copyTransferValue)="copyTransferValue($event.field, $event.value)"
(cancelStep)="onCancel()" (cancelStep)="onCancel()"
@ -46,6 +47,17 @@
</div> </div>
<div class="checkout-page__cart-col"> <div class="checkout-page__cart-col">
@if (checkoutRemainingTime(); as remainingTime) {
<div
class="checkout-page__mobile-countdown d-flex d-md-none align-items-baseline justify-content-center gap-3"
role="timer"
aria-label="Tiempo restante de compra"
>
<span class="checkout-page__mobile-countdown-label">Tiempo restante de compra:</span>
<span class="checkout-page__mobile-countdown-value">{{ remainingTime }}</span>
</div>
}
<app-cart <app-cart
title="COMPRA" title="COMPRA"
[items]="mappedCartItems()" [items]="mappedCartItems()"

View File

@ -28,6 +28,24 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
&__mobile-countdown {
flex: 0 0 auto;
margin-bottom: 1.5rem;
color: var(--tenant-primary);
font-weight: 700;
white-space: nowrap;
}
&__mobile-countdown-label {
font-size: 13px;
}
&__mobile-countdown-value {
font-size: 20px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
} }
.checkout-page__loading { .checkout-page__loading {

View File

@ -14,6 +14,7 @@ import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { CartEditingPolicy } from '../../../../core/services/tenant.interface'; import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
import { CheckoutPageComponent } from './checkout-page.component'; import { CheckoutPageComponent } from './checkout-page.component';
describe('CheckoutPageComponent payment validation', () => { describe('CheckoutPageComponent payment validation', () => {
@ -33,7 +34,7 @@ describe('CheckoutPageComponent payment validation', () => {
stop: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn>;
}; };
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> }; let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
let routeQueryParamMap: ReturnType<typeof convertToParamMap>; let routeParamMap: ReturnType<typeof convertToParamMap>;
let authUserState: ReturnType<typeof signal>; let authUserState: ReturnType<typeof signal>;
let tenantState: ReturnType< let tenantState: ReturnType<
typeof signal<{ typeof signal<{
@ -76,7 +77,7 @@ describe('CheckoutPageComponent payment validation', () => {
cartServiceStub = { cartServiceStub = {
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })), loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
}; };
routeQueryParamMap = convertToParamMap({}); routeParamMap = convertToParamMap({});
authUserState = signal(null); authUserState = signal(null);
tenantState = signal({ tenantState = signal({
codigo: 'tenant-test', codigo: 'tenant-test',
@ -103,8 +104,8 @@ describe('CheckoutPageComponent payment validation', () => {
provide: ActivatedRoute, provide: ActivatedRoute,
useValue: { useValue: {
snapshot: { snapshot: {
get queryParamMap() { get paramMap() {
return routeQueryParamMap; return routeParamMap;
}, },
}, },
}, },
@ -129,6 +130,35 @@ describe('CheckoutPageComponent payment validation', () => {
return { fixture, component: fixture.componentInstance as any }; return { fixture, component: fixture.componentInstance as any };
} }
it('does not expose an active countdown until the purchase timing is loaded', async () => {
const countdown = TestBed.inject(CheckoutCountdownService);
countdown.synchronize({
expires_at: null,
expires_in_seconds: 600,
server_time: new Date().toISOString(),
});
checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25,
status: 'created',
expires_at: '2026-08-27T15:10:00.000Z',
expires_in_seconds: 600,
server_time: '2026-08-27T15:00:00.000Z',
items: [],
subtotal: '0.00',
total: '0.00',
});
routeParamMap = convertToParamMap({ id: 25 });
const { component } = createComponent();
expect(component.checkoutRemainingTime()).toBeNull();
await Promise.resolve();
expect(countdown.remainingSeconds()).toBe(600);
expect(component.checkoutRemainingTime()).toBe('10:00');
});
it('polls QR after five seconds and navigates only when payment is paid', async () => { it('polls QR after five seconds and navigates only when payment is paid', async () => {
checkoutServiceStub.getPurchase checkoutServiceStub.getPurchase
.mockResolvedValueOnce({ status: 'pending_payment' }) .mockResolvedValueOnce({ status: 'pending_payment' })
@ -195,7 +225,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
}); });
it('polls a transfer every three seconds up to four attempts', async () => { it('polls a transfer every three seconds for one minute', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' }); checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
const { component } = createComponent(); const { component } = createComponent();
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
@ -205,14 +235,12 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
for (let attempt = 1; attempt <= 3; attempt += 1) { await vi.advanceTimersByTimeAsync(57_000);
await vi.advanceTimersByTimeAsync(3_000); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
expect(component.transferValidationStatus()).toBe('checking'); expect(component.transferValidationStatus()).toBe('checking');
}
await vi.advanceTimersByTimeAsync(3_000); await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25); expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
@ -256,13 +284,43 @@ describe('CheckoutPageComponent payment validation', () => {
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
await component.onComplete(); await component.onComplete();
await vi.advanceTimersByTimeAsync(12_000); await vi.advanceTimersByTimeAsync(60_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
it('uses the primary candidate reason when transfer polling times out', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({
status: 'in_review',
payment_verification: {
status: 'candidate',
candidate_count: 1,
primary: {
reason: 'exact_amount_near_dni',
dni_distance: 1,
payment_amount: '300000.00',
purchase_amount: '300000.00',
amount_difference: '0.00',
confidence: 'medium',
detected_at: '2026-08-27T18:00:00-03:00',
},
reasons: ['exact_amount_near_dni'],
},
});
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
await vi.advanceTimersByTimeAsync(60_000);
expect(component.transferValidationStatus()).toBe('error');
expect(component.transferVerificationErrorTitle()).toBe(
'El DNI no corresponde con el de la transferencia',
);
});
it('does not poll when submitting a transfer for review fails', async () => { it('does not poll when submitting a transfer for review fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined); vi.spyOn(console, 'error').mockImplementation(() => undefined);
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error')); checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
@ -317,7 +375,7 @@ describe('CheckoutPageComponent payment validation', () => {
subtotal: '2501.00', subtotal: '2501.00',
total: '2501.00', total: '2501.00',
}; };
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue(purchase); checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
authUserState.set({ authUserState.set({
id: 7, id: 7,
@ -354,7 +412,7 @@ describe('CheckoutPageComponent payment validation', () => {
it('keeps the checkout hidden while the purchase is loading', async () => { it('keeps the checkout hidden while the purchase is loading', async () => {
let resolvePurchase!: (purchase: any) => void; let resolvePurchase!: (purchase: any) => void;
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockReturnValue( checkoutServiceStub.getPurchase.mockReturnValue(
new Promise((resolve) => { new Promise((resolve) => {
resolvePurchase = resolve; resolvePurchase = resolve;
@ -375,12 +433,13 @@ describe('CheckoutPageComponent payment validation', () => {
}); });
await Promise.resolve(); await Promise.resolve();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(component.isLoadingPurchase()).toBe(false); expect(component.isLoadingPurchase()).toBe(false);
expect(component.checkoutStepIndex()).toBe(0); expect(component.checkoutStepIndex()).toBe(0);
}); });
it('opens a pending purchase on the payment step and restores its payment method', async () => { it('opens a pending purchase on the payment step and restores its payment method', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@ -400,7 +459,7 @@ describe('CheckoutPageComponent payment validation', () => {
}); });
it('generates a new QR when reopening a pending QR purchase', async () => { it('generates a new QR when reopening a pending QR purchase', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@ -424,7 +483,7 @@ describe('CheckoutPageComponent payment validation', () => {
it.each(['paid', 'cancelled', 'rejected', 'expired'])( it.each(['paid', 'cancelled', 'rejected', 'expired'])(
'redirects a %s purchase to its status page', 'redirects a %s purchase to its status page',
async (status) => { async (status) => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status, status,
@ -442,7 +501,7 @@ describe('CheckoutPageComponent payment validation', () => {
); );
it('redirects a submitted pending payment purchase to its status page', async () => { it('redirects a submitted pending payment purchase to its status page', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeParamMap = convertToParamMap({ id: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({ checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25, id: 25,
status: 'pending_payment', status: 'pending_payment',
@ -460,7 +519,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
it('shows the API error in a toast when cancelling the purchase fails', async () => { it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
const message = 'La compra venció. Iniciá una nueva compra.'; const message = 'La compra venció. Iniciá una nueva compra.';
checkoutServiceStub.cancelPurchase.mockRejectedValue({ checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { code: 'purchase.expired', message }, error: { code: 'purchase.expired', message },
@ -470,7 +529,9 @@ describe('CheckoutPageComponent payment validation', () => {
await component.onModifyPurchase(); await component.onModifyPurchase();
expect(toastServiceStub.danger).toHaveBeenCalledWith(message); expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
expect(component.isCancellingPurchase()).toBe(false); expect(component.isCancellingPurchase()).toBe(false);
@ -587,7 +648,24 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.createdPurchaseId()).toBe(25); expect(component.createdPurchaseId()).toBe(25);
}); });
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => { it('allows leaving checkout when cancellation finds an expired stock reservation', async () => {
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { code: 'stock_reservation.expired', message },
});
const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true);
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(component.createdPurchaseId()).toBeNull();
expect(component.createdPurchase()).toBeNull();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
});
it('shows the API message and redirects to status when a checkout operation finds an expired purchase', async () => {
checkoutServiceStub.generatePaymentIntent.mockRejectedValue( checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
new HttpErrorResponse({ new HttpErrorResponse({
status: 422, status: 422,
@ -604,10 +682,35 @@ describe('CheckoutPageComponent payment validation', () => {
expect(toastServiceStub.danger).toHaveBeenCalledWith( expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.', 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
); );
expect(routerStub.navigate).toHaveBeenCalledWith(['/']); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(component.isGeneratingIntent()).toBe(false); expect(component.isGeneratingIntent()).toBe(false);
}); });
it('redirects to status when QR polling receives a purchase-expired response', async () => {
checkoutServiceStub.getPurchase.mockRejectedValue(
new HttpErrorResponse({
status: 422,
error: {
code: 'purchase.expired',
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
},
}),
);
const { component } = createComponent();
await component.selectPaymentMethod('qr');
await vi.advanceTimersByTimeAsync(5_000);
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
);
});
it('treats a generic customer-data error as expired when the local deadline passed', () => { it('treats a generic customer-data error as expired when the local deadline passed', () => {
const { component } = createComponent(); const { component } = createComponent();
component.createdPurchase.set({ component.createdPurchase.set({
@ -635,6 +738,8 @@ describe('CheckoutPageComponent payment validation', () => {
expect(toastServiceStub.danger).toHaveBeenCalledWith( expect(toastServiceStub.danger).toHaveBeenCalledWith(
'La compra venci\u00f3. Inici\u00e1 una nueva compra.', 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
); );
expect(routerStub.navigate).toHaveBeenCalledWith(['/']); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
queryParams: { status: 'expired' },
});
}); });
}); });

View File

@ -16,8 +16,10 @@ import { firstValueFrom, startWith } from 'rxjs';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { import {
CheckoutService, CheckoutService,
PurchasePaymentCandidateReason,
PurchaseDetailItemResponse, PurchaseDetailItemResponse,
PurchaseDetailResponse, PurchaseDetailResponse,
PurchaseStatusResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service'; import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
@ -28,6 +30,7 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component'; import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { CheckoutDataStepComponent } from './checkout-data-step.component'; import { CheckoutDataStepComponent } from './checkout-data-step.component';
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component'; import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
import { import {
CheckoutForm, CheckoutForm,
PaymentMethod, PaymentMethod,
@ -64,6 +67,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly globalLoadingService = inject(GlobalLoadingService); private readonly globalLoadingService = inject(GlobalLoadingService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
@ -71,7 +75,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 120; private readonly qrPollingMaxAttempts = 120;
private readonly transferPollingIntervalMs = 3_000; private readonly transferPollingIntervalMs = 3_000;
private readonly transferPollingMaxAttempts = 209; private readonly transferPollingMaxAttempts = 20;
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null; private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private qrPollingAttempts = 0; private qrPollingAttempts = 0;
@ -95,6 +99,27 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null); protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly isLoadingPurchase = signal(true); protected readonly isLoadingPurchase = signal(true);
protected readonly checkoutStepIndex = signal(0); protected readonly checkoutStepIndex = signal(0);
protected readonly checkoutRemainingTime = computed(() => {
const purchase = this.createdPurchase();
if (
!purchase ||
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
) {
return null;
}
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
if (remainingSeconds === null) {
return null;
}
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
});
protected readonly cartSubtotal = computed(() => { protected readonly cartSubtotal = computed(() => {
const purchase = this.createdPurchase(); const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.subtotal) : 0; return purchase ? parseFloat(purchase.subtotal) : 0;
@ -135,6 +160,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle'); protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
protected readonly isCheckingQrPayment = signal(false); protected readonly isCheckingQrPayment = signal(false);
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle'); protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
private readonly transferPrimaryCandidateReason = signal<PurchasePaymentCandidateReason | null>(
null,
);
protected readonly transferVerificationErrorTitle = computed(() =>
this.transferPrimaryCandidateReason() === 'exact_amount_near_dni'
? 'El DNI no corresponde con el de la transferencia'
: null,
);
protected readonly whatsappUrl = computed( protected readonly whatsappUrl = computed(
() => () =>
this.tenantService this.tenantService
@ -161,7 +194,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase')); const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) { if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']); void this.router.navigate(['/']);
return; return;
@ -228,6 +261,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
nombre_apellido: formValue.nombre, nombre_apellido: formValue.nombre,
}); });
this.createdPurchase.set(purchase); this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.stepper.next(); this.stepper.next();
@ -281,6 +315,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
const tenant = this.tenantService.tenant(); const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId(); const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) { if (!tenant || !purchaseId) {
this.checkoutCountdownService.clear();
return true; return true;
} }
@ -291,11 +326,25 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
await firstValueFrom(this.cartService.loadCart()); await firstValueFrom(this.cartService.loadCart());
this.createdPurchaseId.set(null); this.createdPurchaseId.set(null);
this.createdPurchase.set(null); this.createdPurchase.set(null);
this.checkoutCountdownService.clear();
this.navigationStarted = true; this.navigationStarted = true;
return true; return true;
} catch (error) { } catch (error) {
console.error('Failed to cancel the current purchase:', error); console.error('Failed to cancel the current purchase:', error);
if (this.isStockReservationExpiredError(error)) {
this.showRequestError(error, 'La reserva de stock venció.');
this.cartService.loadCart(true).subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
});
this.createdPurchaseId.set(null);
this.createdPurchase.set(null);
this.checkoutCountdownService.clear();
this.navigationStarted = true;
return true;
}
this.showRequestError(error, 'No se pudo cancelar la compra.'); this.showRequestError(error, 'No se pudo cancelar la compra.');
return false; return false;
} finally { } finally {
@ -370,6 +419,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.transferDni.set(dni); this.transferDni.set(dni);
this.stopTransferPolling(); this.stopTransferPolling();
this.transferValidationStatus.set('idle'); this.transferValidationStatus.set('idle');
this.transferPrimaryCandidateReason.set(null);
this.isGeneratingIntent.set(true); this.isGeneratingIntent.set(true);
try { try {
const response = await this.checkoutService const response = await this.checkoutService
@ -426,6 +476,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.stopTransferPolling(); this.stopTransferPolling();
this.hasSubmittedTransfer.set(true); this.hasSubmittedTransfer.set(true);
this.transferValidationStatus.set('checking'); this.transferValidationStatus.set('checking');
this.transferPrimaryCandidateReason.set(null);
this.transferPollingAttempts = 0; this.transferPollingAttempts = 0;
const runId = this.transferPollingRunId; const runId = this.transferPollingRunId;
@ -439,6 +490,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
this.captureTransferCandidateReason(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
@ -488,12 +542,24 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
this.captureTransferCandidateReason(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
} }
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) { } catch (error) {
console.error('Failed to validate transfer payment:', error); console.error('Failed to validate transfer payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
} }
if (runId !== this.transferPollingRunId) { if (runId !== this.transferPollingRunId) {
@ -509,6 +575,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.scheduleTransferPoll(runId); this.scheduleTransferPoll(runId);
} }
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
const reason = purchase.payment_verification?.primary?.reason;
if (reason) {
this.transferPrimaryCandidateReason.set(reason);
}
}
private stopTransferPolling(): void { private stopTransferPolling(): void {
this.transferPollingRunId += 1; this.transferPollingRunId += 1;
@ -565,6 +639,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.handleConfirmedPayment(purchaseId); this.handleConfirmedPayment(purchaseId);
return; return;
@ -575,8 +651,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.qrPaymentStatus.set('failed'); this.qrPaymentStatus.set('failed');
return; return;
} }
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) { } catch (error) {
console.error('Failed to validate QR payment:', error); console.error('Failed to validate QR payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
} finally { } finally {
if (runId === this.qrPollingRunId) { if (runId === this.qrPollingRunId) {
this.isCheckingQrPayment.set(false); this.isCheckingQrPayment.set(false);
@ -629,6 +714,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true; this.navigationStarted = true;
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling(); this.stopTransferPolling();
this.checkoutCountdownService.clear();
void this.router.navigate(['/checkout/status', purchaseId]); void this.router.navigate(['/checkout/status', purchaseId]);
} }
@ -666,6 +752,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.createdPurchaseId.set(purchase.id); this.createdPurchaseId.set(purchase.id);
this.createdPurchase.set(purchase); this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0); this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
if ( if (
@ -683,15 +770,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
console.error('Failed to load purchase:', error); console.error('Failed to load purchase:', error);
this.showRequestError(error, 'No se pudo cargar la compra.'); const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
if (!expired) {
void this.router.navigate(['/']); void this.router.navigate(['/']);
} }
} }
}
private showRequestError(error: unknown, fallbackMessage: string): void { private showRequestError(error: unknown, fallbackMessage: string): boolean {
const payload = const payload =
typeof error === 'object' && error !== null && 'error' in error typeof error === 'object' && error !== null && 'error' in error
? (error as { error?: { message?: unknown } }).error ? (error as { error?: ApiErrorResponse }).error
: undefined; : undefined;
const message = const message =
typeof payload?.message === 'string' && payload.message.trim() typeof payload?.message === 'string' && payload.message.trim()
@ -699,6 +788,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
: fallbackMessage; : fallbackMessage;
this.toastService.danger(message); this.toastService.danger(message);
if (payload?.code === 'purchase.expired') {
this.navigateToExpiredPurchaseStatus();
return true;
}
return false;
} }
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean { private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
@ -717,7 +813,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
? response.message ? response.message
: 'La compra venció. Iniciá una nueva compra.', : 'La compra venció. Iniciá una nueva compra.',
); );
void this.router.navigate(['/']); this.navigateToExpiredPurchaseStatus();
return true; return true;
} }
@ -729,6 +825,43 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return false; return false;
} }
private navigateToExpiredPurchaseStatus(): void {
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
if (purchaseId) {
if (this.navigationStarted) {
return;
}
this.navigationStarted = true;
this.stopQrPolling();
this.stopTransferPolling();
this.checkoutCountdownService.clear();
void this.router.navigate(['/checkout/status', purchaseId], {
queryParams: { status: 'expired' },
});
return;
}
void this.router.navigate(['/']);
}
private isPurchaseExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: ApiErrorResponse }).error?.code === 'purchase.expired';
}
private isStockReservationExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: ApiErrorResponse }).error?.code === 'stock_reservation.expired';
}
private hasExpiredPurchase(): boolean { private hasExpiredPurchase(): boolean {
const purchase = this.createdPurchase(); const purchase = this.createdPurchase();

View File

@ -53,6 +53,7 @@
[validationStatus]="transferValidationStatus()" [validationStatus]="transferValidationStatus()"
[paymentAmount]="qrPaymentAmount()" [paymentAmount]="qrPaymentAmount()"
[whatsappUrl]="whatsappUrl()" [whatsappUrl]="whatsappUrl()"
[verificationErrorTitle]="transferVerificationErrorTitle()"
(copyTransferValue)="requestCopy($event.field, $event.value)" (copyTransferValue)="requestCopy($event.field, $event.value)"
(submitDni)="generateTransferIntent.emit($event)" (submitDni)="generateTransferIntent.emit($event)"
(completePurchase)="complete.emit()" (completePurchase)="complete.emit()"

View File

@ -33,6 +33,7 @@ export class CheckoutPaymentStepComponent {
readonly qrPaymentAmount = input<number>(0); readonly qrPaymentAmount = input<number>(0);
readonly whatsappUrl = input<string | null>(null); readonly whatsappUrl = input<string | null>(null);
readonly transferValidationStatus = input<TransferValidationStatus>('idle'); readonly transferValidationStatus = input<TransferValidationStatus>('idle');
readonly transferVerificationErrorTitle = input<string | null>(null);
readonly paymentMethodChange = output<PaymentMethod>(); readonly paymentMethodChange = output<PaymentMethod>();
readonly copyTransferValue = output<{ field: TransferField; value: string }>(); readonly copyTransferValue = output<{ field: TransferField; value: string }>();

View File

@ -3,6 +3,7 @@
<app-payment-verification-error <app-payment-verification-error
[paymentAmount]="paymentAmount()" [paymentAmount]="paymentAmount()"
[whatsappUrl]="whatsappUrl()" [whatsappUrl]="whatsappUrl()"
[title]="verificationErrorTitle()"
/> />
} @else { } @else {
<div class="dni-form-container"> <div class="dni-form-container">

View File

@ -47,4 +47,23 @@ describe('CheckoutPaymentTransferComponent', () => {
expect(whatsapp).toBeDefined(); expect(whatsapp).toBeDefined();
expect(element.querySelector('.payment-verification')).toBeNull(); expect(element.querySelector('.payment-verification')).toBeNull();
}); });
it('shows a custom validation title for a near DNI candidate', async () => {
await TestBed.configureTestingModule({
imports: [CheckoutPaymentTransferComponent],
}).compileComponents();
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
fixture.componentRef.setInput('validationStatus', 'error');
fixture.componentRef.setInput(
'verificationErrorTitle',
'El DNI no corresponde con el de la transferencia',
);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain(
'El DNI no corresponde con el de la transferencia',
);
expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
});
}); });

View File

@ -41,6 +41,7 @@ export class CheckoutPaymentTransferComponent implements OnInit {
readonly validationStatus = input<TransferValidationStatus>('idle'); readonly validationStatus = input<TransferValidationStatus>('idle');
readonly paymentAmount = input<number>(0); readonly paymentAmount = input<number>(0);
readonly whatsappUrl = input<string | null>(null); readonly whatsappUrl = input<string | null>(null);
readonly verificationErrorTitle = input<string | null>(null);
readonly copyTransferValue = output<{ field: TransferField; value: string }>(); readonly copyTransferValue = output<{ field: TransferField; value: string }>();
readonly submitDni = output<string>(); readonly submitDni = output<string>();

View File

@ -2,7 +2,7 @@
<div class="payment-timeout__icon" aria-hidden="true"> <div class="payment-timeout__icon" aria-hidden="true">
<i class="fa-solid fa-xmark"></i> <i class="fa-solid fa-xmark"></i>
</div> </div>
<h4 class="payment-timeout__title">No pudimos verificar el pago de {{ formattedAmount() }}.</h4> <h4 class="payment-timeout__title">{{ displayTitle() }}</h4>
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p> <p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
@if (whatsappUrl()) { @if (whatsappUrl()) {
<app-button <app-button

View File

@ -13,6 +13,7 @@ import { ButtonComponent } from '../../../../../../shared/components/button/butt
export class PaymentVerificationErrorComponent { export class PaymentVerificationErrorComponent {
readonly paymentAmount = input<number>(0); readonly paymentAmount = input<number>(0);
readonly whatsappUrl = input<string | null>(null); readonly whatsappUrl = input<string | null>(null);
readonly title = input<string | null>(null);
protected readonly formattedAmount = computed(() => protected readonly formattedAmount = computed(() =>
new Intl.NumberFormat('es-AR', { new Intl.NumberFormat('es-AR', {
@ -21,6 +22,9 @@ export class PaymentVerificationErrorComponent {
maximumFractionDigits: 0, maximumFractionDigits: 0,
}).format(this.paymentAmount()), }).format(this.paymentAmount()),
); );
protected readonly displayTitle = computed(
() => this.title() ?? `No pudimos verificar el pago de ${this.formattedAmount()}.`,
);
protected openWhatsApp(): void { protected openWhatsApp(): void {
const url = this.whatsappUrl(); const url = this.whatsappUrl();

View File

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

View File

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

View File

@ -17,7 +17,9 @@
<div class="status-content__section status-content__section--secondary"> <div class="status-content__section status-content__section--secondary">
@if (ticketsRoute()) { @if (ticketsRoute()) {
<p class="status-content__message">A continuación, vas a poder ver los tickets que debés presentar en el evento.</p> <p class="status-content__message">
A continuación, vas a poder ver los tickets que debés presentar en el evento.
</p>
<app-button <app-button
type="button" type="button"
@ -29,7 +31,9 @@
<span>Mis tickets</span> <span>Mis tickets</span>
</app-button> </app-button>
} @else if (whatsappUrl()) { } @else if (whatsappUrl()) {
<p class="status-content__message">Comunicate con nosotros para coordinar el env&iacute;o.</p> <p class="status-content__message">
Comunicate con nosotros para coordinar el env&iacute;o.
</p>
<app-button <app-button
type="button" type="button"
@ -51,13 +55,21 @@
<i class="fa-solid fa-clock"></i> <i class="fa-solid fa-clock"></i>
</div> </div>
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2> <h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
<p class="status-content__subtitle">Tu compra ya fue registrada y estamos esperando la confirmaci&oacute;n del pago.</p> <p class="status-content__subtitle">
Tu compra ya fue registrada y estamos esperando la confirmaci&oacute;n del pago.
</p>
</div> </div>
<hr class="status-content__divider" /> <hr class="status-content__divider" />
<div class="status-content__section status-content__section--secondary"> <div class="status-content__section status-content__section--secondary">
@if (paymentIssueMessage()) {
<p class="status-content__message">
{{ paymentIssueMessage() }} Estamos revisando el pago.
</p>
} @else {
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p> <p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
}
</div> </div>
} @else if (status() === 'expired') { } @else if (status() === 'expired') {
<div class="status-content__section status-content__section--primary"> <div class="status-content__section status-content__section--primary">
@ -65,13 +77,17 @@
<i class="fa-solid fa-clock"></i> <i class="fa-solid fa-clock"></i>
</div> </div>
<h2 class="status-content__title">LA COMPRA VENCI&Oacute;</h2> <h2 class="status-content__title">LA COMPRA VENCI&Oacute;</h2>
<p class="status-content__subtitle">El plazo de pago termin&oacute; y liberamos el stock reservado.</p> <p class="status-content__subtitle">
El plazo de pago termin&oacute; y liberamos el stock reservado.
</p>
</div> </div>
<hr class="status-content__divider" /> <hr class="status-content__divider" />
<div class="status-content__section status-content__section--secondary"> <div class="status-content__section status-content__section--secondary">
<p class="status-content__message">Pod&eacute;s volver a la tienda e iniciar una nueva compra.</p> <p class="status-content__message">
Pod&eacute;s volver a la tienda e iniciar una nueva compra.
</p>
</div> </div>
} @else if (status() === 'rejected') { } @else if (status() === 'rejected') {
<div class="status-content__section status-content__section--primary"> <div class="status-content__section status-content__section--primary">
@ -79,7 +95,9 @@
<i class="fa-solid fa-triangle-exclamation"></i> <i class="fa-solid fa-triangle-exclamation"></i>
</div> </div>
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2> <h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
<p class="status-content__subtitle">Revis&aacute; el medio de pago o comunicate con nosotros para continuar.</p> <p class="status-content__subtitle">
Revis&aacute; el medio de pago o comunicate con nosotros para continuar.
</p>
</div> </div>
<hr class="status-content__divider" /> <hr class="status-content__divider" />
@ -114,7 +132,9 @@
<hr class="status-content__divider" /> <hr class="status-content__divider" />
<div class="status-content__section status-content__section--secondary"> <div class="status-content__section status-content__section--secondary">
<p class="status-content__message">Volv&eacute; a ingresar m&aacute;s tarde. Si el problema sigue, comunicate con nosotros.</p> <p class="status-content__message">
Volv&eacute; a ingresar m&aacute;s tarde. Si el problema sigue, comunicate con nosotros.
</p>
@if (whatsappUrl()) { @if (whatsappUrl()) {
<div class="status-content__actions"> <div class="status-content__actions">

View File

@ -5,6 +5,7 @@ import {
CheckoutService, CheckoutService,
PurchaseDetailResponse, PurchaseDetailResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { Tenant } from '../../../../core/services/tenant.interface'; import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { PurchaseStatusPageComponent } from './purchase-status-page.component'; import { PurchaseStatusPageComponent } from './purchase-status-page.component';
@ -66,9 +67,13 @@ describe('PurchaseStatusPageComponent', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
async function render(hasGeneratedTickets: boolean) { async function render(
hasGeneratedTickets: boolean,
forcedStatus?: string,
purchaseResponse = purchase(hasGeneratedTickets),
) {
const checkoutService = { const checkoutService = {
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)), getPurchase: vi.fn().mockResolvedValue(purchaseResponse),
withCustomLoading() { withCustomLoading() {
return this; return this;
}, },
@ -77,15 +82,22 @@ describe('PurchaseStatusPageComponent', () => {
navigate: vi.fn().mockResolvedValue(true), navigate: vi.fn().mockResolvedValue(true),
navigateByUrl: vi.fn().mockResolvedValue(true), navigateByUrl: vi.fn().mockResolvedValue(true),
}; };
const cartService = { clearCart: vi.fn() };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: cartService },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } }, useValue: {
snapshot: {
paramMap: convertToParamMap({ id: '42' }),
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}),
},
},
}, },
{ provide: Router, useValue: router }, { provide: Router, useValue: router },
], ],
@ -100,15 +112,22 @@ describe('PurchaseStatusPageComponent', () => {
fixture, fixture,
element: fixture.nativeElement as HTMLElement, element: fixture.nativeElement as HTMLElement,
checkoutService, checkoutService,
cartService,
router, router,
}; };
} }
it('clears the cart when the purchase is approved', async () => {
const { cartService } = await render(true);
expect(cartService.clearCart).toHaveBeenCalledOnce();
});
it('shows the tickets action when this purchase generated tickets', async () => { it('shows the tickets action when this purchase generated tickets', async () => {
const { element, checkoutService, router } = await render(true); const { element, checkoutService, router } = await render(true);
expect(checkoutService.getPurchase).toHaveBeenCalledOnce(); expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
expect(element.textContent).toContain('Ver mis tickets'); expect(element.textContent).toContain('Mis tickets');
expect(element.textContent).not.toContain('WhatsApp'); expect(element.textContent).not.toContain('WhatsApp');
element.querySelector<HTMLButtonElement>('app-button button')?.click(); element.querySelector<HTMLButtonElement>('app-button button')?.click();
@ -134,6 +153,38 @@ describe('PurchaseStatusPageComponent', () => {
openSpy.mockRestore(); openSpy.mockRestore();
}); });
it('shows the expired result without polling when checkout redirects after expiration', async () => {
const { element, checkoutService } = await render(false, 'expired');
expect(element.textContent).toContain('LA COMPRA VENCIÓ');
expect(element.textContent).not.toContain('ESTAMOS VERIFICANDO TU PAGO');
expect(checkoutService.getPurchase).not.toHaveBeenCalled();
});
it('shows the primary transfer candidate issue while the purchase is in review', async () => {
const { element } = await render(false, undefined, {
status: 'in_review',
payment_verification: {
status: 'candidate',
candidate_count: 2,
primary: {
reason: 'exact_dni_near_amount',
dni_distance: 0,
payment_amount: '49000.00',
purchase_amount: '50000.00',
amount_difference: '1000.00',
confidence: 'high',
detected_at: '2026-08-27T18:00:00-03:00',
},
reasons: ['exact_dni_near_amount', 'exact_amount_near_dni'],
},
} as PurchaseDetailResponse);
expect(element.textContent).toContain('Encontramos 2 transferencias posibles.');
expect(element.textContent).toMatch(/diferencia de \$\s*1\.000/);
expect(element.textContent).toContain('Estamos revisando el pago.');
});
it('polls every five seconds while the payment is pending and shows the confirmation', async () => { it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
@ -147,11 +198,13 @@ describe('PurchaseStatusPageComponent', () => {
return this; return this;
}, },
}; };
const cartService = { clearCart: vi.fn() };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: cartService },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,
@ -174,6 +227,7 @@ describe('PurchaseStatusPageComponent', () => {
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!'); expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
expect(cartService.clearCart).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(10_000); await vi.advanceTimersByTimeAsync(10_000);
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
@ -197,6 +251,7 @@ describe('PurchaseStatusPageComponent', () => {
imports: [PurchaseStatusPageComponent], imports: [PurchaseStatusPageComponent],
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutService }, { provide: CheckoutService, useValue: checkoutService },
{ provide: CartService, useValue: { clearCart: vi.fn() } },
{ provide: TenantService, useValue: { tenant: () => tenant } }, { provide: TenantService, useValue: { tenant: () => tenant } },
{ {
provide: ActivatedRoute, provide: ActivatedRoute,

View File

@ -13,8 +13,10 @@ import { ActivatedRoute, Router } from '@angular/router';
import { import {
CheckoutService, CheckoutService,
PurchasePaymentVerificationResponse,
PurchaseStatusResponse, PurchaseStatusResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { findMenu } from '../../../../core/services/menu.utils'; import { findMenu } from '../../../../core/services/menu.utils';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component'; import { ButtonComponent } from '../../../../shared/components/button/button.component';
@ -35,6 +37,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly cartService = inject(CartService);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
@ -46,6 +49,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
protected readonly isLoading = signal(true); protected readonly isLoading = signal(true);
protected readonly status = signal<PurchaseStatusView>('pending'); protected readonly status = signal<PurchaseStatusView>('pending');
protected readonly hasGeneratedTickets = signal(false); protected readonly hasGeneratedTickets = signal(false);
protected readonly paymentIssueMessage = signal<string | null>(null);
protected readonly ticketsRoute = computed(() => { protected readonly ticketsRoute = computed(() => {
if (!this.hasGeneratedTickets()) { if (!this.hasGeneratedTickets()) {
return null; return null;
@ -72,6 +76,12 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
this.purchaseId = purchaseId; this.purchaseId = purchaseId;
this.tenantCode = tenant.codigo; this.tenantCode = tenant.codigo;
if (this.route.snapshot.queryParamMap?.get('status') === 'expired') {
this.status.set('expired');
this.isLoading.set(false);
return;
}
void this.loadStatus(); void this.loadStatus();
} }
@ -97,6 +107,11 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
const status = this.resolveStatus(purchase); const status = this.resolveStatus(purchase);
this.status.set(status); this.status.set(status);
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
if (status === 'approved') {
this.cartService.clearCart();
}
if (status === 'pending') { if (status === 'pending') {
this.schedulePolling(); this.schedulePolling();
@ -107,7 +122,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
console.error('Failed to fetch purchase status:', error); console.error('Failed to fetch purchase status:', error);
if (!this.isDestroyed) { if (!this.isDestroyed) {
if (isPolling) { if (this.isPurchaseExpiredError(error)) {
this.status.set('expired');
this.stopPolling();
} else if (isPolling) {
this.schedulePolling(); this.schedulePolling();
} else { } else {
this.status.set('error'); this.status.set('error');
@ -154,6 +172,51 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'pending'; return 'pending';
} }
private resolvePaymentIssueMessage(
verification?: PurchasePaymentVerificationResponse,
): string | null {
const primary = verification?.primary;
if (!primary) {
return null;
}
const primaryMessage = (() => {
switch (primary.reason) {
case 'ambiguous_exact_match':
return 'Encontramos una transferencia que también coincide con otra compra.';
case 'exact_dni_near_amount':
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
case 'exact_amount_near_dni':
return primary.dni_distance === null
? 'El monto coincide, pero el DNI del pagador es diferente.'
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
}
})();
if (verification.candidate_count > 1) {
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
}
return primaryMessage;
}
private formatCurrency(amount: string): string {
return new Intl.NumberFormat('es-AR', {
style: 'currency',
currency: 'ARS',
maximumFractionDigits: 2,
}).format(Number(amount));
}
private isPurchaseExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) {
return false;
}
return (error as { error?: { code?: string } }).error?.code === 'purchase.expired';
}
protected goToTickets(): void { protected goToTickets(): void {
const route = this.ticketsRoute(); const route = this.ticketsRoute();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@
height: 100%; height: 100%;
box-sizing: border-box; box-sizing: border-box;
padding: 30px 20px; padding: 30px 20px;
overflow: hidden; overflow: visible;
background-color: #ffffff; background-color: #ffffff;
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: 7px; border-radius: 7px;

View File

@ -6,6 +6,15 @@
@import '../node_modules/bootstrap/scss/bootstrap'; @import '../node_modules/bootstrap/scss/bootstrap';
html,
body,
app-root {
width: 100%;
min-height: 100%;
margin: 0;
background: #f5f5f5;
}
:root, :root,
app-root { app-root {
--border-color: #dddddd; --border-color: #dddddd;