Compare commits
6 Commits
develop
...
feature/al
| Author | SHA1 | Date | |
|---|---|---|---|
| 72c80465e8 | |||
| 5273459b64 | |||
| 3ec469a539 | |||
| f02f4456b7 | |||
| eda8d32f4e | |||
| 5ca1f03e20 |
@@ -7,7 +7,6 @@ import { of } from 'rxjs';
|
|||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { AuthService } from './core/services/auth/auth.service';
|
import { AuthService } from './core/services/auth/auth.service';
|
||||||
import { CartService } from './core/services/cart/cart.service';
|
import { CartService } from './core/services/cart/cart.service';
|
||||||
import { CheckoutService } from './core/services/checkout.service';
|
|
||||||
import { Tenant } from './core/services/tenant.interface';
|
import { Tenant } from './core/services/tenant.interface';
|
||||||
import { TenantService } from './core/services/tenant.service';
|
import { TenantService } from './core/services/tenant.service';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -98,21 +97,6 @@ async function renderAppAt(
|
|||||||
{
|
{
|
||||||
provide: AuthService,
|
provide: AuthService,
|
||||||
useValue: authService
|
useValue: authService
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: CheckoutService,
|
|
||||||
useValue: {
|
|
||||||
withCustomLoading() {
|
|
||||||
return this;
|
|
||||||
},
|
|
||||||
getPurchase: vi.fn().mockResolvedValue({
|
|
||||||
id: 25,
|
|
||||||
status: 'created',
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -262,33 +246,15 @@ describe('app routes', () => {
|
|||||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('redirects unauthenticated users from /checkout/:id to /login', async () => {
|
it('redirects unauthenticated users from /checkout to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
|
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
||||||
|
|
||||||
expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
|
expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows authenticated users to access /checkout/:id', async () => {
|
it('allows authenticated users to access /checkout', async () => {
|
||||||
const checkoutTenant = {
|
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true));
|
||||||
...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/25');
|
expect(router.url).toBe('/checkout');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -115,6 +115,6 @@ describe('App', () => {
|
|||||||
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
expect(document.title).toBe('ShopitFront');
|
expect(document.title).toBe('ShopitFront');
|
||||||
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||||
.toBe("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E");
|
.toBe('favicon.ico');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ import { GlobalLoadingComponent } from './shared/components/global-loading/globa
|
|||||||
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
||||||
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
||||||
|
|
||||||
const EMPTY_FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";
|
|
||||||
|
|
||||||
function hexToRgb(hex: string): string {
|
function hexToRgb(hex: string): string {
|
||||||
const cleanHex = hex.replace('#', '').trim();
|
const cleanHex = hex.replace('#', '').trim();
|
||||||
let r = 0, g = 0, b = 0;
|
let r = 0, g = 0, b = 0;
|
||||||
@@ -68,7 +66,7 @@ export class App {
|
|||||||
effect(() => {
|
effect(() => {
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
||||||
const faviconHref = tenant?.favicon || EMPTY_FAVICON;
|
const faviconHref = tenant?.favicon || 'favicon.ico';
|
||||||
|
|
||||||
this.title.setTitle(siteTitle);
|
this.title.setTitle(siteTitle);
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe('hasMenuGuard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('redirects a missing menu route to the store root', () => {
|
it('redirects a missing menu route to the store root', () => {
|
||||||
const result = runGuard('checkout', '/checkout/25', tenant);
|
const result = runGuard('checkout', '/checkout', tenant);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||||
|
|||||||
@@ -152,9 +152,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="store-layout__categories d-none d-md-block">
|
@if (displayCategories()) {
|
||||||
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
|
<div class="store-layout__categories d-none d-md-block">
|
||||||
@if (displayCategories()) {
|
<div class="container-xl px-3 px-md-4">
|
||||||
<div class="store-layout__category-menu">
|
<div class="store-layout__category-menu">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -175,18 +175,7 @@
|
|||||||
(categorySelect)="onCategorySelect($event)"
|
(categorySelect)="onCategorySelect($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
}
|
</div>
|
||||||
|
|
||||||
@if (checkoutRemainingTime(); as remainingTime) {
|
|
||||||
<div
|
|
||||||
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
|
|
||||||
role="timer"
|
|
||||||
aria-label="Tiempo restante de compra"
|
|
||||||
>
|
|
||||||
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
|
|
||||||
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
}
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -10,26 +10,6 @@
|
|||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__categories {
|
|
||||||
height: 3.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer {
|
|
||||||
color: var(--tenant-primary);
|
|
||||||
font-weight: 700;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer-label {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__checkout-timer-value {
|
|
||||||
font-size: 20px;
|
|
||||||
line-height: 1;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
.store-layout__brand-slot {
|
||||||
min-width: 150px;
|
min-width: 150px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,4 @@
|
|||||||
import {
|
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
|
||||||
Component,
|
|
||||||
computed,
|
|
||||||
ElementRef,
|
|
||||||
HostListener,
|
|
||||||
inject,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core';
|
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||||
@@ -49,7 +40,6 @@ export class StoreHeaderComponent {
|
|||||||
readonly displaySeachBar = input(true);
|
readonly displaySeachBar = input(true);
|
||||||
readonly displayCart = input(true);
|
readonly displayCart = input(true);
|
||||||
readonly cartDisabled = input(false);
|
readonly cartDisabled = input(false);
|
||||||
readonly checkoutRemainingSeconds = input<number | null>(null);
|
|
||||||
readonly cartClick = output<void>();
|
readonly cartClick = output<void>();
|
||||||
readonly ticketsClick = output<void>();
|
readonly ticketsClick = output<void>();
|
||||||
readonly loginClick = output<void>();
|
readonly loginClick = output<void>();
|
||||||
@@ -63,18 +53,6 @@ export class StoreHeaderComponent {
|
|||||||
protected readonly minSearchLength = 3;
|
protected readonly minSearchLength = 3;
|
||||||
protected readonly showSearchError = signal(false);
|
protected readonly showSearchError = signal(false);
|
||||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
||||||
protected readonly checkoutRemainingTime = computed(() => {
|
|
||||||
const remainingSeconds = this.checkoutRemainingSeconds();
|
|
||||||
|
|
||||||
if (remainingSeconds === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const minutes = Math.floor(remainingSeconds / 60);
|
|
||||||
const seconds = remainingSeconds % 60;
|
|
||||||
|
|
||||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
protected onCartClick(): void {
|
protected onCartClick(): void {
|
||||||
if (this.cartDisabled()) {
|
if (this.cartDisabled()) {
|
||||||
|
|||||||
@@ -13,7 +13,6 @@
|
|||||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||||
[displayCart]="displayCart()"
|
[displayCart]="displayCart()"
|
||||||
[cartDisabled]="isCheckoutRoute()"
|
[cartDisabled]="isCheckoutRoute()"
|
||||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
|
||||||
(cartClick)="onCartClick()"
|
(cartClick)="onCartClick()"
|
||||||
(ticketsClick)="onTicketsClick()"
|
(ticketsClick)="onTicketsClick()"
|
||||||
(loginClick)="onLoginClick()"
|
(loginClick)="onLoginClick()"
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
:host {
|
:host {
|
||||||
display: flex;
|
display: flex;
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
min-height: 100dvh;
|
min-height: 100dvh;
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
color: #202020;
|
color: #202020;
|
||||||
@@ -9,8 +7,6 @@
|
|||||||
|
|
||||||
.store-layout {
|
.store-layout {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__cart-overlay {
|
.store-layout__cart-overlay {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import {
|
import {
|
||||||
@@ -24,7 +23,6 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
|
|||||||
import { StoreLayoutComponent } from './store-layout.component';
|
import { StoreLayoutComponent } from './store-layout.component';
|
||||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||||
import { CheckoutService } from '../../services/checkout.service';
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
|
||||||
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
@@ -151,7 +149,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let tenantState = signal<Tenant | null>(tenant);
|
let tenantState = signal<Tenant | null>(tenant);
|
||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
let checkoutRemainingSecondsState = signal<number | null>(null);
|
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
let queryParamMapState: BehaviorSubject<ParamMap>;
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
@@ -159,7 +156,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
checkoutRemainingSecondsState = signal<number | null>(null);
|
|
||||||
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
@@ -218,12 +214,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
provide: CheckoutService,
|
provide: CheckoutService,
|
||||||
useValue: checkoutServiceStub,
|
useValue: checkoutServiceStub,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
provide: CheckoutCountdownService,
|
|
||||||
useValue: {
|
|
||||||
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
@@ -256,7 +246,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
||||||
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25');
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -280,22 +270,6 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the synchronized countdown in the header whenever one is active', () => {
|
|
||||||
checkoutRemainingSecondsState.set(587);
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const element = fixture.nativeElement as HTMLElement;
|
|
||||||
|
|
||||||
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
|
|
||||||
'Tiempo restante de compra:',
|
|
||||||
);
|
|
||||||
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
|
|
||||||
'09:47',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('hides the configured header elements when the tenant disables them', () => {
|
it('hides the configured header elements when the tenant disables them', () => {
|
||||||
tenantState.set({
|
tenantState.set({
|
||||||
...tenant,
|
...tenant,
|
||||||
@@ -613,7 +587,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const authService = TestBed.inject(AuthService);
|
const authService = TestBed.inject(AuthService);
|
||||||
const cartService = TestBed.inject(CartService);
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
|
||||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
@@ -700,44 +674,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
||||||
cart_id: 1,
|
cart_id: 1,
|
||||||
});
|
});
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
|
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
|
||||||
|
queryParams: { purchase: 55 },
|
||||||
|
});
|
||||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
|
|
||||||
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
|
||||||
checkoutServiceStub.startCheckout.mockRejectedValue(
|
|
||||||
new HttpErrorResponse({
|
|
||||||
status: 422,
|
|
||||||
error: { code: 'stock_reservation.expired', message },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
cartState.set({
|
|
||||||
id: 1,
|
|
||||||
tenant_codigo: tenant.codigo,
|
|
||||||
status: 'active',
|
|
||||||
subtotal: '100.00',
|
|
||||||
items: [],
|
|
||||||
});
|
|
||||||
authUserState.set({
|
|
||||||
id: 7,
|
|
||||||
nombre_apellido: 'Juan Perez',
|
|
||||||
email: 'juan@example.com',
|
|
||||||
dni: '12345678',
|
|
||||||
telefono: '3415555555',
|
|
||||||
});
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
|
||||||
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
|
|
||||||
fixture.detectChanges();
|
|
||||||
loadCart.mockClear();
|
|
||||||
|
|
||||||
await (fixture.componentInstance as any).onCheckoutClick();
|
|
||||||
|
|
||||||
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
|
||||||
expect(loadCart).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
||||||
cartState.set({
|
cartState.set({
|
||||||
id: 1,
|
id: 1,
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { HttpErrorResponse } from '@angular/common/http';
|
|
||||||
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import {
|
import {
|
||||||
@@ -18,13 +17,9 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
|
|||||||
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
||||||
import { AuthService } from '../../services/auth/auth.service';
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { findMenu } from '../../services/menu.utils';
|
import { findMenu } from '../../services/menu.utils';
|
||||||
import {
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../services/checkout.service';
|
|
||||||
import { ToastService } from '../../services/toast.service';
|
import { ToastService } from '../../services/toast.service';
|
||||||
import { Category } from '../../services/tenant.interface';
|
import { Category } from '../../services/tenant.interface';
|
||||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -43,7 +38,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
@@ -51,7 +45,6 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||||
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
|
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||||
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||||
@@ -280,20 +273,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], {
|
||||||
|
queryParams: { purchase: purchase.id },
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create cart purchase:', error);
|
console.error('Failed to create cart purchase:', error);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.isCreatingPurchase.set(false);
|
this.isCreatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,12 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout/25' } as never),
|
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
||||||
'/login?returnUrl=%2Fcheckout%2F25',
|
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout/25' } as never),
|
authGuard(null as never, { url: '/checkout' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|||||||
@@ -83,20 +83,6 @@ describe('CartService', () => {
|
|||||||
req.flush({ data: mockCart });
|
req.flush({ data: mockCart });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
|
|
||||||
const availabilityChanged = vi.fn();
|
|
||||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
|
||||||
|
|
||||||
service.loadCart(true).subscribe();
|
|
||||||
|
|
||||||
expect(availabilityChanged).not.toHaveBeenCalled();
|
|
||||||
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
|
|
||||||
req.flush({ data: mockCart });
|
|
||||||
|
|
||||||
expect(service.cart()).toEqual(mockCart);
|
|
||||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates a custom loading mode to the request context', () => {
|
it('propagates a custom loading mode to the request context', () => {
|
||||||
service.withCustomLoading().loadCart().subscribe();
|
service.withCustomLoading().loadCart().subscribe();
|
||||||
|
|
||||||
|
|||||||
@@ -34,19 +34,14 @@ export class CartService extends BaseApiService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
loadCart(): Observable<Cart> {
|
||||||
return this.http
|
return this.http
|
||||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
map((response) => response.data),
|
map((response) => response.data),
|
||||||
tap((cart) => {
|
tap((cart) => this.cartState.set(cart)),
|
||||||
this.cartState.set(cart);
|
|
||||||
if (refreshCatalogAvailability) {
|
|
||||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
@@ -49,6 +49,25 @@ export interface ProductAttribute {
|
|||||||
|
|
||||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
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 {
|
export interface CatalogVariantOption {
|
||||||
value: string;
|
value: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -66,8 +85,7 @@ export interface CatalogItemVariant {
|
|||||||
event_date_id?: number | null;
|
event_date_id?: number | null;
|
||||||
event_date_ids?: number[];
|
event_date_ids?: number[];
|
||||||
event_dates?: string[];
|
event_dates?: string[];
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
minimum_use_date?: string | null;
|
minimum_use_date?: string | null;
|
||||||
maximum_use_date?: string | null;
|
maximum_use_date?: string | null;
|
||||||
effective_minimum_use_date?: string | null;
|
effective_minimum_use_date?: string | null;
|
||||||
@@ -99,7 +117,7 @@ export interface CatalogItemDetail {
|
|||||||
attributes: ProductAttribute[];
|
attributes: ProductAttribute[];
|
||||||
variants: CatalogItemVariant[];
|
variants: CatalogItemVariant[];
|
||||||
selected_variant?: SelectedCatalogItemVariant;
|
selected_variant?: SelectedCatalogItemVariant;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
images?: string[];
|
images?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,8 +132,7 @@ export interface CatalogFeaturedItemVariant {
|
|||||||
id: number;
|
id: number;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string;
|
precio?: string;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
values: Record<string, CatalogVariantValue>;
|
values: Record<string, CatalogVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,8 +164,7 @@ export interface CatalogFeaturedItem {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
maximum_addable_quantity?: number | null;
|
availability: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
CatalogItemDetail,
|
CatalogItemDetail,
|
||||||
CatalogVariantOptionsResponse,
|
CatalogVariantOptionsResponse,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
|
Product,
|
||||||
} from './catalog.interface';
|
} from './catalog.interface';
|
||||||
|
|
||||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||||
@@ -32,6 +33,12 @@ export class CatalogService extends BaseApiService {
|
|||||||
return this.tenantService.getTenantApiUrl();
|
return this.tenantService.getTenantApiUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
|
||||||
|
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
|
||||||
|
params: this.buildHttpParams(params),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
||||||
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
|
||||||
import { CheckoutService } from './checkout.service';
|
import { CheckoutService } from './checkout.service';
|
||||||
|
|
||||||
describe('CheckoutService', () => {
|
describe('CheckoutService', () => {
|
||||||
@@ -39,59 +38,4 @@ describe('CheckoutService', () => {
|
|||||||
|
|
||||||
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refreshes catalog availability when starting checkout fails', async () => {
|
|
||||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
|
||||||
const notifyAvailabilityChanged = vi.spyOn(
|
|
||||||
catalogAvailabilityService,
|
|
||||||
'notifyAvailabilityChanged',
|
|
||||||
);
|
|
||||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
|
||||||
|
|
||||||
request.flush(
|
|
||||||
{ message: 'No hay stock disponible.' },
|
|
||||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(purchasePromise).rejects.toBeTruthy();
|
|
||||||
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
|
|
||||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
|
||||||
const notifyAvailabilityChanged = vi.spyOn(
|
|
||||||
catalogAvailabilityService,
|
|
||||||
'notifyAvailabilityChanged',
|
|
||||||
);
|
|
||||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
|
||||||
|
|
||||||
request.flush(
|
|
||||||
{
|
|
||||||
code: 'stock_reservation.expired',
|
|
||||||
message: 'La reserva de stock venció.',
|
|
||||||
},
|
|
||||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(purchasePromise).rejects.toBeTruthy();
|
|
||||||
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('preserves checkout timing fields when completing a purchase', async () => {
|
|
||||||
const purchasePromise = service.completePurchase('desfile', 55);
|
|
||||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
|
|
||||||
const response = {
|
|
||||||
status: 'pending_payment',
|
|
||||||
expires_at: '2026-08-26T20:00:00.000Z',
|
|
||||||
expires_in_seconds: 900,
|
|
||||||
server_time: '2026-08-26T19:45:00.000Z',
|
|
||||||
};
|
|
||||||
|
|
||||||
expect(request.request.method).toBe('POST');
|
|
||||||
request.flush({ data: response });
|
|
||||||
|
|
||||||
await expect(purchasePromise).resolves.toEqual(response);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||||
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -46,21 +45,6 @@ export function isInsufficientStockResponse(value: unknown): value is Insufficie
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExpiredStockReservationResponse {
|
|
||||||
code: 'stock_reservation.expired';
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isExpiredStockReservationResponse(
|
|
||||||
value: unknown,
|
|
||||||
): value is ExpiredStockReservationResponse {
|
|
||||||
return (
|
|
||||||
typeof value === 'object' &&
|
|
||||||
value !== null &&
|
|
||||||
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export type StartCheckoutPayload =
|
export type StartCheckoutPayload =
|
||||||
| {
|
| {
|
||||||
cart_id: number;
|
cart_id: number;
|
||||||
@@ -71,32 +55,6 @@ export type StartCheckoutPayload =
|
|||||||
|
|
||||||
export interface PurchaseStatusResponse {
|
export interface PurchaseStatusResponse {
|
||||||
status: string | null;
|
status: string | null;
|
||||||
expires_at: string | null;
|
|
||||||
expires_in_seconds: number | null;
|
|
||||||
server_time: string;
|
|
||||||
payment_verification?: PurchasePaymentVerificationResponse;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PurchasePaymentCandidateReason =
|
|
||||||
| 'ambiguous_exact_match'
|
|
||||||
| 'exact_dni_near_amount'
|
|
||||||
| 'exact_amount_near_dni';
|
|
||||||
|
|
||||||
export interface PurchasePaymentCandidatePrimaryResponse {
|
|
||||||
reason: PurchasePaymentCandidateReason;
|
|
||||||
dni_distance: number | null;
|
|
||||||
payment_amount: string;
|
|
||||||
purchase_amount: string;
|
|
||||||
amount_difference: string;
|
|
||||||
confidence: 'exact' | 'high' | 'medium';
|
|
||||||
detected_at: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PurchasePaymentVerificationResponse {
|
|
||||||
status: 'pending' | 'candidate';
|
|
||||||
candidate_count: number;
|
|
||||||
primary: PurchasePaymentCandidatePrimaryResponse | null;
|
|
||||||
reasons: PurchasePaymentCandidateReason[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
||||||
@@ -133,6 +91,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
user_id: number;
|
user_id: number;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
payment_method: string | null;
|
payment_method: string | null;
|
||||||
|
expires_at: string | null;
|
||||||
dni: string | null;
|
dni: string | null;
|
||||||
transfer_payer_dni: string | null;
|
transfer_payer_dni: string | null;
|
||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
@@ -150,34 +109,24 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CheckoutService extends BaseApiService {
|
export class CheckoutService extends BaseApiService {
|
||||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
|
||||||
|
|
||||||
async startCheckout(
|
async startCheckout(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
payload: StartCheckoutPayload,
|
payload: StartCheckoutPayload,
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
try {
|
const response = await firstValueFrom(
|
||||||
const response = await firstValueFrom(
|
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
payload,
|
||||||
payload,
|
),
|
||||||
),
|
);
|
||||||
);
|
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||||
|
|
||||||
if (!purchase?.id) {
|
if (!purchase?.id) {
|
||||||
throw new Error('Error al crear la compra.');
|
throw new Error('Error al crear la compra.');
|
||||||
}
|
|
||||||
|
|
||||||
return purchase;
|
|
||||||
} catch (error) {
|
|
||||||
const responseBody = (error as { error?: unknown } | null)?.error;
|
|
||||||
if (!isExpiredStockReservationResponse(responseBody)) {
|
|
||||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async generatePaymentIntent(
|
async generatePaymentIntent(
|
||||||
@@ -222,6 +171,25 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
||||||
|
{},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
||||||
|
|
||||||
|
if (!purchase) {
|
||||||
|
throw new Error('Error al finalizar la compra.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: purchase.status ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async submitPurchaseForReview(
|
async submitPurchaseForReview(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
@@ -238,7 +206,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
return { status: purchase.status ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
@@ -254,7 +222,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al cancelar la compra.');
|
throw new Error('Error al cancelar la compra.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
return { status: purchase.status ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPurchases(
|
async getPurchases(
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { StoreSectionComponent } from '../../../../shared/components/store-secti
|
|||||||
import { ModalService } from '../../../../core/services/modal.service';
|
import { ModalService } from '../../../../core/services/modal.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.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 { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
|
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
|
||||||
@@ -232,7 +233,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1001,
|
id: 1001,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -243,7 +244,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1002,
|
id: 1002,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -254,7 +255,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1003,
|
id: 1003,
|
||||||
precio: 250000,
|
precio: 250000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('c', 'Sector C'),
|
sector: ticketOption('c', 'Sector C'),
|
||||||
@@ -265,7 +266,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1004,
|
id: 1004,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -276,7 +277,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1005,
|
id: 1005,
|
||||||
precio: 200000,
|
precio: 200000,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
sector: ticketOption('a', 'Sector A'),
|
sector: ticketOption('a', 'Sector A'),
|
||||||
@@ -287,7 +288,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1006,
|
id: 1006,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -298,7 +299,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1007,
|
id: 1007,
|
||||||
precio: 100000,
|
precio: 100000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('b', 'Sector B'),
|
sector: ticketOption('b', 'Sector B'),
|
||||||
@@ -309,7 +310,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1008,
|
id: 1008,
|
||||||
precio: 90000,
|
precio: 90000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -320,7 +321,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1009,
|
id: 1009,
|
||||||
precio: 65000,
|
precio: 65000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
@@ -331,7 +332,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
{
|
{
|
||||||
id: 1010,
|
id: 1010,
|
||||||
precio: 40000,
|
precio: 40000,
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: ticketOption('general', 'General'),
|
tipo: ticketOption('general', 'General'),
|
||||||
sector: ticketOption('d', 'Sector D'),
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
[attr.aria-label]="option.label"
|
[attr.aria-label]="option.label"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[title]="option.label"
|
[title]="option.label"
|
||||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
<span class="visually-hidden">{{ option.label }}</span>
|
<span class="visually-hidden">{{ option.label }}</span>
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
!availableOptions()[attribute.codigo][option.id]
|
!availableOptions()[attribute.codigo][option.id]
|
||||||
"
|
"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
{{ option.label }}
|
{{ option.label }}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { beforeEach, describe, expect, it } from 'vitest';
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
|
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
||||||
|
|
||||||
describe('ProductAttributeSelectorComponent', () => {
|
describe('ProductAttributeSelectorComponent', () => {
|
||||||
@@ -31,7 +32,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -51,12 +52,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
values: { size: 'M' },
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -92,9 +93,9 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
|
{ id: 1, availability: createCatalogAvailability(null), values: { event_date: '1' } },
|
||||||
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
|
{ id: 2, availability: createCatalogAvailability(null), values: { event_date: '2' } },
|
||||||
{ id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
|
{ id: 3, availability: createCatalogAvailability(null), values: { event_date: ['1', '2'] } },
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
@@ -135,8 +136,16 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
|
{
|
||||||
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
|
id: 1,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
values: { size: 'S', internal_type: 'adult' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
values: { size: 'M', internal_type: 'child' },
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
ProductAttribute,
|
ProductAttribute,
|
||||||
ProductAttributeOption,
|
ProductAttributeOption,
|
||||||
} from '../../../../core/services/catalog/catalog.interface';
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
|
import { allowsCatalogAction } from '../../../../core/services/catalog/catalog-availability';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-attribute-selector',
|
selector: 'app-product-attribute-selector',
|
||||||
@@ -29,6 +30,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
public variants = input<CatalogItemVariant[]>([]);
|
public variants = input<CatalogItemVariant[]>([]);
|
||||||
public selectedVariant = input<CatalogItemVariant | null>(null);
|
public selectedVariant = input<CatalogItemVariant | null>(null);
|
||||||
public inventoryPolicy = input.required<InventoryPolicy>();
|
public inventoryPolicy = input.required<InventoryPolicy>();
|
||||||
|
public disabled = input(false);
|
||||||
|
|
||||||
public variantChange = output<CatalogItemVariant | null>();
|
public variantChange = output<CatalogItemVariant | null>();
|
||||||
|
|
||||||
@@ -51,22 +53,15 @@ export class ProductAttributeSelectorComponent {
|
|||||||
const optionNormalized = this.normalizeText(option.value || option.label);
|
const optionNormalized = this.normalizeText(option.value || option.label);
|
||||||
const selectedForAttribute = selections[attribute.codigo] ?? [];
|
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) => {
|
const isAvailable = variants.some((variant) => {
|
||||||
if (!this.isVariantAvailable(variant)) return false;
|
if (!this.isVariantAvailable(variant)) return false;
|
||||||
|
|
||||||
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||||
const desiredOptionIds = selectedForAttribute.includes(option.id)
|
const desiredOptionIds = attribute.allow_multi_select
|
||||||
? selectedForAttribute
|
? selectedForAttribute.includes(option.id)
|
||||||
: [...selectedForAttribute, option.id];
|
? selectedForAttribute
|
||||||
|
: [...selectedForAttribute, option.id]
|
||||||
|
: [option.id];
|
||||||
const desiredValues = desiredOptionIds
|
const desiredValues = desiredOptionIds
|
||||||
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
||||||
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||||
@@ -137,6 +132,8 @@ export class ProductAttributeSelectorComponent {
|
|||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
option: ProductAttributeOption,
|
option: ProductAttributeOption,
|
||||||
): void {
|
): void {
|
||||||
|
if (this.disabled()) return;
|
||||||
|
|
||||||
this.selectedAttributeOptions.update((current) => {
|
this.selectedAttributeOptions.update((current) => {
|
||||||
const selected = current[attribute.codigo] ?? [];
|
const selected = current[attribute.codigo] ?? [];
|
||||||
const isMultiple = attribute.allow_multi_select ?? false;
|
const isMultiple = attribute.allow_multi_select ?? false;
|
||||||
@@ -186,7 +183,15 @@ export class ProductAttributeSelectorComponent {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
|
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);
|
||||||
if (defaultValues.length === 0) {
|
if (defaultValues.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -215,6 +220,17 @@ 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 [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +243,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return variant.maximum_addable_quantity !== 0;
|
return allowsCatalogAction(variant.availability, 'select_variant');
|
||||||
}
|
}
|
||||||
|
|
||||||
private findFirstHexValue(value: unknown): string | null {
|
private findFirstHexValue(value: unknown): string | null {
|
||||||
|
|||||||
@@ -23,10 +23,7 @@ import {
|
|||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import {
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../../../core/services/checkout.service';
|
|
||||||
import {
|
import {
|
||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
@@ -170,20 +167,10 @@ export class CategoryItemsPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra directa.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,7 +34,6 @@
|
|||||||
[qrPaymentAmount]="cartTotal()"
|
[qrPaymentAmount]="cartTotal()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[transferValidationStatus]="transferValidationStatus()"
|
[transferValidationStatus]="transferValidationStatus()"
|
||||||
[transferVerificationErrorTitle]="transferVerificationErrorTitle()"
|
|
||||||
(paymentMethodChange)="selectPaymentMethod($event)"
|
(paymentMethodChange)="selectPaymentMethod($event)"
|
||||||
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
||||||
(cancelStep)="onCancel()"
|
(cancelStep)="onCancel()"
|
||||||
@@ -47,17 +46,6 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="checkout-page__cart-col">
|
<div class="checkout-page__cart-col">
|
||||||
@if (checkoutRemainingTime(); as remainingTime) {
|
|
||||||
<div
|
|
||||||
class="checkout-page__mobile-countdown d-flex d-md-none align-items-baseline justify-content-center gap-3"
|
|
||||||
role="timer"
|
|
||||||
aria-label="Tiempo restante de compra"
|
|
||||||
>
|
|
||||||
<span class="checkout-page__mobile-countdown-label">Tiempo restante de compra:</span>
|
|
||||||
<span class="checkout-page__mobile-countdown-value">{{ remainingTime }}</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
<app-cart
|
<app-cart
|
||||||
title="COMPRA"
|
title="COMPRA"
|
||||||
[items]="mappedCartItems()"
|
[items]="mappedCartItems()"
|
||||||
|
|||||||
@@ -28,24 +28,6 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__mobile-countdown {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
color: var(--tenant-primary);
|
|
||||||
font-weight: 700;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
&__mobile-countdown-label {
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
&__mobile-countdown-value {
|
|
||||||
font-size: 20px;
|
|
||||||
line-height: 1;
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.checkout-page__loading {
|
.checkout-page__loading {
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
|||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
describe('CheckoutPageComponent payment validation', () => {
|
describe('CheckoutPageComponent payment validation', () => {
|
||||||
@@ -34,7 +33,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
stop: ReturnType<typeof vi.fn>;
|
stop: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
||||||
let routeParamMap: ReturnType<typeof convertToParamMap>;
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
let tenantState: ReturnType<
|
let tenantState: ReturnType<
|
||||||
typeof signal<{
|
typeof signal<{
|
||||||
@@ -77,7 +76,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
cartServiceStub = {
|
cartServiceStub = {
|
||||||
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
||||||
};
|
};
|
||||||
routeParamMap = convertToParamMap({});
|
routeQueryParamMap = convertToParamMap({});
|
||||||
authUserState = signal(null);
|
authUserState = signal(null);
|
||||||
tenantState = signal({
|
tenantState = signal({
|
||||||
codigo: 'tenant-test',
|
codigo: 'tenant-test',
|
||||||
@@ -104,8 +103,8 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
snapshot: {
|
snapshot: {
|
||||||
get paramMap() {
|
get queryParamMap() {
|
||||||
return routeParamMap;
|
return routeQueryParamMap;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -130,35 +129,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
return { fixture, component: fixture.componentInstance as any };
|
return { fixture, component: fixture.componentInstance as any };
|
||||||
}
|
}
|
||||||
|
|
||||||
it('does not expose an active countdown until the purchase timing is loaded', async () => {
|
|
||||||
const countdown = TestBed.inject(CheckoutCountdownService);
|
|
||||||
countdown.synchronize({
|
|
||||||
expires_at: null,
|
|
||||||
expires_in_seconds: 600,
|
|
||||||
server_time: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
|
||||||
id: 25,
|
|
||||||
status: 'created',
|
|
||||||
expires_at: '2026-08-27T15:10:00.000Z',
|
|
||||||
expires_in_seconds: 600,
|
|
||||||
server_time: '2026-08-27T15:00:00.000Z',
|
|
||||||
items: [],
|
|
||||||
subtotal: '0.00',
|
|
||||||
total: '0.00',
|
|
||||||
});
|
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
|
||||||
|
|
||||||
const { component } = createComponent();
|
|
||||||
|
|
||||||
expect(component.checkoutRemainingTime()).toBeNull();
|
|
||||||
|
|
||||||
await Promise.resolve();
|
|
||||||
|
|
||||||
expect(countdown.remainingSeconds()).toBe(600);
|
|
||||||
expect(component.checkoutRemainingTime()).toBe('10:00');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('polls QR after five seconds and navigates only when payment is paid', async () => {
|
it('polls QR after five seconds and navigates only when payment is paid', async () => {
|
||||||
checkoutServiceStub.getPurchase
|
checkoutServiceStub.getPurchase
|
||||||
.mockResolvedValueOnce({ status: 'pending_payment' })
|
.mockResolvedValueOnce({ status: 'pending_payment' })
|
||||||
@@ -225,7 +195,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('polls a transfer every three seconds for one minute', async () => {
|
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
@@ -235,12 +205,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(57_000);
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19);
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
expect(component.transferValidationStatus()).toBe('checking');
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
||||||
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
|
}
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(3_000);
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
@@ -284,43 +256,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
await vi.advanceTimersByTimeAsync(60_000);
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses the primary candidate reason when transfer polling times out', async () => {
|
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
|
||||||
status: 'in_review',
|
|
||||||
payment_verification: {
|
|
||||||
status: 'candidate',
|
|
||||||
candidate_count: 1,
|
|
||||||
primary: {
|
|
||||||
reason: 'exact_amount_near_dni',
|
|
||||||
dni_distance: 1,
|
|
||||||
payment_amount: '300000.00',
|
|
||||||
purchase_amount: '300000.00',
|
|
||||||
amount_difference: '0.00',
|
|
||||||
confidence: 'medium',
|
|
||||||
detected_at: '2026-08-27T18:00:00-03:00',
|
|
||||||
},
|
|
||||||
reasons: ['exact_amount_near_dni'],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const { component } = createComponent();
|
|
||||||
component.selectedPaymentMethod.set('transfer');
|
|
||||||
|
|
||||||
await component.onComplete();
|
|
||||||
await vi.advanceTimersByTimeAsync(60_000);
|
|
||||||
|
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
|
||||||
expect(component.transferVerificationErrorTitle()).toBe(
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not poll when submitting a transfer for review fails', async () => {
|
it('does not poll when submitting a transfer for review fails', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
||||||
@@ -375,7 +317,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
subtotal: '2501.00',
|
subtotal: '2501.00',
|
||||||
total: '2501.00',
|
total: '2501.00',
|
||||||
};
|
};
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
||||||
authUserState.set({
|
authUserState.set({
|
||||||
id: 7,
|
id: 7,
|
||||||
@@ -412,7 +354,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
it('keeps the checkout hidden while the purchase is loading', async () => {
|
it('keeps the checkout hidden while the purchase is loading', async () => {
|
||||||
let resolvePurchase!: (purchase: any) => void;
|
let resolvePurchase!: (purchase: any) => void;
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockReturnValue(
|
checkoutServiceStub.getPurchase.mockReturnValue(
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
resolvePurchase = resolve;
|
resolvePurchase = resolve;
|
||||||
@@ -433,13 +375,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
|
||||||
expect(component.isLoadingPurchase()).toBe(false);
|
expect(component.isLoadingPurchase()).toBe(false);
|
||||||
expect(component.checkoutStepIndex()).toBe(0);
|
expect(component.checkoutStepIndex()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -459,7 +400,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('generates a new QR when reopening a pending QR purchase', async () => {
|
it('generates a new QR when reopening a pending QR purchase', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -483,7 +424,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
||||||
'redirects a %s purchase to its status page',
|
'redirects a %s purchase to its status page',
|
||||||
async (status) => {
|
async (status) => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status,
|
status,
|
||||||
@@ -501,7 +442,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
it('redirects a submitted pending payment purchase to its status page', async () => {
|
it('redirects a submitted pending payment purchase to its status page', async () => {
|
||||||
routeParamMap = convertToParamMap({ id: 25 });
|
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -519,7 +460,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
|
it('shows the API error in a toast when cancelling the purchase fails', async () => {
|
||||||
const message = 'La compra venció. Iniciá una nueva compra.';
|
const message = 'La compra venció. Iniciá una nueva compra.';
|
||||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||||
error: { code: 'purchase.expired', message },
|
error: { code: 'purchase.expired', message },
|
||||||
@@ -529,9 +470,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
await component.onModifyPurchase();
|
await component.onModifyPurchase();
|
||||||
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
expect(component.isCancellingPurchase()).toBe(false);
|
expect(component.isCancellingPurchase()).toBe(false);
|
||||||
@@ -648,24 +587,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.createdPurchaseId()).toBe(25);
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows leaving checkout when cancellation finds an expired stock reservation', async () => {
|
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => {
|
||||||
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
|
||||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
|
||||||
error: { code: 'stock_reservation.expired', message },
|
|
||||||
});
|
|
||||||
const { component } = createComponent();
|
|
||||||
|
|
||||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
|
||||||
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
|
||||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
|
||||||
expect(component.createdPurchase()).toBeNull();
|
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the API message and redirects to status when a checkout operation finds an expired purchase', async () => {
|
|
||||||
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
||||||
new HttpErrorResponse({
|
new HttpErrorResponse({
|
||||||
status: 422,
|
status: 422,
|
||||||
@@ -682,35 +604,10 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(component.isGeneratingIntent()).toBe(false);
|
expect(component.isGeneratingIntent()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('redirects to status when QR polling receives a purchase-expired response', async () => {
|
|
||||||
checkoutServiceStub.getPurchase.mockRejectedValue(
|
|
||||||
new HttpErrorResponse({
|
|
||||||
status: 422,
|
|
||||||
error: {
|
|
||||||
code: 'purchase.expired',
|
|
||||||
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const { component } = createComponent();
|
|
||||||
|
|
||||||
await component.selectPaymentMethod('qr');
|
|
||||||
await vi.advanceTimersByTimeAsync(5_000);
|
|
||||||
|
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.createdPurchase.set({
|
component.createdPurchase.set({
|
||||||
@@ -738,8 +635,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -16,10 +16,8 @@ import { firstValueFrom, startWith } from 'rxjs';
|
|||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchasePaymentCandidateReason,
|
|
||||||
PurchaseDetailItemResponse,
|
PurchaseDetailItemResponse,
|
||||||
PurchaseDetailResponse,
|
PurchaseDetailResponse,
|
||||||
PurchaseStatusResponse,
|
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||||
@@ -30,7 +28,6 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
|
|||||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||||
import { CheckoutDataStepComponent } from './checkout-data-step.component';
|
import { CheckoutDataStepComponent } from './checkout-data-step.component';
|
||||||
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
|
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
|
||||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
|
||||||
import {
|
import {
|
||||||
CheckoutForm,
|
CheckoutForm,
|
||||||
PaymentMethod,
|
PaymentMethod,
|
||||||
@@ -67,7 +64,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly globalLoadingService = inject(GlobalLoadingService);
|
private readonly globalLoadingService = inject(GlobalLoadingService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
@@ -75,7 +71,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
private readonly qrPollingMaxAttempts = 120;
|
private readonly qrPollingMaxAttempts = 120;
|
||||||
private readonly transferPollingIntervalMs = 3_000;
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
private readonly transferPollingMaxAttempts = 20;
|
private readonly transferPollingMaxAttempts = 209;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
@@ -99,27 +95,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||||
protected readonly isLoadingPurchase = signal(true);
|
protected readonly isLoadingPurchase = signal(true);
|
||||||
protected readonly checkoutStepIndex = signal(0);
|
protected readonly checkoutStepIndex = signal(0);
|
||||||
protected readonly checkoutRemainingTime = computed(() => {
|
|
||||||
const purchase = this.createdPurchase();
|
|
||||||
|
|
||||||
if (
|
|
||||||
!purchase ||
|
|
||||||
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
|
|
||||||
) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
|
||||||
|
|
||||||
if (remainingSeconds === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const minutes = Math.floor(remainingSeconds / 60);
|
|
||||||
const seconds = remainingSeconds % 60;
|
|
||||||
|
|
||||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
|
||||||
});
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
return purchase ? parseFloat(purchase.subtotal) : 0;
|
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||||
@@ -160,14 +135,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
||||||
protected readonly isCheckingQrPayment = signal(false);
|
protected readonly isCheckingQrPayment = signal(false);
|
||||||
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
||||||
private readonly transferPrimaryCandidateReason = signal<PurchasePaymentCandidateReason | null>(
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
protected readonly transferVerificationErrorTitle = computed(() =>
|
|
||||||
this.transferPrimaryCandidateReason() === 'exact_amount_near_dni'
|
|
||||||
? 'El DNI no corresponde con el de la transferencia'
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
protected readonly whatsappUrl = computed(
|
protected readonly whatsappUrl = computed(
|
||||||
() =>
|
() =>
|
||||||
this.tenantService
|
this.tenantService
|
||||||
@@ -194,7 +161,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
|
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
|
||||||
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
return;
|
return;
|
||||||
@@ -261,7 +228,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
nombre_apellido: formValue.nombre,
|
nombre_apellido: formValue.nombre,
|
||||||
});
|
});
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
|
|
||||||
this.stepper.next();
|
this.stepper.next();
|
||||||
|
|
||||||
@@ -315,7 +281,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
if (!tenant || !purchaseId) {
|
if (!tenant || !purchaseId) {
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,25 +291,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
await firstValueFrom(this.cartService.loadCart());
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
this.createdPurchaseId.set(null);
|
this.createdPurchaseId.set(null);
|
||||||
this.createdPurchase.set(null);
|
this.createdPurchase.set(null);
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
|
|
||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to cancel the current purchase:', error);
|
console.error('Failed to cancel the current purchase:', error);
|
||||||
|
|
||||||
if (this.isStockReservationExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La reserva de stock venció.');
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
this.createdPurchaseId.set(null);
|
|
||||||
this.createdPurchase.set(null);
|
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
this.navigationStarted = true;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -419,7 +370,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.transferDni.set(dni);
|
this.transferDni.set(dni);
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.transferPrimaryCandidateReason.set(null);
|
|
||||||
this.isGeneratingIntent.set(true);
|
this.isGeneratingIntent.set(true);
|
||||||
try {
|
try {
|
||||||
const response = await this.checkoutService
|
const response = await this.checkoutService
|
||||||
@@ -476,7 +426,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.hasSubmittedTransfer.set(true);
|
this.hasSubmittedTransfer.set(true);
|
||||||
this.transferValidationStatus.set('checking');
|
this.transferValidationStatus.set('checking');
|
||||||
this.transferPrimaryCandidateReason.set(null);
|
|
||||||
this.transferPollingAttempts = 0;
|
this.transferPollingAttempts = 0;
|
||||||
|
|
||||||
const runId = this.transferPollingRunId;
|
const runId = this.transferPollingRunId;
|
||||||
@@ -490,9 +439,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.captureTransferCandidateReason(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -542,24 +488,12 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.captureTransferCandidateReason(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (purchase.status === 'expired') {
|
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate transfer payment:', error);
|
console.error('Failed to validate transfer payment:', error);
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (runId !== this.transferPollingRunId) {
|
if (runId !== this.transferPollingRunId) {
|
||||||
@@ -575,14 +509,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.scheduleTransferPoll(runId);
|
this.scheduleTransferPoll(runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
|
|
||||||
const reason = purchase.payment_verification?.primary?.reason;
|
|
||||||
|
|
||||||
if (reason) {
|
|
||||||
this.transferPrimaryCandidateReason.set(reason);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopTransferPolling(): void {
|
private stopTransferPolling(): void {
|
||||||
this.transferPollingRunId += 1;
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
@@ -639,8 +565,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.handleConfirmedPayment(purchaseId);
|
this.handleConfirmedPayment(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -651,17 +575,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.qrPaymentStatus.set('failed');
|
this.qrPaymentStatus.set('failed');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (purchase.status === 'expired') {
|
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate QR payment:', error);
|
console.error('Failed to validate QR payment:', error);
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
|
||||||
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
if (runId === this.qrPollingRunId) {
|
if (runId === this.qrPollingRunId) {
|
||||||
this.isCheckingQrPayment.set(false);
|
this.isCheckingQrPayment.set(false);
|
||||||
@@ -714,7 +629,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||||
}
|
}
|
||||||
@@ -752,7 +666,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.createdPurchaseId.set(purchase.id);
|
this.createdPurchaseId.set(purchase.id);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
this.checkoutCountdownService.synchronize(purchase);
|
|
||||||
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -770,17 +683,15 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load purchase:', error);
|
console.error('Failed to load purchase:', error);
|
||||||
const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
|
this.showRequestError(error, 'No se pudo cargar la compra.');
|
||||||
if (!expired) {
|
void this.router.navigate(['/']);
|
||||||
void this.router.navigate(['/']);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private showRequestError(error: unknown, fallbackMessage: string): boolean {
|
private showRequestError(error: unknown, fallbackMessage: string): void {
|
||||||
const payload =
|
const payload =
|
||||||
typeof error === 'object' && error !== null && 'error' in error
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
? (error as { error?: ApiErrorResponse }).error
|
? (error as { error?: { message?: unknown } }).error
|
||||||
: undefined;
|
: undefined;
|
||||||
const message =
|
const message =
|
||||||
typeof payload?.message === 'string' && payload.message.trim()
|
typeof payload?.message === 'string' && payload.message.trim()
|
||||||
@@ -788,13 +699,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
: fallbackMessage;
|
: fallbackMessage;
|
||||||
|
|
||||||
this.toastService.danger(message);
|
this.toastService.danger(message);
|
||||||
|
|
||||||
if (payload?.code === 'purchase.expired') {
|
|
||||||
this.navigateToExpiredPurchaseStatus();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
||||||
@@ -813,7 +717,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
? response.message
|
? response.message
|
||||||
: 'La compra venció. Iniciá una nueva compra.',
|
: 'La compra venció. Iniciá una nueva compra.',
|
||||||
);
|
);
|
||||||
this.navigateToExpiredPurchaseStatus();
|
void this.router.navigate(['/']);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,43 +729,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private navigateToExpiredPurchaseStatus(): void {
|
|
||||||
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
|
|
||||||
|
|
||||||
if (purchaseId) {
|
|
||||||
if (this.navigationStarted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.navigationStarted = true;
|
|
||||||
this.stopQrPolling();
|
|
||||||
this.stopTransferPolling();
|
|
||||||
this.checkoutCountdownService.clear();
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId], {
|
|
||||||
queryParams: { status: 'expired' },
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.router.navigate(['/']);
|
|
||||||
}
|
|
||||||
|
|
||||||
private isPurchaseExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: ApiErrorResponse }).error?.code === 'purchase.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
private isStockReservationExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: ApiErrorResponse }).error?.code === 'stock_reservation.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasExpiredPurchase(): boolean {
|
private hasExpiredPurchase(): boolean {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,6 @@
|
|||||||
[validationStatus]="transferValidationStatus()"
|
[validationStatus]="transferValidationStatus()"
|
||||||
[paymentAmount]="qrPaymentAmount()"
|
[paymentAmount]="qrPaymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[verificationErrorTitle]="transferVerificationErrorTitle()"
|
|
||||||
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
||||||
(submitDni)="generateTransferIntent.emit($event)"
|
(submitDni)="generateTransferIntent.emit($event)"
|
||||||
(completePurchase)="complete.emit()"
|
(completePurchase)="complete.emit()"
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ export class CheckoutPaymentStepComponent {
|
|||||||
readonly qrPaymentAmount = input<number>(0);
|
readonly qrPaymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
||||||
readonly transferVerificationErrorTitle = input<string | null>(null);
|
|
||||||
|
|
||||||
readonly paymentMethodChange = output<PaymentMethod>();
|
readonly paymentMethodChange = output<PaymentMethod>();
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
<app-payment-verification-error
|
<app-payment-verification-error
|
||||||
[paymentAmount]="paymentAmount()"
|
[paymentAmount]="paymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[title]="verificationErrorTitle()"
|
|
||||||
/>
|
/>
|
||||||
} @else {
|
} @else {
|
||||||
<div class="dni-form-container">
|
<div class="dni-form-container">
|
||||||
|
|||||||
@@ -47,23 +47,4 @@ describe('CheckoutPaymentTransferComponent', () => {
|
|||||||
expect(whatsapp).toBeDefined();
|
expect(whatsapp).toBeDefined();
|
||||||
expect(element.querySelector('.payment-verification')).toBeNull();
|
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows a custom validation title for a near DNI candidate', async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [CheckoutPaymentTransferComponent],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
|
||||||
fixture.componentRef.setInput('validationStatus', 'error');
|
|
||||||
fixture.componentRef.setInput(
|
|
||||||
'verificationErrorTitle',
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'El DNI no corresponde con el de la transferencia',
|
|
||||||
);
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ export class CheckoutPaymentTransferComponent implements OnInit {
|
|||||||
readonly validationStatus = input<TransferValidationStatus>('idle');
|
readonly validationStatus = input<TransferValidationStatus>('idle');
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly verificationErrorTitle = input<string | null>(null);
|
|
||||||
|
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
readonly submitDni = output<string>();
|
readonly submitDni = output<string>();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<div class="payment-timeout__icon" aria-hidden="true">
|
<div class="payment-timeout__icon" aria-hidden="true">
|
||||||
<i class="fa-solid fa-xmark"></i>
|
<i class="fa-solid fa-xmark"></i>
|
||||||
</div>
|
</div>
|
||||||
<h4 class="payment-timeout__title">{{ displayTitle() }}</h4>
|
<h4 class="payment-timeout__title">No pudimos verificar el pago de {{ formattedAmount() }}.</h4>
|
||||||
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
||||||
@if (whatsappUrl()) {
|
@if (whatsappUrl()) {
|
||||||
<app-button
|
<app-button
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import { ButtonComponent } from '../../../../../../shared/components/button/butt
|
|||||||
export class PaymentVerificationErrorComponent {
|
export class PaymentVerificationErrorComponent {
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly title = input<string | null>(null);
|
|
||||||
|
|
||||||
protected readonly formattedAmount = computed(() =>
|
protected readonly formattedAmount = computed(() =>
|
||||||
new Intl.NumberFormat('es-AR', {
|
new Intl.NumberFormat('es-AR', {
|
||||||
@@ -22,9 +21,6 @@ export class PaymentVerificationErrorComponent {
|
|||||||
maximumFractionDigits: 0,
|
maximumFractionDigits: 0,
|
||||||
}).format(this.paymentAmount()),
|
}).format(this.paymentAmount()),
|
||||||
);
|
);
|
||||||
protected readonly displayTitle = computed(
|
|
||||||
() => this.title() ?? `No pudimos verificar el pago de ${this.formattedAmount()}.`,
|
|
||||||
);
|
|
||||||
|
|
||||||
protected openWhatsApp(): void {
|
protected openWhatsApp(): void {
|
||||||
const url = this.whatsappUrl();
|
const url = this.whatsappUrl();
|
||||||
|
|||||||
@@ -44,6 +44,7 @@
|
|||||||
[variants]="prod.variants"
|
[variants]="prod.variants"
|
||||||
[selectedVariant]="prod.selected_variant ?? null"
|
[selectedVariant]="prod.selected_variant ?? null"
|
||||||
[inventoryPolicy]="prod.inventory_policy"
|
[inventoryPolicy]="prod.inventory_policy"
|
||||||
|
[disabled]="!allows(prod.availability, 'select_variant')"
|
||||||
(variantChange)="onVariantChange($event)"
|
(variantChange)="onVariantChange($event)"
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
@@ -53,14 +54,22 @@
|
|||||||
|
|
||||||
<section class="product-detail__section">
|
<section class="product-detail__section">
|
||||||
<div class="product-detail__purchase">
|
<div class="product-detail__purchase">
|
||||||
<app-quantity-selector [(quantity)]="quantity" [max]="selectedVariantMax()" />
|
@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')"
|
||||||
|
/>
|
||||||
|
|
||||||
<div class="product-detail__actions">
|
<div class="product-detail__actions">
|
||||||
<app-button
|
<app-button
|
||||||
class="product-detail__cta"
|
class="product-detail__cta"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
[disabled]="!canAddToCart() || variantLoading() || addingToCart()"
|
||||||
(click)="addToCart()"
|
(click)="addToCart()"
|
||||||
>
|
>
|
||||||
@if (addingToCart()) {
|
@if (addingToCart()) {
|
||||||
@@ -75,9 +84,7 @@
|
|||||||
<app-button
|
<app-button
|
||||||
class="product-detail__cta"
|
class="product-detail__cta"
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="
|
[disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
|
||||||
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
|
|
||||||
"
|
|
||||||
(click)="buyNow()"
|
(click)="buyNow()"
|
||||||
>
|
>
|
||||||
@if (variantLoading() || creatingDirectPurchase()) {
|
@if (variantLoading() || creatingDirectPurchase()) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.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 { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { ProductDetailPageComponent } from './product-detail-page.component';
|
import { ProductDetailPageComponent } from './product-detail-page.component';
|
||||||
@@ -38,7 +39,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
@@ -179,7 +180,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
it('reloads product availability when the cart changes', async () => {
|
it('reloads product availability when the cart changes', async () => {
|
||||||
catalogServiceStub.getCatalogItem.mockReturnValue(
|
catalogServiceStub.getCatalogItem.mockReturnValue(
|
||||||
of({ ...mockProduct, maximum_addable_quantity: 4 }),
|
of({ ...mockProduct, availability: createCatalogAvailability(4) }),
|
||||||
);
|
);
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||||
@@ -192,6 +193,21 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
|
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 () => {
|
it('shows error message if the resolver cannot load the product', async () => {
|
||||||
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -207,10 +223,10 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
const detailProduct: CatalogItemDetail = {
|
const detailProduct: CatalogItemDetail = {
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
images: ['https://example.com/product.png'],
|
images: ['https://example.com/product.png'],
|
||||||
variants: [{ id: 123, maximum_addable_quantity: 10, values: {} }],
|
variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -312,11 +328,15 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 123, maximum_addable_quantity: 10, values: { color: 'beige', material: 'Cuero' } },
|
{
|
||||||
|
id: 123,
|
||||||
|
availability: createCatalogAvailability(10),
|
||||||
|
values: { color: 'beige', material: 'Cuero' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
images: ['https://example.com/variant1.png'],
|
images: ['https://example.com/variant1.png'],
|
||||||
values: {
|
values: {
|
||||||
color: 'beige',
|
color: 'beige',
|
||||||
@@ -353,8 +373,18 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
purpose: 'entry',
|
purpose: 'entry',
|
||||||
has_tickets: true,
|
has_tickets: true,
|
||||||
variants: [
|
variants: [
|
||||||
{ 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' } },
|
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' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
attributes: [
|
attributes: [
|
||||||
{
|
{
|
||||||
@@ -385,7 +415,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 101,
|
id: 101,
|
||||||
event_date_id: 20,
|
event_date_id: 20,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -407,6 +437,8 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
options[1].click();
|
options[1].click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
|
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
|
||||||
});
|
});
|
||||||
@@ -429,7 +461,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
|
|
||||||
fixture.componentInstance['selectedVariant'].set({
|
fixture.componentInstance['selectedVariant'].set({
|
||||||
id: 1,
|
id: 1,
|
||||||
maximum_addable_quantity: 10,
|
availability: createCatalogAvailability(10),
|
||||||
values: {},
|
values: {},
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -507,7 +539,9 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
|
||||||
|
queryParams: { purchase: 44 },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||||
@@ -517,7 +551,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
error: {
|
error: {
|
||||||
code: 'purchase.limit_exceeded',
|
code: 'purchase.limit_exceeded',
|
||||||
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -542,13 +576,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -581,7 +615,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
variants: [],
|
variants: [],
|
||||||
maximum_addable_quantity: 4,
|
availability: createCatalogAvailability(4),
|
||||||
});
|
});
|
||||||
|
|
||||||
await configureTestingModule();
|
await configureTestingModule();
|
||||||
@@ -607,13 +641,13 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 123,
|
id: 123,
|
||||||
maximum_addable_quantity: 5,
|
availability: createCatalogAvailability(5),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -645,7 +679,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 321,
|
id: 321,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -653,7 +687,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
inventory_policy: 'unlimited',
|
inventory_policy: 'unlimited',
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 321,
|
id: 321,
|
||||||
maximum_addable_quantity: null,
|
availability: createCatalogAvailability(null),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
@@ -677,7 +711,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
||||||
const unlimitedVariant = {
|
const unlimitedVariant = {
|
||||||
id: 322,
|
id: 322,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
@@ -686,7 +720,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
max_units_per_user: 2,
|
max_units_per_user: 2,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 322,
|
id: 322,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
images: [],
|
images: [],
|
||||||
values: { event_date: '20' },
|
values: { event_date: '20' },
|
||||||
},
|
},
|
||||||
@@ -710,14 +744,14 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
it('disables purchase actions for tracked variants without stock', async () => {
|
it('disables purchase actions for tracked variants without stock', async () => {
|
||||||
const trackedVariant = {
|
const trackedVariant = {
|
||||||
id: 654,
|
id: 654,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: {},
|
values: {},
|
||||||
};
|
};
|
||||||
resolveProduct({
|
resolveProduct({
|
||||||
...mockProduct,
|
...mockProduct,
|
||||||
selected_variant: {
|
selected_variant: {
|
||||||
id: 654,
|
id: 654,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
images: [],
|
images: [],
|
||||||
values: {},
|
values: {},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -32,6 +32,13 @@ import { ProductDetailResolvedData } from './product-detail-page.resolver';
|
|||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
|
import {
|
||||||
|
AVAILABLE_CATALOG_AVAILABILITY,
|
||||||
|
allowsCatalogAction,
|
||||||
|
combineCatalogAvailability,
|
||||||
|
maximumCatalogQuantity,
|
||||||
|
primaryAvailabilityMessage,
|
||||||
|
} from '../../../../core/services/catalog/catalog-availability';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-detail-page',
|
selector: 'app-product-detail-page',
|
||||||
@@ -96,29 +103,41 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
||||||
);
|
);
|
||||||
protected readonly quantity = signal(1);
|
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>(() => {
|
protected readonly selectedVariantMax = computed<number | null>(() => {
|
||||||
const prod = this.product();
|
const prod = this.product();
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!prod) return 0;
|
if (!prod) return 0;
|
||||||
|
if (!variant && prod.variants.length > 0) return 0;
|
||||||
|
|
||||||
return variant
|
return maximumCatalogQuantity(this.effectiveAvailability());
|
||||||
? (variant.maximum_addable_quantity ?? null)
|
|
||||||
: prod.variants.length === 0
|
|
||||||
? (prod.maximum_addable_quantity ?? null)
|
|
||||||
: 0;
|
|
||||||
});
|
});
|
||||||
protected readonly selectedVariantAvailable = computed(() => {
|
protected readonly hasPurchasableSelection = computed(() => {
|
||||||
const prod = this.product();
|
const prod = this.product();
|
||||||
if (!prod) return false;
|
if (!prod) return false;
|
||||||
if (this.selectedVariantMax() === 0) return false;
|
|
||||||
|
|
||||||
const variant = this.selectedVariant();
|
return prod.variants.length === 0 || this.selectedVariant() !== null;
|
||||||
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 descriptionExpanded = signal(false);
|
||||||
protected readonly descriptionMaxHeight = signal(0);
|
protected readonly descriptionMaxHeight = signal(0);
|
||||||
protected readonly descriptionHasOverflow = signal(false);
|
protected readonly descriptionHasOverflow = signal(false);
|
||||||
@@ -224,8 +243,12 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
this.quantity.set(Math.max(1, maximum));
|
this.quantity.set(Math.max(1, maximum));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: () => {
|
error: (error: HttpErrorResponse) => {
|
||||||
// Keep the last known availability if the silent refresh fails.
|
if (error.status === 404) {
|
||||||
|
this.product.set(null);
|
||||||
|
this.selectedVariant.set(null);
|
||||||
|
this.error.set('Este producto ya no está disponible.');
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -295,8 +318,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
protected addToCart(): void {
|
protected addToCart(): void {
|
||||||
const currentProduct = this.product();
|
const currentProduct = this.product();
|
||||||
const variant = this.selectedVariant();
|
const variant = this.selectedVariant();
|
||||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
if (!currentProduct || !this.canAddToCart()) {
|
||||||
this.toastService.danger('Por favor, selecciona una variante.');
|
this.toastService.danger(
|
||||||
|
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,8 +351,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
if (!currentProduct || !this.canBuyNow()) {
|
||||||
this.toastService.danger('Por favor, selecciona una variante.');
|
this.toastService.danger(
|
||||||
|
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,7 +385,9 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], {
|
||||||
|
queryParams: { purchase: purchase.id },
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
const message =
|
const message =
|
||||||
@@ -371,10 +400,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
|
||||||
return variant.maximum_addable_quantity !== 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleDescription(): void {
|
protected toggleDescription(): void {
|
||||||
this.descriptionExpanded.update((current) => !current);
|
this.descriptionExpanded.update((current) => !current);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|||||||
|
|
||||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
|
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||||
import {
|
import {
|
||||||
PRODUCT_DETAIL_ERROR_MESSAGE,
|
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||||
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||||
@@ -29,7 +30,7 @@ describe('productDetailResolver', () => {
|
|||||||
has_tickets: false,
|
has_tickets: false,
|
||||||
minimum_use_date: null,
|
minimum_use_date: null,
|
||||||
maximum_use_date: null,
|
maximum_use_date: null,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
attributes: [],
|
attributes: [],
|
||||||
variants: [],
|
variants: [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,9 +17,7 @@
|
|||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
@if (ticketsRoute()) {
|
@if (ticketsRoute()) {
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">A continuación, vas a poder ver los tickets que debés presentar en el evento.</p>
|
||||||
A continuación, vas a poder ver los tickets que debés presentar en el evento.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -31,9 +29,7 @@
|
|||||||
<span>Mis tickets</span>
|
<span>Mis tickets</span>
|
||||||
</app-button>
|
</app-button>
|
||||||
} @else if (whatsappUrl()) {
|
} @else if (whatsappUrl()) {
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Comunicate con nosotros para coordinar el envío.</p>
|
||||||
Comunicate con nosotros para coordinar el envío.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -55,21 +51,13 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">Tu compra ya fue registrada y estamos esperando la confirmación del pago.</p>
|
||||||
Tu compra ya fue registrada y estamos esperando la confirmación del pago.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
@if (paymentIssueMessage()) {
|
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
||||||
<p class="status-content__message">
|
|
||||||
{{ paymentIssueMessage() }} Estamos revisando el pago.
|
|
||||||
</p>
|
|
||||||
} @else {
|
|
||||||
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
} @else if (status() === 'expired') {
|
} @else if (status() === 'expired') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
@@ -77,17 +65,13 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">El plazo de pago terminó y liberamos el stock reservado.</p>
|
||||||
El plazo de pago terminó y liberamos el stock reservado.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Podés volver a la tienda e iniciar una nueva compra.</p>
|
||||||
Podés volver a la tienda e iniciar una nueva compra.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
} @else if (status() === 'rejected') {
|
} @else if (status() === 'rejected') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
@@ -95,9 +79,7 @@
|
|||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
||||||
<p class="status-content__subtitle">
|
<p class="status-content__subtitle">Revisá el medio de pago o comunicate con nosotros para continuar.</p>
|
||||||
Revisá el medio de pago o comunicate con nosotros para continuar.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
@@ -132,9 +114,7 @@
|
|||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
<p class="status-content__message">
|
<p class="status-content__message">Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.</p>
|
||||||
Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
@if (whatsappUrl()) {
|
@if (whatsappUrl()) {
|
||||||
<div class="status-content__actions">
|
<div class="status-content__actions">
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchaseDetailResponse,
|
PurchaseDetailResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
|
||||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
||||||
@@ -67,13 +66,9 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function render(
|
async function render(hasGeneratedTickets: boolean) {
|
||||||
hasGeneratedTickets: boolean,
|
|
||||||
forcedStatus?: string,
|
|
||||||
purchaseResponse = purchase(hasGeneratedTickets),
|
|
||||||
) {
|
|
||||||
const checkoutService = {
|
const checkoutService = {
|
||||||
getPurchase: vi.fn().mockResolvedValue(purchaseResponse),
|
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
|
||||||
withCustomLoading() {
|
withCustomLoading() {
|
||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
@@ -82,22 +77,15 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
navigate: vi.fn().mockResolvedValue(true),
|
navigate: vi.fn().mockResolvedValue(true),
|
||||||
navigateByUrl: vi.fn().mockResolvedValue(true),
|
navigateByUrl: vi.fn().mockResolvedValue(true),
|
||||||
};
|
};
|
||||||
const cartService = { clearCart: vi.fn() };
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: cartService },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||||
snapshot: {
|
|
||||||
paramMap: convertToParamMap({ id: '42' }),
|
|
||||||
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{ provide: Router, useValue: router },
|
{ provide: Router, useValue: router },
|
||||||
],
|
],
|
||||||
@@ -112,22 +100,15 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
fixture,
|
fixture,
|
||||||
element: fixture.nativeElement as HTMLElement,
|
element: fixture.nativeElement as HTMLElement,
|
||||||
checkoutService,
|
checkoutService,
|
||||||
cartService,
|
|
||||||
router,
|
router,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
it('clears the cart when the purchase is approved', async () => {
|
|
||||||
const { cartService } = await render(true);
|
|
||||||
|
|
||||||
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the tickets action when this purchase generated tickets', async () => {
|
it('shows the tickets action when this purchase generated tickets', async () => {
|
||||||
const { element, checkoutService, router } = await render(true);
|
const { element, checkoutService, router } = await render(true);
|
||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||||
expect(element.textContent).toContain('Mis tickets');
|
expect(element.textContent).toContain('Ver mis tickets');
|
||||||
expect(element.textContent).not.toContain('WhatsApp');
|
expect(element.textContent).not.toContain('WhatsApp');
|
||||||
|
|
||||||
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
||||||
@@ -153,38 +134,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
openSpy.mockRestore();
|
openSpy.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the expired result without polling when checkout redirects after expiration', async () => {
|
|
||||||
const { element, checkoutService } = await render(false, 'expired');
|
|
||||||
|
|
||||||
expect(element.textContent).toContain('LA COMPRA VENCIÓ');
|
|
||||||
expect(element.textContent).not.toContain('ESTAMOS VERIFICANDO TU PAGO');
|
|
||||||
expect(checkoutService.getPurchase).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the primary transfer candidate issue while the purchase is in review', async () => {
|
|
||||||
const { element } = await render(false, undefined, {
|
|
||||||
status: 'in_review',
|
|
||||||
payment_verification: {
|
|
||||||
status: 'candidate',
|
|
||||||
candidate_count: 2,
|
|
||||||
primary: {
|
|
||||||
reason: 'exact_dni_near_amount',
|
|
||||||
dni_distance: 0,
|
|
||||||
payment_amount: '49000.00',
|
|
||||||
purchase_amount: '50000.00',
|
|
||||||
amount_difference: '1000.00',
|
|
||||||
confidence: 'high',
|
|
||||||
detected_at: '2026-08-27T18:00:00-03:00',
|
|
||||||
},
|
|
||||||
reasons: ['exact_dni_near_amount', 'exact_amount_near_dni'],
|
|
||||||
},
|
|
||||||
} as PurchaseDetailResponse);
|
|
||||||
|
|
||||||
expect(element.textContent).toContain('Encontramos 2 transferencias posibles.');
|
|
||||||
expect(element.textContent).toMatch(/diferencia de \$\s*1\.000/);
|
|
||||||
expect(element.textContent).toContain('Estamos revisando el pago.');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
@@ -198,13 +147,11 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const cartService = { clearCart: vi.fn() };
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: cartService },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
@@ -227,7 +174,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
||||||
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(10_000);
|
await vi.advanceTimersByTimeAsync(10_000);
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
@@ -251,7 +197,6 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
{ provide: CartService, useValue: { clearCart: vi.fn() } },
|
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ import { ActivatedRoute, Router } from '@angular/router';
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchasePaymentVerificationResponse,
|
|
||||||
PurchaseStatusResponse,
|
PurchaseStatusResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
|
||||||
import { findMenu } from '../../../../core/services/menu.utils';
|
import { findMenu } from '../../../../core/services/menu.utils';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
@@ -37,7 +35,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly cartService = inject(CartService);
|
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||||
|
|
||||||
@@ -49,7 +46,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly isLoading = signal(true);
|
protected readonly isLoading = signal(true);
|
||||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||||
protected readonly hasGeneratedTickets = signal(false);
|
protected readonly hasGeneratedTickets = signal(false);
|
||||||
protected readonly paymentIssueMessage = signal<string | null>(null);
|
|
||||||
protected readonly ticketsRoute = computed(() => {
|
protected readonly ticketsRoute = computed(() => {
|
||||||
if (!this.hasGeneratedTickets()) {
|
if (!this.hasGeneratedTickets()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -76,12 +72,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
this.purchaseId = purchaseId;
|
this.purchaseId = purchaseId;
|
||||||
this.tenantCode = tenant.codigo;
|
this.tenantCode = tenant.codigo;
|
||||||
|
|
||||||
if (this.route.snapshot.queryParamMap?.get('status') === 'expired') {
|
|
||||||
this.status.set('expired');
|
|
||||||
this.isLoading.set(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.loadStatus();
|
void this.loadStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,11 +97,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
const status = this.resolveStatus(purchase);
|
const status = this.resolveStatus(purchase);
|
||||||
this.status.set(status);
|
this.status.set(status);
|
||||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||||
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
|
|
||||||
|
|
||||||
if (status === 'approved') {
|
|
||||||
this.cartService.clearCart();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status === 'pending') {
|
if (status === 'pending') {
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
@@ -122,10 +107,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
console.error('Failed to fetch purchase status:', error);
|
console.error('Failed to fetch purchase status:', error);
|
||||||
|
|
||||||
if (!this.isDestroyed) {
|
if (!this.isDestroyed) {
|
||||||
if (this.isPurchaseExpiredError(error)) {
|
if (isPolling) {
|
||||||
this.status.set('expired');
|
|
||||||
this.stopPolling();
|
|
||||||
} else if (isPolling) {
|
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
} else {
|
} else {
|
||||||
this.status.set('error');
|
this.status.set('error');
|
||||||
@@ -172,51 +154,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
return 'pending';
|
return 'pending';
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolvePaymentIssueMessage(
|
|
||||||
verification?: PurchasePaymentVerificationResponse,
|
|
||||||
): string | null {
|
|
||||||
const primary = verification?.primary;
|
|
||||||
|
|
||||||
if (!primary) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const primaryMessage = (() => {
|
|
||||||
switch (primary.reason) {
|
|
||||||
case 'ambiguous_exact_match':
|
|
||||||
return 'Encontramos una transferencia que también coincide con otra compra.';
|
|
||||||
case 'exact_dni_near_amount':
|
|
||||||
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
|
|
||||||
case 'exact_amount_near_dni':
|
|
||||||
return primary.dni_distance === null
|
|
||||||
? 'El monto coincide, pero el DNI del pagador es diferente.'
|
|
||||||
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
if (verification.candidate_count > 1) {
|
|
||||||
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return primaryMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
private formatCurrency(amount: string): string {
|
|
||||||
return new Intl.NumberFormat('es-AR', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: 'ARS',
|
|
||||||
maximumFractionDigits: 2,
|
|
||||||
}).format(Number(amount));
|
|
||||||
}
|
|
||||||
|
|
||||||
private isPurchaseExpiredError(error: unknown): boolean {
|
|
||||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (error as { error?: { code?: string } }).error?.code === 'purchase.expired';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected goToTickets(): void {
|
protected goToTickets(): void {
|
||||||
const route = this.ticketsRoute();
|
const route = this.ticketsRoute();
|
||||||
|
|
||||||
|
|||||||
@@ -38,13 +38,11 @@
|
|||||||
<label class="visually-hidden" for="register-password">Contraseña</label>
|
<label class="visually-hidden" for="register-password">Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password"
|
id="register-password"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Contraseña"
|
placeholder="Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updateField('password', $event)"
|
(valueChange)="updateField('password', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -53,13 +51,11 @@
|
|||||||
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password-repeat"
|
id="register-password-repeat"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Repetir Contraseña"
|
placeholder="Repetir Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updateField('password_confirmation', $event)"
|
(valueChange)="updateField('password_confirmation', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -12,48 +12,6 @@ describe('RegisterPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows and hides both password fields with either visibility control', async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [RegisterPageComponent],
|
|
||||||
providers: [
|
|
||||||
provideRouter([]),
|
|
||||||
{ provide: AuthService, useValue: { register: vi.fn() } },
|
|
||||||
{ provide: ModalService, useValue: { openSimple: vi.fn() } },
|
|
||||||
{ provide: ToastService, useValue: { danger: vi.fn() } }
|
|
||||||
]
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const getPasswordInputs = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll(
|
|
||||||
'input#register-password, input#register-password-repeat'
|
|
||||||
)
|
|
||||||
) as HTMLInputElement[];
|
|
||||||
const getVisibilityButtons = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll('button[aria-label]')
|
|
||||||
) as HTMLButtonElement[];
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
|
|
||||||
getVisibilityButtons()[0].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
|
||||||
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
|
||||||
'Ocultar contraseña',
|
|
||||||
'Ocultar contraseña'
|
|
||||||
]);
|
|
||||||
|
|
||||||
getVisibilityButtons()[1].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('submits registration data and redirects to /login on success', async () => {
|
it('submits registration data and redirects to /login on success', async () => {
|
||||||
const authService = {
|
const authService = {
|
||||||
register: vi.fn().mockReturnValue(
|
register: vi.fn().mockReturnValue(
|
||||||
|
|||||||
@@ -48,7 +48,6 @@ export class RegisterPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
private readonly passwordVisibleState = signal(false);
|
|
||||||
|
|
||||||
protected readonly form = this.formBuilder.nonNullable.group({
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
||||||
@@ -68,11 +67,6 @@ export class RegisterPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
|
||||||
|
|
||||||
protected setPasswordVisibility(visible: boolean): void {
|
|
||||||
this.passwordVisibleState.set(visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
goToLogin(): void {
|
goToLogin(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
|
|||||||
@@ -13,13 +13,11 @@
|
|||||||
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-new"
|
id="reset-password-new"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Nueva Contraseña"
|
placeholder="Nueva Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updatePassword('password', $event)"
|
(valueChange)="updatePassword('password', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -32,13 +30,11 @@
|
|||||||
</label>
|
</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-confirmation"
|
id="reset-password-confirmation"
|
||||||
type="password-toggle"
|
type="password"
|
||||||
placeholder="Repetir Nueva Contraseña"
|
placeholder="Repetir Nueva Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
[visible]="passwordVisible()"
|
|
||||||
(valueChange)="updatePassword('password_confirmation', $event)"
|
(valueChange)="updatePassword('password_confirmation', $event)"
|
||||||
(visibleChange)="setPasswordVisibility($event)"
|
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -50,43 +50,6 @@ describe('ResetPasswordPageComponent', () => {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
it('shows and hides both password fields with either visibility control', async () => {
|
|
||||||
const modalService = {
|
|
||||||
openSimple: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [ResetPasswordPageComponent],
|
|
||||||
providers: resetProviders(modalService),
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
const getPasswordInputs = () =>
|
|
||||||
Array.from(fixture.nativeElement.querySelectorAll('input')) as HTMLInputElement[];
|
|
||||||
const getVisibilityButtons = () =>
|
|
||||||
Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll('button[aria-label]'),
|
|
||||||
) as HTMLButtonElement[];
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
|
|
||||||
getVisibilityButtons()[0].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
|
||||||
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
|
||||||
'Ocultar contraseña',
|
|
||||||
'Ocultar contraseña',
|
|
||||||
]);
|
|
||||||
|
|
||||||
getVisibilityButtons()[1].click();
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects passwords that do not match', async () => {
|
it('rejects passwords that do not match', async () => {
|
||||||
const modalService = {
|
const modalService = {
|
||||||
openSimple: vi.fn(),
|
openSimple: vi.fn(),
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ export class ResetPasswordPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
private readonly passwordVisibleState = signal(false);
|
|
||||||
|
|
||||||
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
||||||
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
||||||
@@ -73,11 +72,6 @@ export class ResetPasswordPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
|
||||||
|
|
||||||
protected setPasswordVisibility(visible: boolean): void {
|
|
||||||
this.passwordVisibleState.set(visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
||||||
this.form.controls[controlName].setValue(String(value));
|
this.form.controls[controlName].setValue(String(value));
|
||||||
|
|||||||
@@ -24,10 +24,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|||||||
|
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import {
|
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||||
CheckoutService,
|
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
} from '../../../../core/services/checkout.service';
|
|
||||||
import {
|
import {
|
||||||
CatalogFeaturedItem,
|
CatalogFeaturedItem,
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
@@ -202,20 +199,10 @@ export class SearchPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
const message =
|
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
|
||||||
? error.error.message
|
|
||||||
: 'No se pudo iniciar la compra directa.';
|
|
||||||
this.toastService.danger(message);
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from '../../../../core/services/catalog/catalog.interface';
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.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 { Tenant } from '../../../../core/services/tenant.interface';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
@@ -83,6 +84,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
|
|||||||
nombre: 'Auriculares Bluetooth',
|
nombre: 'Auriculares Bluetooth',
|
||||||
precio: '24999.00',
|
precio: '24999.00',
|
||||||
image: '/catalog/auriculares.jpg',
|
image: '/catalog/auriculares.jpg',
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
@@ -90,6 +92,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
|
|||||||
nombre: 'Teclado Mecanico',
|
nombre: 'Teclado Mecanico',
|
||||||
precio: '18999.00',
|
precio: '18999.00',
|
||||||
image: null,
|
image: null,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -406,7 +409,14 @@ describe('StoreHomePageComponent', () => {
|
|||||||
|
|
||||||
it('requests another page for the selected featured group', async () => {
|
it('requests another page for the selected featured group', async () => {
|
||||||
const pageTwoItems: CatalogFeaturedItem[] = [
|
const pageTwoItems: CatalogFeaturedItem[] = [
|
||||||
{ id: 3, type: 'product', nombre: 'Mouse Gamer', precio: '15999.00', image: null },
|
{
|
||||||
|
id: 3,
|
||||||
|
type: 'product',
|
||||||
|
nombre: 'Mouse Gamer',
|
||||||
|
precio: '15999.00',
|
||||||
|
image: null,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
const catalogServiceStub = {
|
const catalogServiceStub = {
|
||||||
getCatalog: vi.fn(),
|
getCatalog: vi.fn(),
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
|||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
isExpiredStockReservationResponse,
|
|
||||||
isInsufficientStockResponse,
|
isInsufficientStockResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import {
|
import {
|
||||||
@@ -218,18 +217,10 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
tenant.codigo,
|
tenant.codigo,
|
||||||
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout', purchase.id]);
|
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
|
||||||
this.toastService.danger(error.error.message);
|
|
||||||
this.cartService.loadCart(true).subscribe({
|
|
||||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
||||||
const unavailableIds = error.error.unavailable_items
|
const unavailableIds = error.error.unavailable_items
|
||||||
.map((item) => item.variant_id)
|
.map((item) => item.variant_id)
|
||||||
|
|||||||
@@ -91,6 +91,15 @@ export const routes: Routes = [
|
|||||||
(m) => m.ProductDetailPageComponent,
|
(m) => m.ProductDetailPageComponent,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'checkout',
|
||||||
|
canActivate: [authGuard, hasMenuGuard('checkout')],
|
||||||
|
canDeactivate: [checkoutPendingPurchaseGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./pages/checkout-page/checkout-page.component').then(
|
||||||
|
(m) => m.CheckoutPageComponent,
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'checkout/status',
|
path: 'checkout/status',
|
||||||
component: SimpleLayoutComponent,
|
component: SimpleLayoutComponent,
|
||||||
@@ -104,15 +113,6 @@ export const routes: Routes = [
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: 'checkout/:id',
|
|
||||||
canActivate: [authGuard, hasMenuGuard('checkout')],
|
|
||||||
canDeactivate: [checkoutPendingPurchaseGuard],
|
|
||||||
loadComponent: () =>
|
|
||||||
import('./pages/checkout-page/checkout-page.component').then(
|
|
||||||
(m) => m.CheckoutPageComponent,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: 'ayuda',
|
path: 'ayuda',
|
||||||
canActivate: [hasMenuGuard('help')],
|
canActivate: [hasMenuGuard('help')],
|
||||||
|
|||||||
@@ -175,63 +175,6 @@ describe('CartComponent', () => {
|
|||||||
expect(removeItem).not.toHaveBeenCalled();
|
expect(removeItem).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('notifies the user and refreshes the cart when a mutation reports expiration', async () => {
|
|
||||||
const expirationMessage = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
|
||||||
const removeItem = vi.fn().mockReturnValue(
|
|
||||||
throwError(() => ({
|
|
||||||
error: {
|
|
||||||
code: 'stock_reservation.expired',
|
|
||||||
message: expirationMessage,
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
const loadCart = vi.fn().mockReturnValue(of({}));
|
|
||||||
const danger = vi.fn();
|
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [CartComponent],
|
|
||||||
providers: [
|
|
||||||
{
|
|
||||||
provide: CartService,
|
|
||||||
useValue: {
|
|
||||||
cart: signal(null).asReadonly(),
|
|
||||||
loadCart,
|
|
||||||
updateItemQuantity: vi.fn(),
|
|
||||||
removeItem,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: ModalService,
|
|
||||||
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: ToastService,
|
|
||||||
useValue: { success: vi.fn(), info: vi.fn(), danger },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(CartComponent);
|
|
||||||
fixture.componentRef.setInput('items', [
|
|
||||||
{
|
|
||||||
cartItemId: 10,
|
|
||||||
imageUrl: null,
|
|
||||||
product: 'Producto vencido',
|
|
||||||
originalPrice: null,
|
|
||||||
discountedPrice: 1000,
|
|
||||||
discountPercentage: null,
|
|
||||||
attributes: [],
|
|
||||||
quantity: 1,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('remove');
|
|
||||||
|
|
||||||
expect(danger).toHaveBeenCalledWith(expirationMessage);
|
|
||||||
expect(loadCart).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('optimistically updates quantity and rolls back on error', async () => {
|
it('optimistically updates quantity and rolls back on error', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
|
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
|
||||||
|
|||||||
@@ -98,12 +98,11 @@ export class CartComponent {
|
|||||||
this.clearOverride(update.cartItemId);
|
this.clearOverride(update.cartItemId);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
|
console.error('Error updating cart quantity', err);
|
||||||
|
const msg =
|
||||||
|
err.error?.message || 'Error al actualizar la cantidad del producto.';
|
||||||
|
this.toastService.danger(msg);
|
||||||
this.clearOverride(update.cartItemId);
|
this.clearOverride(update.cartItemId);
|
||||||
this.handleMutationError(
|
|
||||||
err,
|
|
||||||
'Error al actualizar la cantidad del producto.',
|
|
||||||
'Error updating cart quantity',
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
catchError(() => EMPTY),
|
catchError(() => EMPTY),
|
||||||
@@ -206,12 +205,9 @@ export class CartComponent {
|
|||||||
this.toastService.success(response.message || 'Variante actualizada.');
|
this.toastService.success(response.message || 'Variante actualizada.');
|
||||||
},
|
},
|
||||||
error: (error: HttpErrorResponse) => {
|
error: (error: HttpErrorResponse) => {
|
||||||
|
console.error('Error updating cart item variant', error);
|
||||||
this.clearVariantOverride(cartItemId);
|
this.clearVariantOverride(cartItemId);
|
||||||
this.handleMutationError(
|
this.toastService.danger(error.error?.message || 'No se pudo actualizar la variante.');
|
||||||
error,
|
|
||||||
'No se pudo actualizar la variante.',
|
|
||||||
'Error updating cart item variant',
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -309,29 +305,10 @@ export class CartComponent {
|
|||||||
this.toastService.info(msg);
|
this.toastService.info(msg);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
this.handleMutationError(
|
console.error('Error removing item from cart', err);
|
||||||
err,
|
const msg = err.error?.message || 'Error al eliminar el producto del carrito.';
|
||||||
'Error al eliminar el producto del carrito.',
|
this.toastService.danger(msg);
|
||||||
'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),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,7 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
[availability]="itemAvailability(item)"
|
||||||
[unavailableMessage]="item.unavailable_message ?? null"
|
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
[saving]="savingProductIds().has(item.id)"
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitRowBuy(item, $event)"
|
(buy)="emitRowBuy(item, $event)"
|
||||||
@@ -25,8 +24,7 @@
|
|||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
[availability]="itemAvailability(item)"
|
||||||
[unavailableMessage]="item.unavailable_message ?? null"
|
|
||||||
[variants]="item.variants ?? []"
|
[variants]="item.variants ?? []"
|
||||||
[saving]="savingProductIds().has(item.id)"
|
[saving]="savingProductIds().has(item.id)"
|
||||||
(buy)="emitColumnBuy(item, $event)"
|
(buy)="emitColumnBuy(item, $event)"
|
||||||
@@ -40,8 +38,8 @@
|
|||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||||
[unavailableMessage]="item.unavailable_message ?? null"
|
[unavailableMessage]="availabilityMessage(item)"
|
||||||
[disabled]="loading() || !!item.unavailable_message"
|
[disabled]="loading() || !allows(itemAvailability(item), 'buy_now')"
|
||||||
(buy)="emitTicketBuy(item, $event)"
|
(buy)="emitTicketBuy(item, $event)"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
@@ -50,7 +48,7 @@
|
|||||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||||
[title]="item.nombre"
|
[title]="item.nombre"
|
||||||
[originalPrice]="price(item)"
|
[originalPrice]="price(item)"
|
||||||
[unavailableMessage]="item.unavailable_message ?? null"
|
[unavailableMessage]="availabilityMessage(item)"
|
||||||
[imagePriority]="loadImages() && index < 4"
|
[imagePriority]="loadImages() && index < 4"
|
||||||
(buy)="emitProductDetailBuy(item)"
|
(buy)="emitProductDetailBuy(item)"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { of } from 'rxjs';
|
|||||||
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
|
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
|
||||||
import { CartService } from '../../../core/services/cart/cart.service';
|
import { CartService } from '../../../core/services/cart/cart.service';
|
||||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||||
|
import { createCatalogAvailability } from '../../../core/services/catalog/catalog-availability';
|
||||||
import {
|
import {
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
@@ -23,6 +24,7 @@ describe('ProductListComponent', () => {
|
|||||||
descripcion: 'Primera descripcion',
|
descripcion: 'Primera descripcion',
|
||||||
precio: '100.00',
|
precio: '100.00',
|
||||||
image: '/images/one.png',
|
image: '/images/one.png',
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
variants: [],
|
variants: [],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -32,6 +34,7 @@ describe('ProductListComponent', () => {
|
|||||||
descripcion: 'Segunda descripcion',
|
descripcion: 'Segunda descripcion',
|
||||||
precio: 200,
|
precio: 200,
|
||||||
image: null,
|
image: null,
|
||||||
|
availability: createCatalogAvailability(null),
|
||||||
variants: [],
|
variants: [],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -56,6 +59,20 @@ describe('ProductListComponent', () => {
|
|||||||
) {
|
) {
|
||||||
const getVariantOptions = vi.fn().mockReturnValue(
|
const getVariantOptions = vi.fn().mockReturnValue(
|
||||||
of({
|
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) => ({
|
selectors: ['tipo', 'sector', 'fila', 'asiento'].map((key, index) => ({
|
||||||
key,
|
key,
|
||||||
label: key,
|
label: key,
|
||||||
@@ -73,7 +90,12 @@ describe('ProductListComponent', () => {
|
|||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [ProductListComponent],
|
imports: [ProductListComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CatalogService, useValue: { getVariantOptions } },
|
{
|
||||||
|
provide: CatalogService,
|
||||||
|
useValue: {
|
||||||
|
withoutLoading: () => ({ getVariantOptions }),
|
||||||
|
},
|
||||||
|
},
|
||||||
{ provide: CartService, useValue: {} },
|
{ provide: CartService, useValue: {} },
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -193,8 +215,8 @@ describe('ProductListComponent', () => {
|
|||||||
const itemWithVariants: ProductListItem = {
|
const itemWithVariants: ProductListItem = {
|
||||||
...items[0],
|
...items[0],
|
||||||
variants: [
|
variants: [
|
||||||
{ id: 91, maximum_addable_quantity: 3, values: { fecha: '10 de octubre' } },
|
{ id: 91, availability: createCatalogAvailability(3), values: { fecha: '10 de octubre' } },
|
||||||
{ id: 92, maximum_addable_quantity: 4, values: { fecha: '11 de octubre' } },
|
{ id: 92, availability: createCatalogAvailability(4), values: { fecha: '11 de octubre' } },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const fixture = await render('column_with_cart', [itemWithVariants]);
|
const fixture = await render('column_with_cart', [itemWithVariants]);
|
||||||
@@ -220,7 +242,7 @@ describe('ProductListComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 91,
|
id: 91,
|
||||||
maximum_addable_quantity: 2,
|
availability: createCatalogAvailability(2),
|
||||||
values: { fecha: '10 de octubre' },
|
values: { fecha: '10 de octubre' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -248,7 +270,7 @@ describe('ProductListComponent', () => {
|
|||||||
variants: [
|
variants: [
|
||||||
{
|
{
|
||||||
id: 91,
|
id: 91,
|
||||||
maximum_addable_quantity: 0,
|
availability: createCatalogAvailability(0),
|
||||||
values: { fecha: '10 de octubre' },
|
values: { fecha: '10 de octubre' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -304,7 +326,7 @@ describe('ProductListComponent', () => {
|
|||||||
{
|
{
|
||||||
id: 401,
|
id: 401,
|
||||||
precio: '10000.00',
|
precio: '10000.00',
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: { value: 'vip', label: 'VIP' },
|
tipo: { value: 'vip', label: 'VIP' },
|
||||||
sector: { value: 'a', label: 'Sector A' },
|
sector: { value: 'a', label: 'Sector A' },
|
||||||
@@ -315,7 +337,7 @@ describe('ProductListComponent', () => {
|
|||||||
{
|
{
|
||||||
id: 402,
|
id: 402,
|
||||||
precio: '12000.00',
|
precio: '12000.00',
|
||||||
maximum_addable_quantity: 1,
|
availability: createCatalogAvailability(1),
|
||||||
values: {
|
values: {
|
||||||
tipo: { value: 'vip', label: 'VIP' },
|
tipo: { value: 'vip', label: 'VIP' },
|
||||||
sector: { value: 'a', label: 'Sector A' },
|
sector: { value: 'a', label: 'Sector A' },
|
||||||
|
|||||||
@@ -18,6 +18,11 @@ import {
|
|||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
CatalogProductLayout,
|
CatalogProductLayout,
|
||||||
} from '../../../core/services/catalog/catalog.interface';
|
} 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 { CarouselComponent } from '../carousel/carousel.component';
|
||||||
import { PaginatorComponent } from '../paginator/paginator.component';
|
import { PaginatorComponent } from '../paginator/paginator.component';
|
||||||
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
|
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
|
||||||
@@ -74,6 +79,7 @@ export class ProductListComponent {
|
|||||||
readonly buy = output<ProductListBuyEvent>();
|
readonly buy = output<ProductListBuyEvent>();
|
||||||
readonly addToCart = output<ProductListCartEvent>();
|
readonly addToCart = output<ProductListCartEvent>();
|
||||||
readonly pageChange = output<number>();
|
readonly pageChange = output<number>();
|
||||||
|
protected readonly allows = allowsCatalogAction;
|
||||||
|
|
||||||
protected readonly effectiveLayout = computed<ProductListLayout>(() =>
|
protected readonly effectiveLayout = computed<ProductListLayout>(() =>
|
||||||
this.mobile() && this.layout() === 'row' ? 'column_with_cart' : this.layout(),
|
this.mobile() && this.layout() === 'row' ? 'column_with_cart' : this.layout(),
|
||||||
@@ -108,6 +114,14 @@ export class ProductListComponent {
|
|||||||
return Number.isFinite(price) ? price : 0;
|
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(
|
protected emitRowCart(
|
||||||
product: ProductListItem,
|
product: ProductListItem,
|
||||||
event: { quantity: number; variant: unknown },
|
event: { quantity: number; variant: unknown },
|
||||||
|
|||||||
@@ -21,13 +21,14 @@
|
|||||||
<app-variant-selector
|
<app-variant-selector
|
||||||
class="product-row-card__selectors"
|
class="product-row-card__selectors"
|
||||||
[variants]="variants()"
|
[variants]="variants()"
|
||||||
|
[disabled]="!allows(availability(), 'select_variant')"
|
||||||
[(selectedVariant)]="selectedVariant"
|
[(selectedVariant)]="selectedVariant"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<app-quantity-selector
|
<app-quantity-selector
|
||||||
[(quantity)]="quantity"
|
[(quantity)]="quantity"
|
||||||
[max]="effectiveMaximum()"
|
[max]="effectiveMaximum()"
|
||||||
[disabled]="unavailable()"
|
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -38,14 +39,22 @@
|
|||||||
|
|
||||||
<div class="product-row-card__buttons">
|
<div class="product-row-card__buttons">
|
||||||
<div class="product-row-card__btn-wrapper">
|
<div class="product-row-card__btn-wrapper">
|
||||||
<app-button variant="primary" [disabled]="unavailable()" (click)="onBuy()">
|
<app-button
|
||||||
|
variant="primary"
|
||||||
|
[disabled]="!hasPurchasableSelection() || !allows(effectiveAvailability(), 'buy_now')"
|
||||||
|
(click)="onBuy()"
|
||||||
|
>
|
||||||
Comprar
|
Comprar
|
||||||
</app-button>
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="product-row-card__btn-wrapper">
|
<div class="product-row-card__btn-wrapper">
|
||||||
<app-button
|
<app-button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
[disabled]="saving() || unavailable()"
|
[disabled]="
|
||||||
|
saving() ||
|
||||||
|
!hasPurchasableSelection() ||
|
||||||
|
!allows(effectiveAvailability(), 'add_to_cart')
|
||||||
|
"
|
||||||
(click)="onAddToCart()"
|
(click)="onAddToCart()"
|
||||||
>
|
>
|
||||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||||
|
|||||||
@@ -14,13 +14,20 @@ import {
|
|||||||
VariantSelectorComponent,
|
VariantSelectorComponent,
|
||||||
VariantSelectorVariant,
|
VariantSelectorVariant,
|
||||||
} from '../variant-selector/variant-selector.component';
|
} 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 {
|
export interface Variant extends VariantSelectorVariant {
|
||||||
label?: string;
|
label?: string;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
maximum_addable_quantity?: number | null;
|
availability?: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -36,8 +43,7 @@ export class ProductRowCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
readonly maximumAddableQuantity = input<number | null>(null);
|
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
|
||||||
readonly unavailableMessage = input<string | null>(null);
|
|
||||||
readonly variants = input<Variant[]>([]);
|
readonly variants = input<Variant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -60,19 +66,22 @@ export class ProductRowCardComponent {
|
|||||||
|
|
||||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||||
});
|
});
|
||||||
protected readonly effectiveMaximum = computed(
|
protected readonly effectiveAvailability = computed(() =>
|
||||||
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
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 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()));
|
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
|
protected readonly allows = allowsCatalogAction;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
@@ -85,7 +94,11 @@ export class ProductRowCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
if (this.saving() || this.unavailable()) {
|
if (
|
||||||
|
this.saving() ||
|
||||||
|
!this.hasPurchasableSelection() ||
|
||||||
|
!this.allows(this.effectiveAvailability(), 'add_to_cart')
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +109,8 @@ export class ProductRowCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
if (this.unavailable()) return;
|
if (!this.hasPurchasableSelection() || !this.allows(this.effectiveAvailability(), 'buy_now'))
|
||||||
|
return;
|
||||||
|
|
||||||
this.buy.emit({
|
this.buy.emit({
|
||||||
quantity: this.quantity(),
|
quantity: this.quantity(),
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ import {
|
|||||||
CatalogVariantSelector,
|
CatalogVariantSelector,
|
||||||
CatalogVariantValue,
|
CatalogVariantValue,
|
||||||
} from '../../../core/services/catalog/catalog.interface';
|
} from '../../../core/services/catalog/catalog.interface';
|
||||||
|
import {
|
||||||
|
allowsCatalogAction,
|
||||||
|
createCatalogAvailability,
|
||||||
|
} from '../../../core/services/catalog/catalog-availability';
|
||||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||||
import { ModalService } from '../../../core/services/modal.service';
|
import { ModalService } from '../../../core/services/modal.service';
|
||||||
import { ToastService } from '../../../core/services/toast.service';
|
import { ToastService } from '../../../core/services/toast.service';
|
||||||
@@ -353,7 +357,11 @@ export class ProductTicketSelectorComponent {
|
|||||||
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
|
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
|
||||||
variants.push(reservedVariant);
|
variants.push(reservedVariant);
|
||||||
}
|
}
|
||||||
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
|
return variants.filter(
|
||||||
|
({ id, availability }) =>
|
||||||
|
(availability === undefined || allowsCatalogAction(availability, 'select_variant')) &&
|
||||||
|
!reservedByOtherRows.has(id),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
|
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
|
||||||
@@ -363,7 +371,9 @@ export class ProductTicketSelectorComponent {
|
|||||||
return {
|
return {
|
||||||
id: item.variant.id,
|
id: item.variant.id,
|
||||||
precio: item.variant.precio,
|
precio: item.variant.precio,
|
||||||
maximum_addable_quantity: item.variant.stock_tecnico,
|
availability: createCatalogAvailability(
|
||||||
|
item.variant.stock_tecnico === null ? null : item.variant.stock_tecnico + item.cantidad,
|
||||||
|
),
|
||||||
values: item.variant.values,
|
values: item.variant.values,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
<app-quantity-selector
|
<app-quantity-selector
|
||||||
[(quantity)]="quantity"
|
[(quantity)]="quantity"
|
||||||
[max]="effectiveMaximum()"
|
[max]="effectiveMaximum()"
|
||||||
[disabled]="unavailable()"
|
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
@@ -29,12 +29,16 @@
|
|||||||
<app-quantity-selector
|
<app-quantity-selector
|
||||||
[(quantity)]="quantity"
|
[(quantity)]="quantity"
|
||||||
[max]="effectiveMaximum()"
|
[max]="effectiveMaximum()"
|
||||||
[disabled]="unavailable()"
|
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="product-vertical-with-cart-card__variant-selectors">
|
<div class="product-vertical-with-cart-card__variant-selectors">
|
||||||
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
|
<app-variant-selector
|
||||||
|
[variants]="variants()"
|
||||||
|
[disabled]="!allows(availability(), 'select_variant')"
|
||||||
|
[(selectedVariant)]="selectedVariant"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@@ -42,14 +46,21 @@
|
|||||||
<div class="product-vertical-with-cart-card__actions">
|
<div class="product-vertical-with-cart-card__actions">
|
||||||
<app-button
|
<app-button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
[disabled]="unavailable() || (hasVariants() && selectedVariant() === null)"
|
[disabled]="
|
||||||
|
!allows(effectiveAvailability(), 'buy_now') ||
|
||||||
|
(hasVariants() && selectedVariant() === null)
|
||||||
|
"
|
||||||
(click)="onBuy()"
|
(click)="onBuy()"
|
||||||
>
|
>
|
||||||
Comprar
|
Comprar
|
||||||
</app-button>
|
</app-button>
|
||||||
<app-button
|
<app-button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
[disabled]="saving() || unavailable() || (hasVariants() && selectedVariant() === null)"
|
[disabled]="
|
||||||
|
saving() ||
|
||||||
|
!allows(effectiveAvailability(), 'add_to_cart') ||
|
||||||
|
(hasVariants() && selectedVariant() === null)
|
||||||
|
"
|
||||||
(click)="onAddToCart()"
|
(click)="onAddToCart()"
|
||||||
>
|
>
|
||||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding: 30px 20px;
|
padding: 30px 20px;
|
||||||
overflow: visible;
|
overflow: hidden;
|
||||||
background-color: #ffffff;
|
background-color: #ffffff;
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 7px;
|
border-radius: 7px;
|
||||||
|
|||||||
@@ -58,11 +58,17 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
|||||||
|
|
||||||
it('shows the backend availability message with the reusable tooltip', async () => {
|
it('shows the backend availability message with the reusable tooltip', async () => {
|
||||||
const fixture = await createComponent();
|
const fixture = await createComponent();
|
||||||
fixture.componentRef.setInput('maximumAddableQuantity', 0);
|
fixture.componentRef.setInput('availability', {
|
||||||
fixture.componentRef.setInput(
|
state: 'visible',
|
||||||
'unavailableMessage',
|
maximum_quantity: 0,
|
||||||
'Alcanzaste el cupo máximo permitido para este producto.',
|
reasons: [
|
||||||
);
|
{
|
||||||
|
code: 'user_quota_reached',
|
||||||
|
message: 'Alcanzaste el cupo máximo permitido para este producto.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
allowed_actions: [],
|
||||||
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');
|
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');
|
||||||
|
|||||||
@@ -15,12 +15,19 @@ import {
|
|||||||
VariantSelectorComponent,
|
VariantSelectorComponent,
|
||||||
VariantSelectorVariant,
|
VariantSelectorVariant,
|
||||||
} from '../variant-selector/variant-selector.component';
|
} 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 {
|
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
maximum_addable_quantity?: number | null;
|
availability?: CatalogAvailability;
|
||||||
unavailable_message?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -34,8 +41,7 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
readonly title = input<string>('');
|
readonly title = input<string>('');
|
||||||
readonly description = input<string>('');
|
readonly description = input<string>('');
|
||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
readonly maximumAddableQuantity = input<number | null>(null);
|
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
|
||||||
readonly unavailableMessage = input<string | null>(null);
|
|
||||||
readonly variants = input<VerticalCartVariant[]>([]);
|
readonly variants = input<VerticalCartVariant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -58,17 +64,16 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
});
|
});
|
||||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||||
protected readonly effectiveMaximum = computed(
|
protected readonly effectiveAvailability = computed(() =>
|
||||||
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
|
||||||
);
|
);
|
||||||
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
protected readonly effectiveMaximum = computed(() =>
|
||||||
protected readonly effectiveUnavailableMessage = computed(() => {
|
maximumCatalogQuantity(this.effectiveAvailability()),
|
||||||
const selectedVariant = this.selectedVariantData();
|
);
|
||||||
|
protected readonly effectiveUnavailableMessage = computed(() =>
|
||||||
return selectedVariant
|
primaryAvailabilityMessage(this.effectiveAvailability()),
|
||||||
? (selectedVariant.unavailable_message ?? null)
|
);
|
||||||
: this.unavailableMessage();
|
protected readonly allows = allowsCatalogAction;
|
||||||
});
|
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
@@ -81,7 +86,7 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onAddToCart(): void {
|
protected onAddToCart(): void {
|
||||||
if (this.saving() || this.unavailable()) {
|
if (this.saving() || !this.allows(this.effectiveAvailability(), 'add_to_cart')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +94,7 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onBuy(): void {
|
protected onBuy(): void {
|
||||||
if (this.unavailable()) return;
|
if (!this.allows(this.effectiveAvailability(), 'buy_now')) return;
|
||||||
|
|
||||||
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ describe('VariantSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
fixture.componentRef.setInput('selectedVariant', 2);
|
fixture.componentRef.setInput('selectedVariant', 2);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
const selects = Array.from(
|
const selects = Array.from(
|
||||||
fixture.nativeElement.querySelectorAll('select'),
|
fixture.nativeElement.querySelectorAll('select'),
|
||||||
@@ -80,6 +82,28 @@ describe('VariantSelectorComponent', () => {
|
|||||||
expect(fixture.componentInstance.selectedVariant()).toBe(1);
|
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 () => {
|
it('requires manual selections when autoSelectFirst is disabled', async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [VariantSelectorComponent],
|
imports: [VariantSelectorComponent],
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
untracked,
|
untracked,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
|
||||||
|
import { allowsCatalogAction } from '../../../core/services/catalog/catalog-availability';
|
||||||
|
|
||||||
export interface VariantAttributeOption {
|
export interface VariantAttributeOption {
|
||||||
value: string;
|
value: string;
|
||||||
@@ -22,6 +24,7 @@ export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeSca
|
|||||||
export interface VariantSelectorVariant {
|
export interface VariantSelectorVariant {
|
||||||
id: unknown;
|
id: unknown;
|
||||||
values: Record<string, VariantAttributeValue>;
|
values: Record<string, VariantAttributeValue>;
|
||||||
|
availability?: CatalogAvailability;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VariantSelectorSelectionChange {
|
export interface VariantSelectorSelectionChange {
|
||||||
@@ -64,10 +67,12 @@ export class VariantSelectorComponent {
|
|||||||
right: VariantAttributeValue | null,
|
right: VariantAttributeValue | null,
|
||||||
): boolean => left !== null && right !== null && this.sameValue(left, right);
|
): boolean => left !== null && right !== null && this.sameValue(left, right);
|
||||||
protected readonly attributeKeys = computed(() =>
|
protected readonly attributeKeys = computed(() =>
|
||||||
Array.from(new Set(this.variants().flatMap((variant) => Object.keys(variant.values)))),
|
Array.from(
|
||||||
|
new Set(this.getSelectableVariants().flatMap((variant) => Object.keys(variant.values))),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
|
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
|
||||||
const variants = this.variants();
|
const variants = this.getSelectableVariants();
|
||||||
const keys = this.attributeKeys();
|
const keys = this.attributeKeys();
|
||||||
const selectedValues = this.selectedValues();
|
const selectedValues = this.selectedValues();
|
||||||
|
|
||||||
@@ -110,7 +115,7 @@ export class VariantSelectorComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const variants = this.variants();
|
const variants = this.getSelectableVariants();
|
||||||
const selectedVariant = this.selectedVariant();
|
const selectedVariant = this.selectedVariant();
|
||||||
const autoSelectFirst = this.autoSelectFirst();
|
const autoSelectFirst = this.autoSelectFirst();
|
||||||
|
|
||||||
@@ -139,7 +144,7 @@ export class VariantSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
|
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
|
||||||
const variants = this.variants();
|
const variants = this.getSelectableVariants();
|
||||||
const keys = this.attributeKeys();
|
const keys = this.attributeKeys();
|
||||||
const changedIndex = keys.indexOf(key);
|
const changedIndex = keys.indexOf(key);
|
||||||
const values = { ...this.selectedValues() };
|
const values = { ...this.selectedValues() };
|
||||||
@@ -198,6 +203,14 @@ export class VariantSelectorComponent {
|
|||||||
return Array.from(options.values());
|
return Array.from(options.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getSelectableVariants(): VariantSelectorVariant[] {
|
||||||
|
return this.variants().filter(
|
||||||
|
(variant) =>
|
||||||
|
variant.availability === undefined ||
|
||||||
|
allowsCatalogAction(variant.availability, 'select_variant'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private reconcileManualSelection(
|
private reconcileManualSelection(
|
||||||
selectedValues: Record<string, VariantAttributeValue>,
|
selectedValues: Record<string, VariantAttributeValue>,
|
||||||
variants: VariantSelectorVariant[],
|
variants: VariantSelectorVariant[],
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export const environment = {
|
export const environment = {
|
||||||
production: true,
|
production: false,
|
||||||
nombre:"Homologación - activo",
|
nombre:"Homologación - activo",
|
||||||
url:"https://backend.qa.shopit.com.ar/api/",
|
url:"https://backend.qa.shopit.com.ar/api/",
|
||||||
urlDescarga:"url/"
|
urlDescarga:"url/"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<title>ShopitFront</title>
|
<title>ShopitFront</title>
|
||||||
<base href="/">
|
<base href="/">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E">
|
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<app-root></app-root>
|
<app-root></app-root>
|
||||||
|
|||||||
@@ -6,15 +6,6 @@
|
|||||||
|
|
||||||
@import '../node_modules/bootstrap/scss/bootstrap';
|
@import '../node_modules/bootstrap/scss/bootstrap';
|
||||||
|
|
||||||
html,
|
|
||||||
body,
|
|
||||||
app-root {
|
|
||||||
width: 100%;
|
|
||||||
min-height: 100%;
|
|
||||||
margin: 0;
|
|
||||||
background: #f5f5f5;
|
|
||||||
}
|
|
||||||
|
|
||||||
:root,
|
:root,
|
||||||
app-root {
|
app-root {
|
||||||
--border-color: #dddddd;
|
--border-color: #dddddd;
|
||||||
|
|||||||
Reference in New Issue
Block a user