16 Commits

Author SHA1 Message Date
dbfadf417a refactor(checkout): remove unused completion request 2026-08-27 12:11:16 -03:00
dddb086cd8 refactor(catalog): remove obsolete products request 2026-08-27 12:11:16 -03:00
a825b3693b fix(catalog): refresh after expired cart replacement 2026-08-27 09:54:21 -03:00
679342ec8d fix(checkout): defer catalog refresh for expired reservations 2026-08-27 09:54:15 -03:00
a5420e6a42 feat(checkout): refresh catalog availability on checkout failure 2026-08-27 09:50:33 -03:00
91b8788c91 feat(checkout): implement mobile countdown display and logic 2026-08-27 09:20:24 -03:00
b6a52ceb8c feat(checkout): enhance countdown synchronization and cleanup logic 2026-08-27 09:03:38 -03:00
51d051733c fix(store-layout): update checkout countdown logic and test description 2026-08-27 08:59:41 -03:00
f62cd08807 feat(store-header): display checkout countdown 2026-08-27 08:52:57 -03:00
d61b1e4b0a feat(checkout): synchronize purchase countdown 2026-08-27 08:52:42 -03:00
1bffefece3 fix(store-header): adjust category menu structure and set height for categories 2026-08-27 08:46:53 -03:00
b0d2cd05bc feat(checkout): add completePurchase method and update PurchaseStatusResponse 2026-08-26 17:00:35 -03:00
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
85529f40f2 fix(register-page): implement password visibility toggle for registration fields 2026-08-26 10:02:56 -03:00
4a952af784 fix(favicon): update favicon handling to use a default SVG icon 2026-08-25 11:44:24 -03:00
b1d4c4d13d fix(reset-password): implement password visibility toggle for input fields 2026-08-25 11:26:56 -03:00
61 changed files with 1178 additions and 672 deletions

View File

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

View File

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

View File

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

View File

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

View File

@@ -152,9 +152,9 @@
</div>
</div>
@if (displayCategories()) {
<div class="store-layout__categories d-none d-md-block">
<div class="container-xl px-3 px-md-4">
<div class="store-layout__categories d-none d-md-block">
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
@if (displayCategories()) {
<div class="store-layout__category-menu">
<button
type="button"
@@ -175,7 +175,18 @@
(categorySelect)="onCategorySelect($event)"
/>
</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>
</header>

View File

@@ -10,6 +10,26 @@
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 {
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 { AuthUser } from '../../../services/auth/auth.interfaces';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
@@ -40,6 +49,7 @@ export class StoreHeaderComponent {
readonly displaySeachBar = input(true);
readonly displayCart = input(true);
readonly cartDisabled = input(false);
readonly checkoutRemainingSeconds = input<number | null>(null);
readonly cartClick = output<void>();
readonly ticketsClick = output<void>();
readonly loginClick = output<void>();
@@ -53,6 +63,18 @@ export class StoreHeaderComponent {
protected readonly minSearchLength = 3;
protected readonly showSearchError = signal(false);
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 {
if (this.cartDisabled()) {

View File

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

View File

@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {
@@ -23,6 +24,7 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
import { StoreLayoutComponent } from './store-layout.component';
import { StoreHeaderComponent } from './store-header/store-header.component';
import { CheckoutService } from '../../services/checkout.service';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
const tenant: Tenant = {
@@ -149,6 +151,7 @@ describe('StoreLayoutComponent', () => {
let tenantState = signal<Tenant | null>(tenant);
let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null);
let checkoutRemainingSecondsState = signal<number | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
let queryParamMapState: BehaviorSubject<ParamMap>;
@@ -156,6 +159,7 @@ describe('StoreLayoutComponent', () => {
tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null);
authUserState = signal<AuthUser | null>(null);
checkoutRemainingSecondsState = signal<number | null>(null);
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
const isAuthenticatedState = signal(false);
checkoutServiceStub = {
@@ -214,6 +218,12 @@ describe('StoreLayoutComponent', () => {
provide: CheckoutService,
useValue: checkoutServiceStub,
},
{
provide: CheckoutCountdownService,
useValue: {
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
},
},
],
}).compileComponents();
});
@@ -246,7 +256,7 @@ describe('StoreLayoutComponent', () => {
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
tenantState.set({ ...tenant, base_path: 'fiesta' });
const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25');
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
@@ -270,6 +280,22 @@ describe('StoreLayoutComponent', () => {
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', () => {
tenantState.set({
...tenant,
@@ -587,7 +613,7 @@ describe('StoreLayoutComponent', () => {
const authService = TestBed.inject(AuthService);
const cartService = TestBed.inject(CartService);
const router = TestBed.inject(Router);
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
const fixture = TestBed.createComponent(StoreLayoutComponent);
@@ -674,12 +700,44 @@ describe('StoreLayoutComponent', () => {
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
cart_id: 1,
});
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 55 },
});
expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
});
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', () => {
cartState.set({
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 { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
@@ -17,9 +18,13 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
import { AuthService } from '../../services/auth/auth.service';
import { findMenu } from '../../services/menu.utils';
import { CheckoutService } from '../../services/checkout.service';
import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service';
import { Category } from '../../services/tenant.interface';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
@Component({
selector: 'app-store-layout',
@@ -38,6 +43,7 @@ export class StoreLayoutComponent implements OnInit {
private readonly cartService = inject(CartService);
private readonly authService = inject(AuthService);
private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly toastService = inject(ToastService);
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
@@ -45,6 +51,7 @@ export class StoreLayoutComponent implements OnInit {
protected readonly isCartOpen = signal(false);
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
protected readonly isCreatingPurchase = signal(false);
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
@@ -273,12 +280,20 @@ export class StoreLayoutComponent implements OnInit {
});
this.isCartOpen.set(false);
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
await this.router.navigate(['/checkout', purchase.id]);
} catch (error) {
console.error('Failed to create cart purchase:', error);
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 {
this.isCreatingPurchase.set(false);
}

View File

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

View File

@@ -83,6 +83,20 @@ describe('CartService', () => {
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', () => {
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
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
withCredentials: true,
})
.pipe(
map((response) => response.data),
tap((cart) => this.cartState.set(cart)),
tap((cart) => {
this.cartState.set(cart);
if (refreshCatalogAvailability) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
}),
);
}

View File

@@ -1,59 +0,0 @@
import { describe, expect, it } from 'vitest';
import { CatalogAvailability } from './catalog.interface';
import {
allowsCatalogAction,
combineCatalogAvailability,
createCatalogAvailability,
maximumCatalogQuantity,
} from './catalog-availability';
describe('catalog availability', () => {
it('represents hidden items without irrelevant actions or quantities', () => {
const availability = createCatalogAvailability(0);
expect(availability).toEqual({
state: 'hidden',
reasons: [
{
code: 'out_of_stock',
message: 'Este producto no tiene stock disponible.',
},
],
});
expect(allowsCatalogAction(availability, 'buy_now')).toBe(false);
expect(maximumCatalogQuantity(availability)).toBe(0);
});
it('intersects product and variant actions and quantities', () => {
const product: CatalogAvailability = {
state: 'visible',
maximum_quantity: 3,
allowed_actions: ['select_variant', 'change_quantity'],
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
};
const variant: CatalogAvailability = {
state: 'visible',
maximum_quantity: 2,
allowed_actions: ['change_quantity', 'add_to_cart'],
reasons: [],
};
expect(combineCatalogAvailability(product, variant)).toEqual({
state: 'visible',
maximum_quantity: 2,
allowed_actions: ['change_quantity'],
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
});
});
it('lets a hidden decision win composition', () => {
const availability = combineCatalogAvailability(
createCatalogAvailability(5),
createCatalogAvailability(0),
);
expect(availability.state).toBe('hidden');
expect(allowsCatalogAction(availability, 'add_to_cart')).toBe(false);
});
});

View File

@@ -1,80 +0,0 @@
import { CatalogAction, CatalogAvailability } from './catalog.interface';
const ALL_CATALOG_ACTIONS: CatalogAction[] = [
'select_variant',
'change_quantity',
'add_to_cart',
'buy_now',
];
export const AVAILABLE_CATALOG_AVAILABILITY: CatalogAvailability = {
state: 'visible',
maximum_quantity: null,
allowed_actions: ALL_CATALOG_ACTIONS,
reasons: [],
};
export function createCatalogAvailability(maximumQuantity: number | null): CatalogAvailability {
const unavailable = maximumQuantity === 0;
if (unavailable) {
return {
state: 'hidden',
reasons: [
{
code: 'out_of_stock',
message: 'Este producto no tiene stock disponible.',
},
],
};
}
return {
state: 'visible',
maximum_quantity: maximumQuantity,
allowed_actions: [...ALL_CATALOG_ACTIONS],
reasons: [],
};
}
export function primaryAvailabilityMessage(availability: CatalogAvailability): string | null {
return availability.reasons[0]?.message ?? null;
}
export function allowsCatalogAction(
availability: CatalogAvailability,
action: CatalogAction,
): boolean {
return availability.state === 'visible' && availability.allowed_actions.includes(action);
}
export function maximumCatalogQuantity(availability: CatalogAvailability): number | null {
return availability.state === 'visible' ? availability.maximum_quantity : 0;
}
export function combineCatalogAvailability(
product: CatalogAvailability,
variant?: CatalogAvailability | null,
): CatalogAvailability {
if (!variant) return product;
const reasons = [...product.reasons, ...variant.reasons];
if (product.state === 'hidden' || variant.state === 'hidden') {
return { state: 'hidden', reasons };
}
return {
state: 'visible',
maximum_quantity: minimumNullable(product.maximum_quantity, variant.maximum_quantity),
allowed_actions: product.allowed_actions.filter((action) =>
variant.allowed_actions.includes(action),
),
reasons,
};
}
function minimumNullable(left: number | null, right: number | null): number | null {
if (left === null) return right;
if (right === null) return left;
return Math.min(left, right);
}

View File

@@ -49,25 +49,6 @@ export interface ProductAttribute {
export type InventoryPolicy = 'tracked' | 'unlimited';
export interface CatalogRestriction {
code: 'out_of_stock' | 'user_quota_reached' | string;
message: string;
}
export type CatalogAction = 'select_variant' | 'change_quantity' | 'add_to_cart' | 'buy_now';
export type CatalogAvailability =
| {
state: 'hidden';
reasons: CatalogRestriction[];
}
| {
state: 'visible';
maximum_quantity: number | null;
allowed_actions: CatalogAction[];
reasons: CatalogRestriction[];
};
export interface CatalogVariantOption {
value: string;
label: string;
@@ -85,7 +66,8 @@ export interface CatalogItemVariant {
event_date_id?: number | null;
event_date_ids?: number[];
event_dates?: string[];
availability: CatalogAvailability;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
minimum_use_date?: string | null;
maximum_use_date?: string | null;
effective_minimum_use_date?: string | null;
@@ -117,7 +99,7 @@ export interface CatalogItemDetail {
attributes: ProductAttribute[];
variants: CatalogItemVariant[];
selected_variant?: SelectedCatalogItemVariant;
availability: CatalogAvailability;
maximum_addable_quantity?: number | null;
images?: string[];
}
@@ -132,7 +114,8 @@ export interface CatalogFeaturedItemVariant {
id: number;
descripcion?: string | null;
precio?: string;
availability: CatalogAvailability;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
values: Record<string, CatalogVariantValue>;
}
@@ -164,7 +147,8 @@ export interface CatalogFeaturedItem {
descripcion?: string | null;
precio: number | string;
image?: string | null;
availability: CatalogAvailability;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
variants?: CatalogFeaturedItemVariant[];
}

View File

@@ -14,7 +14,6 @@ import {
CatalogItemDetail,
CatalogVariantOptionsResponse,
CategoryItemsResponse,
Product,
} from './catalog.interface';
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
@@ -33,12 +32,6 @@ export class CatalogService extends BaseApiService {
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[]> {
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 { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/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 { CatalogAvailabilityService } from './catalog/catalog-availability.service';
import { CheckoutService } from './checkout.service';
describe('CheckoutService', () => {
@@ -38,4 +39,59 @@ describe('CheckoutService', () => {
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 { environment } from '../../../environments/environment';
import { ApiPaginatedResponse } from './api-paginated-response.interface';
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
import { BaseApiService } from './base-api.service';
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
export interface UpdatePurchaseCustomerPayload {
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 =
| {
cart_id: number;
@@ -55,6 +71,9 @@ export type StartCheckoutPayload =
export interface PurchaseStatusResponse {
status: string | null;
expires_at: string | null;
expires_in_seconds: number | null;
server_time: string;
}
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
@@ -91,7 +110,6 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
user_id: number;
created_at: string | null;
payment_method: string | null;
expires_at: string | null;
dni: string | null;
transfer_payer_dni: string | null;
telefono: string | null;
@@ -109,24 +127,34 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
providedIn: 'root',
})
export class CheckoutService extends BaseApiService {
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
async startCheckout(
tenantCode: string,
payload: StartCheckoutPayload,
): Promise<PurchaseDetailResponse> {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
payload,
),
);
try {
const response = await firstValueFrom(
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
payload,
),
);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
if (!purchase?.id) {
throw new Error('Error al crear la compra.');
if (!purchase?.id) {
throw new Error('Error al crear la compra.');
}
return purchase;
} catch (error) {
const responseBody = (error as { error?: unknown } | null)?.error;
if (!isExpiredStockReservationResponse(responseBody)) {
this.catalogAvailabilityService.notifyAvailabilityChanged();
}
throw error;
}
return purchase;
}
async generatePaymentIntent(
@@ -171,25 +199,6 @@ export class CheckoutService extends BaseApiService {
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(
tenantCode: string,
purchaseId: number,
@@ -206,7 +215,7 @@ export class CheckoutService extends BaseApiService {
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> {
@@ -222,7 +231,7 @@ export class CheckoutService extends BaseApiService {
throw new Error('Error al cancelar la compra.');
}
return { status: purchase.status ?? null };
return purchase;
}
async getPurchases(

View File

@@ -13,7 +13,6 @@ import { StoreSectionComponent } from '../../../../shared/components/store-secti
import { ModalService } from '../../../../core/services/modal.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { StepComponent } from '../../../../shared/components/stepper/step.component';
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
@@ -233,7 +232,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1001,
precio: 250000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -244,7 +243,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1002,
precio: 250000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -255,7 +254,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1003,
precio: 250000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('c', 'Sector C'),
@@ -266,7 +265,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1004,
precio: 200000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -277,7 +276,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1005,
precio: 200000,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
values: {
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
sector: ticketOption('a', 'Sector A'),
@@ -288,7 +287,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1006,
precio: 100000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'),
@@ -299,7 +298,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1007,
precio: 100000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('b', 'Sector B'),
@@ -310,7 +309,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1008,
precio: 90000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),
@@ -321,7 +320,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1009,
precio: 65000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),
@@ -332,7 +331,7 @@ export class ReutilizablesTestPageComponent {
{
id: 1010,
precio: 40000,
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: ticketOption('general', 'General'),
sector: ticketOption('d', 'Sector D'),

View File

@@ -17,7 +17,7 @@
[attr.aria-label]="option.label"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[title]="option.label"
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
<span class="visually-hidden">{{ option.label }}</span>
@@ -33,7 +33,7 @@
!availableOptions()[attribute.codigo][option.id]
"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
{{ option.label }}

View File

@@ -2,7 +2,6 @@ import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it } from 'vitest';
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
describe('ProductAttributeSelectorComponent', () => {
@@ -32,7 +31,7 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [
{
id: 1,
availability: createCatalogAvailability(null),
maximum_addable_quantity: null,
values: { size: 'S' },
},
]);
@@ -52,12 +51,12 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [
{
id: 1,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
values: { size: 'S' },
},
{
id: 2,
availability: createCatalogAvailability(2),
maximum_addable_quantity: 2,
values: { size: 'M' },
},
]);
@@ -93,9 +92,9 @@ describe('ProductAttributeSelectorComponent', () => {
]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [
{ id: 1, availability: createCatalogAvailability(null), values: { event_date: '1' } },
{ id: 2, availability: createCatalogAvailability(null), values: { event_date: '2' } },
{ id: 3, availability: createCatalogAvailability(null), values: { event_date: ['1', '2'] } },
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
{ id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
]);
fixture.detectChanges();
@@ -136,16 +135,8 @@ describe('ProductAttributeSelectorComponent', () => {
]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [
{
id: 1,
availability: createCatalogAvailability(null),
values: { size: 'S', internal_type: 'adult' },
},
{
id: 2,
availability: createCatalogAvailability(null),
values: { size: 'M', internal_type: 'child' },
},
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
]);
fixture.detectChanges();

View File

@@ -15,7 +15,6 @@ import {
ProductAttribute,
ProductAttributeOption,
} from '../../../../core/services/catalog/catalog.interface';
import { allowsCatalogAction } from '../../../../core/services/catalog/catalog-availability';
@Component({
selector: 'app-product-attribute-selector',
@@ -30,7 +29,6 @@ export class ProductAttributeSelectorComponent {
public variants = input<CatalogItemVariant[]>([]);
public selectedVariant = input<CatalogItemVariant | null>(null);
public inventoryPolicy = input.required<InventoryPolicy>();
public disabled = input(false);
public variantChange = output<CatalogItemVariant | null>();
@@ -53,15 +51,22 @@ export class ProductAttributeSelectorComponent {
const optionNormalized = this.normalizeText(option.value || option.label);
const selectedForAttribute = selections[attribute.codigo] ?? [];
if (
!attribute.allow_multi_select &&
selectedForAttribute.length >= 1 &&
!selectedForAttribute.includes(option.id)
) {
availability[attribute.codigo][option.id] = false;
continue;
}
const isAvailable = variants.some((variant) => {
if (!this.isVariantAvailable(variant)) return false;
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
const desiredOptionIds = attribute.allow_multi_select
? selectedForAttribute.includes(option.id)
? selectedForAttribute
: [...selectedForAttribute, option.id]
: [option.id];
const desiredOptionIds = selectedForAttribute.includes(option.id)
? selectedForAttribute
: [...selectedForAttribute, option.id];
const desiredValues = desiredOptionIds
.map((id) => attribute.options.find((candidate) => candidate.id === id))
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
@@ -132,8 +137,6 @@ export class ProductAttributeSelectorComponent {
attribute: ProductAttribute,
option: ProductAttributeOption,
): void {
if (this.disabled()) return;
this.selectedAttributeOptions.update((current) => {
const selected = current[attribute.codigo] ?? [];
const isMultiple = attribute.allow_multi_select ?? false;
@@ -183,15 +186,7 @@ export class ProductAttributeSelectorComponent {
return [];
}
const defaultValues =
attribute.type === 'event_date'
? (
variant.event_date_ids ??
(variant.event_date_id === null || variant.event_date_id === undefined
? []
: [variant.event_date_id])
).map(String)
: this.getVariantAttributeValues(attribute, variant.values);
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
if (defaultValues.length === 0) {
return [];
}
@@ -220,17 +215,6 @@ export class ProductAttributeSelectorComponent {
}
}
if (attribute.type === 'event_date') {
const variant = this.variants().find((candidate) => candidate.values === variantAttributes);
const eventDateIds =
variant?.event_date_ids ??
(variant?.event_date_id === null || variant?.event_date_id === undefined
? []
: [variant.event_date_id]);
return eventDateIds.map(String);
}
return [];
}
@@ -243,7 +227,7 @@ export class ProductAttributeSelectorComponent {
}
private isVariantAvailable(variant: CatalogItemVariant): boolean {
return allowsCatalogAction(variant.availability, 'select_variant');
return variant.maximum_addable_quantity !== 0;
}
private findFirstHexValue(value: unknown): string | null {

View File

@@ -23,7 +23,10 @@ import {
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service';
import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import {
CatalogGroupLayout,
CategoryItemsResponse,
@@ -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) {
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 {
this.creatingDirectPurchase.set(false);
}

View File

@@ -46,6 +46,17 @@
</div>
<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
title="COMPRA"
[items]="mappedCartItems()"

View File

@@ -28,6 +28,24 @@
display: flex;
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 {

View File

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

View File

@@ -28,6 +28,7 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { CheckoutDataStepComponent } from './checkout-data-step.component';
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
import {
CheckoutForm,
PaymentMethod,
@@ -64,6 +65,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly router = inject(Router);
private readonly tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly authService = inject(AuthService);
private readonly globalLoadingService = inject(GlobalLoadingService);
private readonly toastService = inject(ToastService);
@@ -95,6 +97,28 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly isLoadingPurchase = signal(true);
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(() => {
const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.subtotal) : 0;
@@ -161,7 +185,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
void this.router.navigate(['/']);
return;
@@ -228,6 +252,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
nombre_apellido: formValue.nombre,
});
this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.stepper.next();
@@ -281,6 +306,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) {
this.checkoutCountdownService.clear();
return true;
}
@@ -291,11 +317,25 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
await firstValueFrom(this.cartService.loadCart());
this.createdPurchaseId.set(null);
this.createdPurchase.set(null);
this.checkoutCountdownService.clear();
this.navigationStarted = true;
return true;
} catch (error) {
console.error('Failed to cancel the current purchase:', error);
if (this.isStockReservationExpiredError(error)) {
this.showRequestError(error, 'La reserva de stock venció.');
this.cartService.loadCart(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.');
return false;
} finally {
@@ -439,6 +479,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return;
}
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId);
return;
@@ -488,12 +530,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return;
}
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) {
console.error('Failed to validate transfer payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
}
if (runId !== this.transferPollingRunId) {
@@ -565,6 +618,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return;
}
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') {
this.handleConfirmedPayment(purchaseId);
return;
@@ -575,8 +630,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.qrPaymentStatus.set('failed');
return;
}
if (purchase.status === 'expired') {
this.navigateToPurchaseStatus(purchaseId);
return;
}
} catch (error) {
console.error('Failed to validate QR payment:', error);
if (this.isPurchaseExpiredError(error)) {
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
return;
}
} finally {
if (runId === this.qrPollingRunId) {
this.isCheckingQrPayment.set(false);
@@ -629,6 +693,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true;
this.stopQrPolling();
this.stopTransferPolling();
this.checkoutCountdownService.clear();
void this.router.navigate(['/checkout/status', purchaseId]);
}
@@ -666,6 +731,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.createdPurchaseId.set(purchase.id);
this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
if (
@@ -683,15 +749,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
}
} catch (error) {
console.error('Failed to load purchase:', error);
this.showRequestError(error, 'No se pudo cargar la compra.');
void this.router.navigate(['/']);
const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
if (!expired) {
void this.router.navigate(['/']);
}
}
}
private showRequestError(error: unknown, fallbackMessage: string): void {
private showRequestError(error: unknown, fallbackMessage: string): boolean {
const payload =
typeof error === 'object' && error !== null && 'error' in error
? (error as { error?: { message?: unknown } }).error
? (error as { error?: ApiErrorResponse }).error
: undefined;
const message =
typeof payload?.message === 'string' && payload.message.trim()
@@ -699,6 +767,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
: fallbackMessage;
this.toastService.danger(message);
if (payload?.code === 'purchase.expired') {
this.navigateToExpiredPurchaseStatus();
return true;
}
return false;
}
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
@@ -717,7 +792,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
? response.message
: 'La compra venció. Iniciá una nueva compra.',
);
void this.router.navigate(['/']);
this.navigateToExpiredPurchaseStatus();
return true;
}
@@ -729,6 +804,43 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return false;
}
private navigateToExpiredPurchaseStatus(): void {
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
if (purchaseId) {
if (this.navigationStarted) {
return;
}
this.navigationStarted = true;
this.stopQrPolling();
this.stopTransferPolling();
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 {
const purchase = this.createdPurchase();

View File

@@ -44,7 +44,6 @@
[variants]="prod.variants"
[selectedVariant]="prod.selected_variant ?? null"
[inventoryPolicy]="prod.inventory_policy"
[disabled]="!allows(prod.availability, 'select_variant')"
(variantChange)="onVariantChange($event)"
/>
</section>
@@ -54,22 +53,14 @@
<section class="product-detail__section">
<div class="product-detail__purchase">
@if (restrictionMessage(); as message) {
<p class="mb-0 text-danger" role="status">{{ message }}</p>
}
<app-quantity-selector
[(quantity)]="quantity"
[max]="selectedVariantMax()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
/>
<app-quantity-selector [(quantity)]="quantity" [max]="selectedVariantMax()" />
<div class="product-detail__actions">
<app-button
class="product-detail__cta"
variant="secondary"
type="button"
[disabled]="!canAddToCart() || variantLoading() || addingToCart()"
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
(click)="addToCart()"
>
@if (addingToCart()) {
@@ -84,7 +75,9 @@
<app-button
class="product-detail__cta"
type="button"
[disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
[disabled]="
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
"
(click)="buyNow()"
>
@if (variantLoading() || creatingDirectPurchase()) {

View File

@@ -10,7 +10,6 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component';
@@ -39,7 +38,7 @@ describe('ProductDetailPageComponent', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
availability: createCatalogAvailability(10),
maximum_addable_quantity: 10,
attributes: [],
variants: [],
};
@@ -180,7 +179,7 @@ describe('ProductDetailPageComponent', () => {
it('reloads product availability when the cart changes', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue(
of({ ...mockProduct, availability: createCatalogAvailability(4) }),
of({ ...mockProduct, maximum_addable_quantity: 4 }),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -193,21 +192,6 @@ describe('ProductDetailPageComponent', () => {
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
});
it('stops presenting a product that becomes hidden during an availability refresh', async () => {
catalogServiceStub.getCatalogItem.mockReturnValue(
throwError(() => new HttpErrorResponse({ status: 404 })),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
fixture.detectChanges();
expect(fixture.componentInstance['product']()).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Este producto ya no está disponible.');
});
it('shows error message if the resolver cannot load the product', async () => {
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
await configureTestingModule();
@@ -223,10 +207,10 @@ describe('ProductDetailPageComponent', () => {
const detailProduct: CatalogItemDetail = {
...mockProduct,
images: ['https://example.com/product.png'],
variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
selected_variant: {
id: 123,
availability: createCatalogAvailability(10),
maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
values: {},
},
@@ -328,15 +312,11 @@ describe('ProductDetailPageComponent', () => {
},
],
variants: [
{
id: 123,
availability: createCatalogAvailability(10),
values: { color: 'beige', material: 'Cuero' },
},
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
],
selected_variant: {
id: 123,
availability: createCatalogAvailability(10),
maximum_addable_quantity: 10,
images: ['https://example.com/variant1.png'],
values: {
color: 'beige',
@@ -373,18 +353,8 @@ describe('ProductDetailPageComponent', () => {
purpose: 'entry',
has_tickets: true,
variants: [
{
id: 101,
event_date_id: 20,
availability: createCatalogAvailability(10),
values: { event_date: '20' },
},
{
id: 102,
event_date_id: 21,
availability: createCatalogAvailability(10),
values: { event_date: '21' },
},
{ id: 101, event_date_id: 20, maximum_addable_quantity: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, maximum_addable_quantity: 10, values: { event_date: '21' } },
],
attributes: [
{
@@ -415,7 +385,7 @@ describe('ProductDetailPageComponent', () => {
selected_variant: {
id: 101,
event_date_id: 20,
availability: createCatalogAvailability(10),
maximum_addable_quantity: 10,
images: [],
values: {},
},
@@ -437,8 +407,6 @@ describe('ProductDetailPageComponent', () => {
options[1].click();
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
});
@@ -461,7 +429,7 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({
id: 1,
availability: createCatalogAvailability(10),
maximum_addable_quantity: 10,
values: {},
});
fixture.detectChanges();
@@ -539,9 +507,7 @@ describe('ProductDetailPageComponent', () => {
},
],
});
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
queryParams: { purchase: 44 },
});
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
});
it('shows the backend purchase-limit message for a direct checkout', async () => {
@@ -551,7 +517,7 @@ describe('ProductDetailPageComponent', () => {
error: {
code: 'purchase.limit_exceeded',
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
availability: createCatalogAvailability(2),
maximum_addable_quantity: 2,
},
}),
);
@@ -576,13 +542,13 @@ describe('ProductDetailPageComponent', () => {
variants: [
{
id: 123,
availability: createCatalogAvailability(5),
maximum_addable_quantity: 5,
values: {},
},
],
selected_variant: {
id: 123,
availability: createCatalogAvailability(5),
maximum_addable_quantity: 5,
images: [],
values: {},
},
@@ -615,7 +581,7 @@ describe('ProductDetailPageComponent', () => {
resolveProduct({
...mockProduct,
variants: [],
availability: createCatalogAvailability(4),
maximum_addable_quantity: 4,
});
await configureTestingModule();
@@ -641,13 +607,13 @@ describe('ProductDetailPageComponent', () => {
variants: [
{
id: 123,
availability: createCatalogAvailability(5),
maximum_addable_quantity: 5,
values: {},
},
],
selected_variant: {
id: 123,
availability: createCatalogAvailability(5),
maximum_addable_quantity: 5,
images: [],
values: {},
},
@@ -679,7 +645,7 @@ describe('ProductDetailPageComponent', () => {
it('allows unlimited variants to increase quantity without a maximum', async () => {
const unlimitedVariant = {
id: 321,
availability: createCatalogAvailability(null),
maximum_addable_quantity: null,
values: {},
};
resolveProduct({
@@ -687,7 +653,7 @@ describe('ProductDetailPageComponent', () => {
inventory_policy: 'unlimited',
selected_variant: {
id: 321,
availability: createCatalogAvailability(null),
maximum_addable_quantity: null,
images: [],
values: {},
},
@@ -711,7 +677,7 @@ describe('ProductDetailPageComponent', () => {
it('caps an unlimited variant at the per-user purchase limit', async () => {
const unlimitedVariant = {
id: 322,
availability: createCatalogAvailability(2),
maximum_addable_quantity: 2,
values: {},
};
resolveProduct({
@@ -720,7 +686,7 @@ describe('ProductDetailPageComponent', () => {
max_units_per_user: 2,
selected_variant: {
id: 322,
availability: createCatalogAvailability(2),
maximum_addable_quantity: 2,
images: [],
values: { event_date: '20' },
},
@@ -744,14 +710,14 @@ describe('ProductDetailPageComponent', () => {
it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = {
id: 654,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
values: {},
};
resolveProduct({
...mockProduct,
selected_variant: {
id: 654,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
images: [],
values: {},
},

View File

@@ -32,13 +32,6 @@ import { ProductDetailResolvedData } from './product-detail-page.resolver';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../../core/services/catalog/catalog-availability';
@Component({
selector: 'app-product-detail-page',
@@ -103,41 +96,29 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
() => this.selectedVariant()?.precio ?? this.product()?.precio,
);
protected readonly quantity = signal(1);
protected readonly effectiveAvailability = computed(() => {
const prod = this.product();
const variant = this.selectedVariant();
if (!prod) return AVAILABLE_CATALOG_AVAILABILITY;
return combineCatalogAvailability(prod.availability, variant?.availability);
});
protected readonly selectedVariantMax = computed<number | null>(() => {
const prod = this.product();
const variant = this.selectedVariant();
if (!prod) return 0;
if (!variant && prod.variants.length > 0) return 0;
return maximumCatalogQuantity(this.effectiveAvailability());
return variant
? (variant.maximum_addable_quantity ?? null)
: prod.variants.length === 0
? (prod.maximum_addable_quantity ?? null)
: 0;
});
protected readonly hasPurchasableSelection = computed(() => {
protected readonly selectedVariantAvailable = computed(() => {
const prod = this.product();
if (!prod) return false;
if (this.selectedVariantMax() === 0) return false;
return prod.variants.length === 0 || this.selectedVariant() !== null;
const variant = this.selectedVariant();
if (variant) return this.isVariantAvailable(variant);
if (prod.purpose === 'entry') return false;
if (prod.variants.length > 0) return false;
return this.selectedVariantMax() !== 0;
});
protected readonly canAddToCart = computed(
() =>
this.hasPurchasableSelection() &&
allowsCatalogAction(this.effectiveAvailability(), 'add_to_cart'),
);
protected readonly canBuyNow = computed(
() =>
this.hasPurchasableSelection() &&
allowsCatalogAction(this.effectiveAvailability(), 'buy_now'),
);
protected readonly restrictionMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
);
protected readonly allows = allowsCatalogAction;
protected readonly descriptionExpanded = signal(false);
protected readonly descriptionMaxHeight = signal(0);
protected readonly descriptionHasOverflow = signal(false);
@@ -243,12 +224,8 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.quantity.set(Math.max(1, maximum));
}
},
error: (error: HttpErrorResponse) => {
if (error.status === 404) {
this.product.set(null);
this.selectedVariant.set(null);
this.error.set('Este producto ya no está disponible.');
}
error: () => {
// Keep the last known availability if the silent refresh fails.
},
});
}
@@ -318,10 +295,8 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected addToCart(): void {
const currentProduct = this.product();
const variant = this.selectedVariant();
if (!currentProduct || !this.canAddToCart()) {
this.toastService.danger(
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
);
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
return;
}
@@ -351,10 +326,8 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
return;
}
if (!currentProduct || !this.canBuyNow()) {
this.toastService.danger(
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
);
if (!currentProduct || !this.selectedVariantAvailable()) {
this.toastService.danger('Por favor, selecciona una variante.');
return;
}
@@ -385,9 +358,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
],
});
await this.router.navigate(['/checkout'], {
queryParams: { purchase: purchase.id },
});
await this.router.navigate(['/checkout', purchase.id]);
} catch (error) {
console.error('Failed to create direct purchase:', error);
const message =
@@ -400,6 +371,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
}
private isVariantAvailable(variant: CatalogItemVariant): boolean {
return variant.maximum_addable_quantity !== 0;
}
protected toggleDescription(): void {
this.descriptionExpanded.update((current) => !current);
}

View File

@@ -5,7 +5,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import {
PRODUCT_DETAIL_ERROR_MESSAGE,
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
@@ -30,7 +29,7 @@ describe('productDetailResolver', () => {
has_tickets: false,
minimum_use_date: null,
maximum_use_date: null,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
attributes: [],
variants: [],
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -24,7 +24,10 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CartService } from '../../../../core/services/cart/cart.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CheckoutService } from '../../../../core/services/checkout.service';
import {
CheckoutService,
isExpiredStockReservationResponse,
} from '../../../../core/services/checkout.service';
import {
CatalogFeaturedItem,
CatalogFeaturedItems,
@@ -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) {
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 {
this.creatingDirectPurchase.set(false);
}

View File

@@ -13,7 +13,6 @@ import {
} from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
@@ -84,7 +83,6 @@ const pageOneItems: CatalogFeaturedItem[] = [
nombre: 'Auriculares Bluetooth',
precio: '24999.00',
image: '/catalog/auriculares.jpg',
availability: createCatalogAvailability(null),
},
{
id: 2,
@@ -92,7 +90,6 @@ const pageOneItems: CatalogFeaturedItem[] = [
nombre: 'Teclado Mecanico',
precio: '18999.00',
image: null,
availability: createCatalogAvailability(null),
},
];
@@ -409,14 +406,7 @@ describe('StoreHomePageComponent', () => {
it('requests another page for the selected featured group', async () => {
const pageTwoItems: CatalogFeaturedItem[] = [
{
id: 3,
type: 'product',
nombre: 'Mouse Gamer',
precio: '15999.00',
image: null,
availability: createCatalogAvailability(null),
},
{ id: 3, type: 'product', nombre: 'Mouse Gamer', precio: '15999.00', image: null },
];
const catalogServiceStub = {
getCatalog: vi.fn(),

View File

@@ -21,6 +21,7 @@ import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import {
CheckoutService,
isExpiredStockReservationResponse,
isInsufficientStockResponse,
} from '../../../../core/services/checkout.service';
import {
@@ -217,10 +218,18 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
tenant.codigo,
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
);
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
await this.router.navigate(['/checkout', purchase.id]);
} catch (error) {
console.error('Failed to create direct purchase:', error);
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)) {
const unavailableIds = error.error.unavailable_items
.map((item) => item.variant_id)

View File

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

View File

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

View File

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

View File

@@ -12,7 +12,8 @@
[title]="item.nombre"
[description]="item.descripcion ?? ''"
[price]="price(item)"
[availability]="itemAvailability(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[unavailableMessage]="item.unavailable_message ?? null"
[variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitRowBuy(item, $event)"
@@ -24,7 +25,8 @@
[title]="item.nombre"
[description]="item.descripcion ?? ''"
[price]="price(item)"
[availability]="itemAvailability(item)"
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
[unavailableMessage]="item.unavailable_message ?? null"
[variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitColumnBuy(item, $event)"
@@ -38,8 +40,8 @@
[description]="item.descripcion ?? ''"
[price]="price(item)"
[imageUrl]="loadImages() ? (item.image ?? null) : null"
[unavailableMessage]="availabilityMessage(item)"
[disabled]="loading() || !allows(itemAvailability(item), 'buy_now')"
[unavailableMessage]="item.unavailable_message ?? null"
[disabled]="loading() || !!item.unavailable_message"
(buy)="emitTicketBuy(item, $event)"
/>
}
@@ -48,7 +50,7 @@
[imageUrl]="loadImages() ? (item.image ?? null) : null"
[title]="item.nombre"
[originalPrice]="price(item)"
[unavailableMessage]="availabilityMessage(item)"
[unavailableMessage]="item.unavailable_message ?? null"
[imagePriority]="loadImages() && index < 4"
(buy)="emitProductDetailBuy(item)"
/>

View File

@@ -6,7 +6,6 @@ import { of } from 'rxjs';
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
import { CartService } from '../../../core/services/cart/cart.service';
import { CatalogService } from '../../../core/services/catalog/catalog.service';
import { createCatalogAvailability } from '../../../core/services/catalog/catalog-availability';
import {
CatalogFeaturedItems,
CatalogGroupLayout,
@@ -24,7 +23,6 @@ describe('ProductListComponent', () => {
descripcion: 'Primera descripcion',
precio: '100.00',
image: '/images/one.png',
availability: createCatalogAvailability(null),
variants: [],
},
{
@@ -34,7 +32,6 @@ describe('ProductListComponent', () => {
descripcion: 'Segunda descripcion',
precio: 200,
image: null,
availability: createCatalogAvailability(null),
variants: [],
},
];
@@ -59,20 +56,6 @@ describe('ProductListComponent', () => {
) {
const getVariantOptions = vi.fn().mockReturnValue(
of({
variants: [
{
id: 401,
precio: '10000.00',
availability: createCatalogAvailability(1),
values: { tipo: '1', sector: '2', fila: '3', asiento: '4' },
},
{
id: 402,
precio: '12000.00',
availability: createCatalogAvailability(1),
values: { tipo: '1', sector: '2', fila: '3', asiento: '5' },
},
],
selectors: ['tipo', 'sector', 'fila', 'asiento'].map((key, index) => ({
key,
label: key,
@@ -90,12 +73,7 @@ describe('ProductListComponent', () => {
await TestBed.configureTestingModule({
imports: [ProductListComponent],
providers: [
{
provide: CatalogService,
useValue: {
withoutLoading: () => ({ getVariantOptions }),
},
},
{ provide: CatalogService, useValue: { getVariantOptions } },
{ provide: CartService, useValue: {} },
],
}).compileComponents();
@@ -215,8 +193,8 @@ describe('ProductListComponent', () => {
const itemWithVariants: ProductListItem = {
...items[0],
variants: [
{ id: 91, availability: createCatalogAvailability(3), values: { fecha: '10 de octubre' } },
{ id: 92, availability: createCatalogAvailability(4), values: { fecha: '11 de octubre' } },
{ id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
{ id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
],
};
const fixture = await render('column_with_cart', [itemWithVariants]);
@@ -242,7 +220,7 @@ describe('ProductListComponent', () => {
variants: [
{
id: 91,
availability: createCatalogAvailability(2),
maximum_addable_quantity: 2,
values: { fecha: '10 de octubre' },
},
],
@@ -270,7 +248,7 @@ describe('ProductListComponent', () => {
variants: [
{
id: 91,
availability: createCatalogAvailability(0),
maximum_addable_quantity: 0,
values: { fecha: '10 de octubre' },
},
],
@@ -326,7 +304,7 @@ describe('ProductListComponent', () => {
{
id: 401,
precio: '10000.00',
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },
@@ -337,7 +315,7 @@ describe('ProductListComponent', () => {
{
id: 402,
precio: '12000.00',
availability: createCatalogAvailability(1),
maximum_addable_quantity: 1,
values: {
tipo: { value: 'vip', label: 'VIP' },
sector: { value: 'a', label: 'Sector A' },

View File

@@ -18,11 +18,6 @@ import {
CatalogGroupLayout,
CatalogProductLayout,
} from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
import { CarouselComponent } from '../carousel/carousel.component';
import { PaginatorComponent } from '../paginator/paginator.component';
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
@@ -79,7 +74,6 @@ export class ProductListComponent {
readonly buy = output<ProductListBuyEvent>();
readonly addToCart = output<ProductListCartEvent>();
readonly pageChange = output<number>();
protected readonly allows = allowsCatalogAction;
protected readonly effectiveLayout = computed<ProductListLayout>(() =>
this.mobile() && this.layout() === 'row' ? 'column_with_cart' : this.layout(),
@@ -114,14 +108,6 @@ export class ProductListComponent {
return Number.isFinite(price) ? price : 0;
}
protected availabilityMessage(item: ProductListItem): string | null {
return primaryAvailabilityMessage(this.itemAvailability(item));
}
protected itemAvailability(item: ProductListItem) {
return item.availability ?? AVAILABLE_CATALOG_AVAILABILITY;
}
protected emitRowCart(
product: ProductListItem,
event: { quantity: number; variant: unknown },

View File

@@ -21,14 +21,13 @@
<app-variant-selector
class="product-row-card__selectors"
[variants]="variants()"
[disabled]="!allows(availability(), 'select_variant')"
[(selectedVariant)]="selectedVariant"
/>
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
[disabled]="unavailable()"
/>
</div>
@@ -39,22 +38,14 @@
<div class="product-row-card__buttons">
<div class="product-row-card__btn-wrapper">
<app-button
variant="primary"
[disabled]="!hasPurchasableSelection() || !allows(effectiveAvailability(), 'buy_now')"
(click)="onBuy()"
>
<app-button variant="primary" [disabled]="unavailable()" (click)="onBuy()">
Comprar
</app-button>
</div>
<div class="product-row-card__btn-wrapper">
<app-button
variant="secondary"
[disabled]="
saving() ||
!hasPurchasableSelection() ||
!allows(effectiveAvailability(), 'add_to_cart')
"
[disabled]="saving() || unavailable()"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -14,20 +14,13 @@ import {
VariantSelectorComponent,
VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
export interface Variant extends VariantSelectorVariant {
label?: string;
descripcion?: string | null;
precio?: string | number;
availability?: CatalogAvailability;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
}
@Component({
@@ -43,7 +36,8 @@ export class ProductRowCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly variants = input<Variant[]>([]);
readonly saving = input(false);
@@ -66,22 +60,19 @@ export class ProductRowCardComponent {
return Number.isFinite(variantPrice) ? variantPrice : this.price();
});
protected readonly effectiveAvailability = computed(() =>
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
);
protected readonly hasVariants = computed(() => this.variants().length > 0);
protected readonly hasPurchasableSelection = computed(
() => !this.hasVariants() || this.selectedVariantData() !== undefined,
);
protected readonly effectiveMaximum = computed(() =>
maximumCatalogQuantity(this.effectiveAvailability()),
);
protected readonly effectiveUnavailableMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
protected readonly effectiveMaximum = computed(
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
);
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected readonly allows = allowsCatalogAction;
constructor() {
effect(() => {
@@ -94,11 +85,7 @@ export class ProductRowCardComponent {
}
protected onAddToCart(): void {
if (
this.saving() ||
!this.hasPurchasableSelection() ||
!this.allows(this.effectiveAvailability(), 'add_to_cart')
) {
if (this.saving() || this.unavailable()) {
return;
}
@@ -109,8 +96,7 @@ export class ProductRowCardComponent {
}
protected onBuy(): void {
if (!this.hasPurchasableSelection() || !this.allows(this.effectiveAvailability(), 'buy_now'))
return;
if (this.unavailable()) return;
this.buy.emit({
quantity: this.quantity(),

View File

@@ -23,10 +23,6 @@ import {
CatalogVariantSelector,
CatalogVariantValue,
} from '../../../core/services/catalog/catalog.interface';
import {
allowsCatalogAction,
createCatalogAvailability,
} from '../../../core/services/catalog/catalog-availability';
import { CatalogService } from '../../../core/services/catalog/catalog.service';
import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service';
@@ -357,11 +353,7 @@ export class ProductTicketSelectorComponent {
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
variants.push(reservedVariant);
}
return variants.filter(
({ id, availability }) =>
(availability === undefined || allowsCatalogAction(availability, 'select_variant')) &&
!reservedByOtherRows.has(id),
);
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
}
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
@@ -371,9 +363,7 @@ export class ProductTicketSelectorComponent {
return {
id: item.variant.id,
precio: item.variant.precio,
availability: createCatalogAvailability(
item.variant.stock_tecnico === null ? null : item.variant.stock_tecnico + item.cantidad,
),
maximum_addable_quantity: item.variant.stock_tecnico,
values: item.variant.values,
};
}

View File

@@ -19,7 +19,7 @@
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
[disabled]="unavailable()"
/>
</div>
} @else {
@@ -29,16 +29,12 @@
<app-quantity-selector
[(quantity)]="quantity"
[max]="effectiveMaximum()"
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
[disabled]="unavailable()"
/>
</div>
<div class="product-vertical-with-cart-card__variant-selectors">
<app-variant-selector
[variants]="variants()"
[disabled]="!allows(availability(), 'select_variant')"
[(selectedVariant)]="selectedVariant"
/>
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
</div>
</div>
}
@@ -46,21 +42,14 @@
<div class="product-vertical-with-cart-card__actions">
<app-button
variant="primary"
[disabled]="
!allows(effectiveAvailability(), 'buy_now') ||
(hasVariants() && selectedVariant() === null)
"
[disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onBuy()"
>
Comprar
</app-button>
<app-button
variant="secondary"
[disabled]="
saving() ||
!allows(effectiveAvailability(), 'add_to_cart') ||
(hasVariants() && selectedVariant() === null)
"
[disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
(click)="onAddToCart()"
>
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}

View File

@@ -58,17 +58,11 @@ describe('ProductVerticalWithCartCardComponent', () => {
it('shows the backend availability message with the reusable tooltip', async () => {
const fixture = await createComponent();
fixture.componentRef.setInput('availability', {
state: 'visible',
maximum_quantity: 0,
reasons: [
{
code: 'user_quota_reached',
message: 'Alcanzaste el cupo máximo permitido para este producto.',
},
],
allowed_actions: [],
});
fixture.componentRef.setInput('maximumAddableQuantity', 0);
fixture.componentRef.setInput(
'unavailableMessage',
'Alcanzaste el cupo máximo permitido para este producto.',
);
fixture.detectChanges();
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');

View File

@@ -15,19 +15,12 @@ import {
VariantSelectorComponent,
VariantSelectorVariant,
} from '../variant-selector/variant-selector.component';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import {
AVAILABLE_CATALOG_AVAILABILITY,
allowsCatalogAction,
combineCatalogAvailability,
maximumCatalogQuantity,
primaryAvailabilityMessage,
} from '../../../core/services/catalog/catalog-availability';
export interface VerticalCartVariant extends VariantSelectorVariant {
descripcion?: string | null;
precio?: string | number;
availability?: CatalogAvailability;
maximum_addable_quantity?: number | null;
unavailable_message?: string | null;
}
@Component({
@@ -41,7 +34,8 @@ export class ProductVerticalWithCartCardComponent {
readonly title = input<string>('');
readonly description = input<string>('');
readonly price = input<number>(0);
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
readonly maximumAddableQuantity = input<number | null>(null);
readonly unavailableMessage = input<string | null>(null);
readonly variants = input<VerticalCartVariant[]>([]);
readonly saving = input(false);
@@ -64,16 +58,17 @@ export class ProductVerticalWithCartCardComponent {
});
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected readonly hasVariants = computed(() => this.variants().length > 0);
protected readonly effectiveAvailability = computed(() =>
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
protected readonly effectiveMaximum = computed(
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
);
protected readonly effectiveMaximum = computed(() =>
maximumCatalogQuantity(this.effectiveAvailability()),
);
protected readonly effectiveUnavailableMessage = computed(() =>
primaryAvailabilityMessage(this.effectiveAvailability()),
);
protected readonly allows = allowsCatalogAction;
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
protected readonly effectiveUnavailableMessage = computed(() => {
const selectedVariant = this.selectedVariantData();
return selectedVariant
? (selectedVariant.unavailable_message ?? null)
: this.unavailableMessage();
});
constructor() {
effect(() => {
@@ -86,7 +81,7 @@ export class ProductVerticalWithCartCardComponent {
}
protected onAddToCart(): void {
if (this.saving() || !this.allows(this.effectiveAvailability(), 'add_to_cart')) {
if (this.saving() || this.unavailable()) {
return;
}
@@ -94,7 +89,7 @@ export class ProductVerticalWithCartCardComponent {
}
protected onBuy(): void {
if (!this.allows(this.effectiveAvailability(), 'buy_now')) return;
if (this.unavailable()) return;
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
}

View File

@@ -62,8 +62,6 @@ describe('VariantSelectorComponent', () => {
]);
fixture.componentRef.setInput('selectedVariant', 2);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const selects = Array.from(
fixture.nativeElement.querySelectorAll('select'),
@@ -82,28 +80,6 @@ describe('VariantSelectorComponent', () => {
expect(fixture.componentInstance.selectedVariant()).toBe(1);
});
it('does not offer variants whose availability forbids selection', async () => {
await TestBed.configureTestingModule({
imports: [VariantSelectorComponent],
}).compileComponents();
const fixture = TestBed.createComponent(VariantSelectorComponent);
fixture.componentRef.setInput('variants', [
{ id: 1, values: { talle: 'S' } },
{
id: 2,
values: { talle: 'M' },
availability: { state: 'visible', maximum_quantity: 0, allowed_actions: [], reasons: [] },
},
]);
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('S');
expect(fixture.nativeElement.textContent).not.toContain('M');
expect(fixture.componentInstance.selectedVariant()).toBe(1);
});
it('requires manual selections when autoSelectFirst is disabled', async () => {
await TestBed.configureTestingModule({
imports: [VariantSelectorComponent],

View File

@@ -10,8 +10,6 @@ import {
untracked,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
import { allowsCatalogAction } from '../../../core/services/catalog/catalog-availability';
export interface VariantAttributeOption {
value: string;
@@ -24,7 +22,6 @@ export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeSca
export interface VariantSelectorVariant {
id: unknown;
values: Record<string, VariantAttributeValue>;
availability?: CatalogAvailability;
}
export interface VariantSelectorSelectionChange {
@@ -67,12 +64,10 @@ export class VariantSelectorComponent {
right: VariantAttributeValue | null,
): boolean => left !== null && right !== null && this.sameValue(left, right);
protected readonly attributeKeys = computed(() =>
Array.from(
new Set(this.getSelectableVariants().flatMap((variant) => Object.keys(variant.values))),
),
Array.from(new Set(this.variants().flatMap((variant) => Object.keys(variant.values)))),
);
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
const variants = this.getSelectableVariants();
const variants = this.variants();
const keys = this.attributeKeys();
const selectedValues = this.selectedValues();
@@ -115,7 +110,7 @@ export class VariantSelectorComponent {
});
effect(() => {
const variants = this.getSelectableVariants();
const variants = this.variants();
const selectedVariant = this.selectedVariant();
const autoSelectFirst = this.autoSelectFirst();
@@ -144,7 +139,7 @@ export class VariantSelectorComponent {
}
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
const variants = this.getSelectableVariants();
const variants = this.variants();
const keys = this.attributeKeys();
const changedIndex = keys.indexOf(key);
const values = { ...this.selectedValues() };
@@ -203,14 +198,6 @@ export class VariantSelectorComponent {
return Array.from(options.values());
}
private getSelectableVariants(): VariantSelectorVariant[] {
return this.variants().filter(
(variant) =>
variant.availability === undefined ||
allowsCatalogAction(variant.availability, 'select_variant'),
);
}
private reconcileManualSelection(
selectedValues: Record<string, VariantAttributeValue>,
variants: VariantSelectorVariant[],

View File

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

View File

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