Compare commits
58 Commits
c24a8b946d
...
fix/zoom_b
| Author | SHA1 | Date | |
|---|---|---|---|
| 4bd74d95cb | |||
| 6f87aae939 | |||
| 71ef09b413 | |||
| 1d54cb1c48 | |||
| 7d52e11bca | |||
| ebae063a0f | |||
| f0c1e74c1b | |||
| 709859e731 | |||
| e95a7612c2 | |||
| 8bc0e165c7 | |||
| 158b28ec1a | |||
| 8c22485d49 | |||
| 2462f25f2f | |||
| 63b01f366a | |||
| ddd0b1b56d | |||
| 2cad0c39b4 | |||
| 3089873232 | |||
| 3fa0235163 | |||
| 0910d90363 | |||
| f3d446d012 | |||
| 1ec48f7e21 | |||
| 07972760fc | |||
| 848c3b280f | |||
| c387a01d62 | |||
| 5d9adc0494 | |||
| 593580d648 | |||
| eb524c7d99 | |||
| 65e8436ae1 | |||
| 07500f699d | |||
| 4997665da6 | |||
| dbfadf417a | |||
| dddb086cd8 | |||
| a825b3693b | |||
| 679342ec8d | |||
| a5420e6a42 | |||
| 91b8788c91 | |||
| b6a52ceb8c | |||
| 51d051733c | |||
| f62cd08807 | |||
| d61b1e4b0a | |||
| 1bffefece3 | |||
| b0d2cd05bc | |||
| 591f53c102 | |||
| 85529f40f2 | |||
| 4a952af784 | |||
| b1d4c4d13d | |||
| 8861e42fff | |||
| 7fbdd3844f | |||
| f2c1542e46 | |||
| def86405dc | |||
| 870de3ca6e | |||
| d8d489e846 | |||
| 4183d6386d | |||
| 8089298383 | |||
| d51db00247 | |||
| 88c3a08a23 | |||
| 21e89805d0 | |||
| 195ac73aed |
@@ -7,6 +7,7 @@ import { of } from 'rxjs';
|
|||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { AuthService } from './core/services/auth/auth.service';
|
import { AuthService } from './core/services/auth/auth.service';
|
||||||
import { CartService } from './core/services/cart/cart.service';
|
import { CartService } from './core/services/cart/cart.service';
|
||||||
|
import { CheckoutService } from './core/services/checkout.service';
|
||||||
import { Tenant } from './core/services/tenant.interface';
|
import { Tenant } from './core/services/tenant.interface';
|
||||||
import { TenantService } from './core/services/tenant.service';
|
import { TenantService } from './core/services/tenant.service';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -97,6 +98,21 @@ async function renderAppAt(
|
|||||||
{
|
{
|
||||||
provide: AuthService,
|
provide: AuthService,
|
||||||
useValue: authService
|
useValue: authService
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: CheckoutService,
|
||||||
|
useValue: {
|
||||||
|
withCustomLoading() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
getPurchase: vi.fn().mockResolvedValue({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
items: [],
|
||||||
|
subtotal: '0.00',
|
||||||
|
total: '0.00'
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -246,15 +262,33 @@ describe('app routes', () => {
|
|||||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('redirects unauthenticated users from /checkout to /login', async () => {
|
it('redirects unauthenticated users from /checkout/:id to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
|
||||||
|
|
||||||
expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
|
expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows authenticated users to access /checkout', async () => {
|
it('allows authenticated users to access /checkout/:id', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true));
|
const checkoutTenant = {
|
||||||
|
...tenant,
|
||||||
|
menues: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
code: 'checkout',
|
||||||
|
label: 'Checkout',
|
||||||
|
parent_menu_code: null,
|
||||||
|
content_type: 'dynamic' as const,
|
||||||
|
route: '/checkout',
|
||||||
|
submenues: []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
const { router } = await renderAppAt(
|
||||||
|
'/checkout/25',
|
||||||
|
createTenantServiceStub('ready', checkoutTenant),
|
||||||
|
createAuthServiceStub(true)
|
||||||
|
);
|
||||||
|
|
||||||
expect(router.url).toBe('/checkout');
|
expect(router.url).toBe('/checkout/25');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -115,6 +115,6 @@ describe('App', () => {
|
|||||||
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
expect(document.title).toBe('ShopitFront');
|
expect(document.title).toBe('ShopitFront');
|
||||||
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
expect(document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'))
|
||||||
.toBe('favicon.ico');
|
.toBe("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import { GlobalLoadingComponent } from './shared/components/global-loading/globa
|
|||||||
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
||||||
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
||||||
|
|
||||||
|
const EMPTY_FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";
|
||||||
|
|
||||||
function hexToRgb(hex: string): string {
|
function hexToRgb(hex: string): string {
|
||||||
const cleanHex = hex.replace('#', '').trim();
|
const cleanHex = hex.replace('#', '').trim();
|
||||||
let r = 0, g = 0, b = 0;
|
let r = 0, g = 0, b = 0;
|
||||||
@@ -66,7 +68,7 @@ export class App {
|
|||||||
effect(() => {
|
effect(() => {
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
||||||
const faviconHref = tenant?.favicon || 'favicon.ico';
|
const faviconHref = tenant?.favicon || EMPTY_FAVICON;
|
||||||
|
|
||||||
this.title.setTitle(siteTitle);
|
this.title.setTitle(siteTitle);
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe('hasMenuGuard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('redirects a missing menu route to the store root', () => {
|
it('redirects a missing menu route to the store root', () => {
|
||||||
const result = runGuard('checkout', '/checkout', tenant);
|
const result = runGuard('checkout', '/checkout/25', tenant);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||||
|
|||||||
@@ -79,10 +79,13 @@
|
|||||||
|
|
||||||
@if (displayCart()) {
|
@if (displayCart()) {
|
||||||
<app-cart-icon
|
<app-cart-icon
|
||||||
[quantity]="cartQuantity()"
|
[quantity]="cartDisabled() ? null : cartQuantity()"
|
||||||
ariaLabel="Carrito de compras"
|
[disabled]="cartDisabled()"
|
||||||
title="Carrito"
|
[ariaLabel]="
|
||||||
(click)="cartClick.emit()"
|
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
||||||
|
"
|
||||||
|
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
|
||||||
|
(click)="onCartClick()"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,9 +152,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (displayCategories()) {
|
<div class="store-layout__categories d-none d-md-block">
|
||||||
<div class="store-layout__categories d-none d-md-block">
|
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
|
||||||
<div class="container-xl px-3 px-md-4">
|
@if (displayCategories()) {
|
||||||
<div class="store-layout__category-menu">
|
<div class="store-layout__category-menu">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -172,7 +175,18 @@
|
|||||||
(categorySelect)="onCategorySelect($event)"
|
(categorySelect)="onCategorySelect($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
}
|
||||||
|
|
||||||
|
@if (checkoutRemainingTime(); as remainingTime) {
|
||||||
|
<div
|
||||||
|
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
|
||||||
|
role="timer"
|
||||||
|
aria-label="Tiempo restante de compra"
|
||||||
|
>
|
||||||
|
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
|
||||||
|
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -10,6 +10,26 @@
|
|||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.store-layout__categories {
|
||||||
|
height: 3.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer {
|
||||||
|
color: var(--tenant-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer-label {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer-value {
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
.store-layout__brand-slot {
|
||||||
min-width: 150px;
|
min-width: 150px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
|
import {
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
ElementRef,
|
||||||
|
HostListener,
|
||||||
|
inject,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
signal,
|
||||||
|
} from '@angular/core';
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, RouterLink } from '@angular/router';
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||||
@@ -39,6 +48,8 @@ export class StoreHeaderComponent {
|
|||||||
readonly displayCategories = input(true);
|
readonly displayCategories = input(true);
|
||||||
readonly displaySeachBar = input(true);
|
readonly displaySeachBar = input(true);
|
||||||
readonly displayCart = input(true);
|
readonly displayCart = input(true);
|
||||||
|
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>();
|
||||||
@@ -52,6 +63,26 @@ 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 {
|
||||||
|
if (this.cartDisabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cartClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
@HostListener('document:click', ['$event'])
|
@HostListener('document:click', ['$event'])
|
||||||
protected onDocumentClick(event: MouseEvent): void {
|
protected onDocumentClick(event: MouseEvent): void {
|
||||||
|
|||||||
@@ -12,7 +12,9 @@
|
|||||||
[displayCategories]="tenant()?.display_categories ?? true"
|
[displayCategories]="tenant()?.display_categories ?? true"
|
||||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||||
[displayCart]="displayCart()"
|
[displayCart]="displayCart()"
|
||||||
(cartClick)="isCartOpen.set(!isCartOpen())"
|
[cartDisabled]="isCheckoutRoute()"
|
||||||
|
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
||||||
|
(cartClick)="onCartClick()"
|
||||||
(ticketsClick)="onTicketsClick()"
|
(ticketsClick)="onTicketsClick()"
|
||||||
(loginClick)="onLoginClick()"
|
(loginClick)="onLoginClick()"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
@@ -20,7 +22,7 @@
|
|||||||
(categorySelect)="onCategorySelect($event)"
|
(categorySelect)="onCategorySelect($event)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@if (displayCart() && isCartOpen()) {
|
@if (displayCart() && !isCheckoutRoute() && isCartOpen()) {
|
||||||
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
|
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
|
||||||
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
||||||
<app-cart
|
<app-cart
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
:host {
|
:host {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
min-height: 100dvh;
|
min-height: 100dvh;
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
color: #202020;
|
color: #202020;
|
||||||
@@ -7,6 +9,8 @@
|
|||||||
|
|
||||||
.store-layout {
|
.store-layout {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__cart-overlay {
|
.store-layout__cart-overlay {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import {
|
import {
|
||||||
@@ -8,6 +9,7 @@ import {
|
|||||||
ParamMap,
|
ParamMap,
|
||||||
provideRouter,
|
provideRouter,
|
||||||
Router,
|
Router,
|
||||||
|
UrlSerializer,
|
||||||
} from '@angular/router';
|
} from '@angular/router';
|
||||||
|
|
||||||
import { BehaviorSubject, of } from 'rxjs';
|
import { BehaviorSubject, of } from 'rxjs';
|
||||||
@@ -22,6 +24,8 @@ 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';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -147,6 +151,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let tenantState = signal<Tenant | null>(tenant);
|
let tenantState = signal<Tenant | null>(tenant);
|
||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
|
let checkoutRemainingSecondsState = signal<number | null>(null);
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
let queryParamMapState: BehaviorSubject<ParamMap>;
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
@@ -154,6 +159,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
|
checkoutRemainingSecondsState = signal<number | null>(null);
|
||||||
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
@@ -164,6 +170,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
|
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||||
@@ -211,6 +218,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
provide: CheckoutService,
|
provide: CheckoutService,
|
||||||
useValue: checkoutServiceStub,
|
useValue: checkoutServiceStub,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: CheckoutCountdownService,
|
||||||
|
useValue: {
|
||||||
|
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
@@ -240,6 +253,49 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
||||||
|
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const cartButton = element.querySelector<HTMLButtonElement>('app-cart-icon button');
|
||||||
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
|
|
||||||
|
expect(cartButton?.disabled).toBe(true);
|
||||||
|
expect(cartButton?.getAttribute('aria-label')).toBe(
|
||||||
|
'Carrito no disponible durante el checkout',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
|
||||||
|
|
||||||
|
header.componentInstance.cartClick.emit();
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
expect(element.querySelector('app-cart')).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,
|
||||||
@@ -557,7 +613,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const authService = TestBed.inject(AuthService);
|
const authService = TestBed.inject(AuthService);
|
||||||
const cartService = TestBed.inject(CartService);
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
|
||||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
@@ -644,12 +700,44 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
||||||
cart_id: 1,
|
cart_id: 1,
|
||||||
});
|
});
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
|
expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
|
||||||
queryParams: { purchase: 55 },
|
|
||||||
});
|
|
||||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
|
||||||
|
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
||||||
|
checkoutServiceStub.startCheckout.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: { code: 'stock_reservation.expired', message },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cartState.set({
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [],
|
||||||
|
});
|
||||||
|
authUserState.set({
|
||||||
|
id: 7,
|
||||||
|
nombre_apellido: 'Juan Perez',
|
||||||
|
email: 'juan@example.com',
|
||||||
|
dni: '12345678',
|
||||||
|
telefono: '3415555555',
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
|
||||||
|
fixture.detectChanges();
|
||||||
|
loadCart.mockClear();
|
||||||
|
|
||||||
|
await (fixture.componentInstance as any).onCheckoutClick();
|
||||||
|
|
||||||
|
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
||||||
|
expect(loadCart).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
||||||
cartState.set({
|
cartState.set({
|
||||||
id: 1,
|
id: 1,
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
|
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 { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
NavigationEnd,
|
||||||
|
PRIMARY_OUTLET,
|
||||||
|
Router,
|
||||||
|
RouterOutlet,
|
||||||
|
} from '@angular/router';
|
||||||
|
import { filter } from 'rxjs';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||||
@@ -10,9 +18,13 @@ import { ButtonComponent } from '../../../shared/components/button/button.compon
|
|||||||
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
||||||
import { AuthService } from '../../services/auth/auth.service';
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { findMenu } from '../../services/menu.utils';
|
import { findMenu } from '../../services/menu.utils';
|
||||||
import { CheckoutService } from '../../services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
isExpiredStockReservationResponse,
|
||||||
|
} from '../../services/checkout.service';
|
||||||
import { ToastService } from '../../services/toast.service';
|
import { ToastService } from '../../services/toast.service';
|
||||||
import { Category } from '../../services/tenant.interface';
|
import { Category } from '../../services/tenant.interface';
|
||||||
|
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -31,12 +43,15 @@ 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);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
|
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||||
|
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly 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);
|
||||||
@@ -149,8 +164,22 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.router.events
|
||||||
|
.pipe(
|
||||||
|
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((event) => {
|
||||||
|
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
|
||||||
|
this.isCheckoutRoute.set(isCheckoutRoute);
|
||||||
|
|
||||||
|
if (isCheckoutRoute) {
|
||||||
|
this.isCartOpen.set(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||||
if (params.get('openCart') === 'true') {
|
if (params.get('openCart') === 'true' && !this.isCheckoutRoute()) {
|
||||||
this.isCartOpen.set(true);
|
this.isCartOpen.set(true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -160,10 +189,24 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private isCheckoutUrl(url: string): boolean {
|
||||||
|
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
||||||
|
|
||||||
|
return primarySegments[0]?.path === 'checkout';
|
||||||
|
}
|
||||||
|
|
||||||
protected onLoginClick(): void {
|
protected onLoginClick(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected onCartClick(): void {
|
||||||
|
if (this.isCheckoutRoute()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isCartOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
protected onSearch(term: string): void {
|
protected onSearch(term: string): void {
|
||||||
void this.router.navigate(['/buscar'], {
|
void this.router.navigate(['/buscar'], {
|
||||||
queryParams: { q: term, page: 1 },
|
queryParams: { q: term, page: 1 },
|
||||||
@@ -237,12 +280,20 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
await this.router.navigate(['/checkout'], {
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
queryParams: { purchase: purchase.id },
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create cart purchase:', error);
|
console.error('Failed to create cart purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra.';
|
||||||
|
this.toastService.danger(message);
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.isCreatingPurchase.set(false);
|
this.isCreatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,12 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
|
authGuard(null as never, { url: '/checkout/25' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
||||||
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
|
'/login?returnUrl=%2Fcheckout%2F25',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout' } as never),
|
authGuard(null as never, { url: '/checkout/25' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|||||||
@@ -83,6 +83,20 @@ describe('CartService', () => {
|
|||||||
req.flush({ data: mockCart });
|
req.flush({ data: mockCart });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
|
service.loadCart(true).subscribe();
|
||||||
|
|
||||||
|
expect(availabilityChanged).not.toHaveBeenCalled();
|
||||||
|
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
|
||||||
|
req.flush({ data: mockCart });
|
||||||
|
|
||||||
|
expect(service.cart()).toEqual(mockCart);
|
||||||
|
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('propagates a custom loading mode to the request context', () => {
|
it('propagates a custom loading mode to the request context', () => {
|
||||||
service.withCustomLoading().loadCart().subscribe();
|
service.withCustomLoading().loadCart().subscribe();
|
||||||
|
|
||||||
|
|||||||
@@ -34,14 +34,19 @@ export class CartService extends BaseApiService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadCart(): Observable<Cart> {
|
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
||||||
return this.http
|
return this.http
|
||||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
map((response) => response.data),
|
map((response) => response.data),
|
||||||
tap((cart) => this.cartState.set(cart)),
|
tap((cart) => {
|
||||||
|
this.cartState.set(cart);
|
||||||
|
if (refreshCatalogAvailability) {
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
|
}
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ export interface CatalogItemVariant {
|
|||||||
event_date_ids?: number[];
|
event_date_ids?: number[];
|
||||||
event_dates?: string[];
|
event_dates?: string[];
|
||||||
maximum_addable_quantity?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
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;
|
||||||
@@ -114,6 +115,7 @@ export interface CatalogFeaturedItemVariant {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string;
|
precio?: string;
|
||||||
maximum_addable_quantity?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
values: Record<string, CatalogVariantValue>;
|
values: Record<string, CatalogVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,6 +148,7 @@ export interface CatalogFeaturedItem {
|
|||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
maximum_addable_quantity?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
CatalogItemDetail,
|
CatalogItemDetail,
|
||||||
CatalogVariantOptionsResponse,
|
CatalogVariantOptionsResponse,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
Product,
|
|
||||||
} from './catalog.interface';
|
} from './catalog.interface';
|
||||||
|
|
||||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||||
@@ -33,12 +32,6 @@ export class CatalogService extends BaseApiService {
|
|||||||
return this.tenantService.getTenantApiUrl();
|
return this.tenantService.getTenantApiUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
|
|
||||||
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
|
|
||||||
params: this.buildHttpParams(params),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
||||||
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
||||||
}
|
}
|
||||||
|
|||||||
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { CheckoutCountdownService } from './checkout-countdown.service';
|
||||||
|
|
||||||
|
describe('CheckoutCountdownService', () => {
|
||||||
|
let service: CheckoutCountdownService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
|
||||||
|
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
|
||||||
|
service = TestBed.inject(CheckoutCountdownService);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
service.clear();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts down from the checkout server timing without depending on the client clock', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: '2026-08-27T15:10:00.000Z',
|
||||||
|
expires_in_seconds: 600,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(600);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(1_000);
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(599);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recalculates against the deadline after a delayed browser interval', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: 10,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
|
||||||
|
vi.advanceTimersByTime(1_000);
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the countdown when checkout has no expiration', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: null,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: 10,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
service.synchronize({});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(10);
|
||||||
|
});
|
||||||
|
});
|
||||||
97
src/app/core/services/checkout-countdown.service.ts
Normal file
97
src/app/core/services/checkout-countdown.service.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import { Injectable, OnDestroy, signal } from '@angular/core';
|
||||||
|
|
||||||
|
export interface CheckoutTiming {
|
||||||
|
expires_at: string | null;
|
||||||
|
expires_in_seconds: number | null;
|
||||||
|
server_time: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class CheckoutCountdownService implements OnDestroy {
|
||||||
|
private readonly remainingSecondsState = signal<number | null>(null);
|
||||||
|
private deadlineMs: number | null = null;
|
||||||
|
private intervalId: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
|
||||||
|
|
||||||
|
synchronize(timing: Partial<CheckoutTiming>): void {
|
||||||
|
const remainingSeconds = this.resolveRemainingSeconds(timing);
|
||||||
|
|
||||||
|
if (remainingSeconds === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainingSeconds === null) {
|
||||||
|
this.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.stopInterval();
|
||||||
|
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
|
||||||
|
this.updateRemainingSeconds();
|
||||||
|
|
||||||
|
if (remainingSeconds > 0) {
|
||||||
|
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.stopInterval();
|
||||||
|
this.deadlineMs = null;
|
||||||
|
this.remainingSecondsState.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
|
||||||
|
if (timing.expires_at === null && timing.expires_in_seconds === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expiresAt =
|
||||||
|
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
|
||||||
|
const serverTime =
|
||||||
|
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
|
||||||
|
|
||||||
|
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
|
||||||
|
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof timing.expires_in_seconds === 'number' &&
|
||||||
|
Number.isFinite(timing.expires_in_seconds)
|
||||||
|
) {
|
||||||
|
return Math.max(0, Math.ceil(timing.expires_in_seconds));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number.isFinite(expiresAt)) {
|
||||||
|
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateRemainingSeconds(): void {
|
||||||
|
if (this.deadlineMs === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
|
||||||
|
this.remainingSecondsState.set(remainingSeconds);
|
||||||
|
|
||||||
|
if (remainingSeconds === 0) {
|
||||||
|
this.stopInterval();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopInterval(): void {
|
||||||
|
if (this.intervalId !== null) {
|
||||||
|
clearInterval(this.intervalId);
|
||||||
|
this.intervalId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||||
import { CheckoutService } from './checkout.service';
|
import { CheckoutService } from './checkout.service';
|
||||||
|
|
||||||
describe('CheckoutService', () => {
|
describe('CheckoutService', () => {
|
||||||
@@ -38,4 +39,59 @@ describe('CheckoutService', () => {
|
|||||||
|
|
||||||
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refreshes catalog availability when starting checkout fails', async () => {
|
||||||
|
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||||
|
const notifyAvailabilityChanged = vi.spyOn(
|
||||||
|
catalogAvailabilityService,
|
||||||
|
'notifyAvailabilityChanged',
|
||||||
|
);
|
||||||
|
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||||
|
|
||||||
|
request.flush(
|
||||||
|
{ message: 'No hay stock disponible.' },
|
||||||
|
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(purchasePromise).rejects.toBeTruthy();
|
||||||
|
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
|
||||||
|
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||||
|
const notifyAvailabilityChanged = vi.spyOn(
|
||||||
|
catalogAvailabilityService,
|
||||||
|
'notifyAvailabilityChanged',
|
||||||
|
);
|
||||||
|
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||||
|
|
||||||
|
request.flush(
|
||||||
|
{
|
||||||
|
code: 'stock_reservation.expired',
|
||||||
|
message: 'La reserva de stock venció.',
|
||||||
|
},
|
||||||
|
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(purchasePromise).rejects.toBeTruthy();
|
||||||
|
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves checkout timing fields when completing a purchase', async () => {
|
||||||
|
const purchasePromise = service.completePurchase('desfile', 55);
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
|
||||||
|
const response = {
|
||||||
|
status: 'pending_payment',
|
||||||
|
expires_at: '2026-08-26T20:00:00.000Z',
|
||||||
|
expires_in_seconds: 900,
|
||||||
|
server_time: '2026-08-26T19:45:00.000Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
request.flush({ data: response });
|
||||||
|
|
||||||
|
await expect(purchasePromise).resolves.toEqual(response);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { Injectable } from '@angular/core';
|
import { inject, Injectable } from '@angular/core';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||||
|
import { 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;
|
||||||
@@ -43,6 +46,21 @@ export function isInsufficientStockResponse(value: unknown): value is Insufficie
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ExpiredStockReservationResponse {
|
||||||
|
code: 'stock_reservation.expired';
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isExpiredStockReservationResponse(
|
||||||
|
value: unknown,
|
||||||
|
): value is ExpiredStockReservationResponse {
|
||||||
|
return (
|
||||||
|
typeof value === 'object' &&
|
||||||
|
value !== null &&
|
||||||
|
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export type StartCheckoutPayload =
|
export type StartCheckoutPayload =
|
||||||
| {
|
| {
|
||||||
cart_id: number;
|
cart_id: number;
|
||||||
@@ -53,6 +71,32 @@ export type StartCheckoutPayload =
|
|||||||
|
|
||||||
export interface PurchaseStatusResponse {
|
export interface PurchaseStatusResponse {
|
||||||
status: string | null;
|
status: string | null;
|
||||||
|
expires_at: string | null;
|
||||||
|
expires_in_seconds: number | null;
|
||||||
|
server_time: string;
|
||||||
|
payment_verification?: PurchasePaymentVerificationResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PurchasePaymentCandidateReason =
|
||||||
|
| 'ambiguous_exact_match'
|
||||||
|
| 'exact_dni_near_amount'
|
||||||
|
| 'exact_amount_near_dni';
|
||||||
|
|
||||||
|
export interface PurchasePaymentCandidatePrimaryResponse {
|
||||||
|
reason: PurchasePaymentCandidateReason;
|
||||||
|
dni_distance: number | null;
|
||||||
|
payment_amount: string;
|
||||||
|
purchase_amount: string;
|
||||||
|
amount_difference: string;
|
||||||
|
confidence: 'exact' | 'high' | 'medium';
|
||||||
|
detected_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchasePaymentVerificationResponse {
|
||||||
|
status: 'pending' | 'candidate';
|
||||||
|
candidate_count: number;
|
||||||
|
primary: PurchasePaymentCandidatePrimaryResponse | null;
|
||||||
|
reasons: PurchasePaymentCandidateReason[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
||||||
@@ -89,7 +133,6 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
user_id: number;
|
user_id: number;
|
||||||
created_at: string | null;
|
created_at: string | null;
|
||||||
payment_method: string | null;
|
payment_method: string | null;
|
||||||
expires_at: string | null;
|
|
||||||
dni: string | null;
|
dni: string | null;
|
||||||
transfer_payer_dni: string | null;
|
transfer_payer_dni: string | null;
|
||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
@@ -107,24 +150,34 @@ 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> {
|
||||||
const response = await firstValueFrom(
|
try {
|
||||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
const response = await firstValueFrom(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
payload,
|
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||||
),
|
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(
|
||||||
@@ -169,25 +222,6 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
|
||||||
const response = await firstValueFrom(
|
|
||||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
|
||||||
{},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
|
||||||
|
|
||||||
if (!purchase) {
|
|
||||||
throw new Error('Error al finalizar la compra.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: purchase.status ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async submitPurchaseForReview(
|
async submitPurchaseForReview(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
@@ -204,7 +238,7 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { status: purchase.status ?? null };
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
@@ -220,18 +254,26 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al cancelar la compra.');
|
throw new Error('Error al cancelar la compra.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { status: purchase.status ?? null };
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPurchases(
|
async getPurchases(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
status?: string,
|
status?: string,
|
||||||
): Promise<{ data: PurchaseSummaryResponse[] }> {
|
pagination: ApiPaginationQueryParams = {},
|
||||||
let url = `${environment.url}tenants/${tenantCode}/compras`;
|
): Promise<ApiPaginatedResponse<PurchaseSummaryResponse[]>> {
|
||||||
if (status) {
|
const params: Record<string, string | number> = {};
|
||||||
url += `?status=${status}`;
|
|
||||||
}
|
if (status) params['status'] = status;
|
||||||
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
|
if (pagination.page) params['page'] = pagination.page;
|
||||||
|
if (pagination.per_page) params['per_page'] = pagination.per_page;
|
||||||
|
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.http.get<ApiPaginatedResponse<PurchaseSummaryResponse[]>>(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras`,
|
||||||
|
{ params },
|
||||||
|
),
|
||||||
|
);
|
||||||
if (!response) {
|
if (!response) {
|
||||||
throw new Error('Error al obtener las compras.');
|
throw new Error('Error al obtener las compras.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
||||||
@@ -258,6 +259,36 @@ describe('ModalService', () => {
|
|||||||
showCloseButton: true,
|
showCloseButton: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the image viewer fullscreen with normalized zoom limits', () => {
|
||||||
|
service.openImage({
|
||||||
|
title: 'Producto',
|
||||||
|
src: '/images/producto.webp',
|
||||||
|
alt: 'Producto visto de frente',
|
||||||
|
initialZoom: 8,
|
||||||
|
minZoom: 0,
|
||||||
|
maxZoom: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeModal = service.activeModal();
|
||||||
|
|
||||||
|
expect(activeModal?.component).toBe(ImageModalComponent);
|
||||||
|
expect(activeModal?.config).toEqual({
|
||||||
|
title: 'Producto',
|
||||||
|
size: 'full',
|
||||||
|
presentation: 'fullscreen-media',
|
||||||
|
data: {
|
||||||
|
src: '/images/producto.webp',
|
||||||
|
alt: 'Producto visto de frente',
|
||||||
|
initialZoom: 3,
|
||||||
|
minZoom: 0.1,
|
||||||
|
maxZoom: 3,
|
||||||
|
},
|
||||||
|
closeOnBackdrop: true,
|
||||||
|
closeOnEscape: true,
|
||||||
|
showCloseButton: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
|
|||||||
@@ -2,16 +2,19 @@ import { InjectionToken, Injectable, Type, signal } from '@angular/core';
|
|||||||
import { Observable, Subject, map } from 'rxjs';
|
import { Observable, Subject, map } from 'rxjs';
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
|
|
||||||
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||||
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced';
|
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced' | 'swipe';
|
||||||
|
export type ModalPresentation = 'dialog' | 'fullscreen-media';
|
||||||
|
|
||||||
export interface ModalConfig<TData = unknown> {
|
export interface ModalConfig<TData = unknown> {
|
||||||
title?: string;
|
title?: string;
|
||||||
data?: TData;
|
data?: TData;
|
||||||
size?: ModalSize;
|
size?: ModalSize;
|
||||||
|
presentation?: ModalPresentation;
|
||||||
closeOnBackdrop?: boolean;
|
closeOnBackdrop?: boolean;
|
||||||
closeOnEscape?: boolean;
|
closeOnEscape?: boolean;
|
||||||
showCloseButton?: boolean;
|
showCloseButton?: boolean;
|
||||||
@@ -62,6 +65,25 @@ export interface QrModalConfig extends Omit<ModalConfig<QrModalData>, 'data' | '
|
|||||||
ticket: string;
|
ticket: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ImageModalData {
|
||||||
|
src: string;
|
||||||
|
alt: string;
|
||||||
|
initialZoom: number;
|
||||||
|
minZoom: number;
|
||||||
|
maxZoom: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageModalConfig extends Omit<
|
||||||
|
ModalConfig<ImageModalData>,
|
||||||
|
'data' | 'presentation' | 'size'
|
||||||
|
> {
|
||||||
|
src: string;
|
||||||
|
alt: string;
|
||||||
|
initialZoom?: number;
|
||||||
|
minZoom?: number;
|
||||||
|
maxZoom?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
||||||
component: Type<unknown>;
|
component: Type<unknown>;
|
||||||
config: NormalizedModalConfig<TData>;
|
config: NormalizedModalConfig<TData>;
|
||||||
@@ -195,6 +217,33 @@ export class ModalService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
openImage(config: ImageModalConfig): Observable<void> {
|
||||||
|
return this.openImageRef(config).afterClosed$.pipe(map(() => undefined));
|
||||||
|
}
|
||||||
|
|
||||||
|
openImageRef(config: ImageModalConfig): ModalRef<void> {
|
||||||
|
const { src, alt, initialZoom = 1, minZoom = 1, maxZoom = 4, ...modalConfig } = config;
|
||||||
|
const normalizedMinZoom = Math.max(0.1, minZoom);
|
||||||
|
const normalizedMaxZoom = Math.max(normalizedMinZoom, maxZoom);
|
||||||
|
const normalizedInitialZoom = Math.min(
|
||||||
|
normalizedMaxZoom,
|
||||||
|
Math.max(normalizedMinZoom, initialZoom),
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.open(ImageModalComponent, {
|
||||||
|
...modalConfig,
|
||||||
|
size: 'full',
|
||||||
|
presentation: 'fullscreen-media',
|
||||||
|
data: {
|
||||||
|
src,
|
||||||
|
alt,
|
||||||
|
initialZoom: normalizedInitialZoom,
|
||||||
|
minZoom: normalizedMinZoom,
|
||||||
|
maxZoom: normalizedMaxZoom,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
||||||
if (this.activeModalState()?.ref !== ref) {
|
if (this.activeModalState()?.ref !== ref) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -83,6 +83,9 @@
|
|||||||
Abrir modal ancho
|
Abrir modal ancho
|
||||||
</app-button>
|
</app-button>
|
||||||
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
||||||
|
<app-button variant="secondary" (click)="openImageModal()">
|
||||||
|
Abrir visor de imagen
|
||||||
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-showcase__result" data-testid="modal-last-result">
|
<div class="modal-showcase__result" data-testid="modal-last-result">
|
||||||
{{ lastModalResult }}
|
{{ lastModalResult }}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ function createModalServiceStub() {
|
|||||||
open: vi.fn(),
|
open: vi.fn(),
|
||||||
openConfirm: vi.fn().mockReturnValue(of(true)),
|
openConfirm: vi.fn().mockReturnValue(of(true)),
|
||||||
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
||||||
|
openImage: vi.fn().mockReturnValue(of(undefined)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,6 +282,9 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
const deleteButton = buttons.find((button) =>
|
const deleteButton = buttons.find((button) =>
|
||||||
button.textContent?.includes('Abrir confirm delete'),
|
button.textContent?.includes('Abrir confirm delete'),
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
const imageButton = buttons.find((button) =>
|
||||||
|
button.textContent?.includes('Abrir visor de imagen'),
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Todavia no se abrio ningun modal.',
|
'Todavia no se abrio ningun modal.',
|
||||||
@@ -290,6 +294,8 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
deleteButton.click();
|
deleteButton.click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
imageButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
||||||
title: 'Confirmar accion',
|
title: 'Confirmar accion',
|
||||||
@@ -302,6 +308,11 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
});
|
});
|
||||||
|
expect(modalServiceStub.openImage).toHaveBeenCalledWith({
|
||||||
|
title: 'Mochila urbana roja',
|
||||||
|
src: '/images/carousel-mochila-roja.webp',
|
||||||
|
alt: 'Mochila urbana roja vista de frente',
|
||||||
|
});
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Resultado: false',
|
'Resultado: false',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -493,6 +493,14 @@ export class ReutilizablesTestPageComponent {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openImageModal(): void {
|
||||||
|
this.modalService.openImage({
|
||||||
|
title: 'Mochila urbana roja',
|
||||||
|
src: '/images/carousel-mochila-roja.webp',
|
||||||
|
alt: 'Mochila urbana roja vista de frente',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
||||||
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
||||||
this.lastModalResult = `Resultado: ${confirmed}`;
|
this.lastModalResult = `Resultado: ${confirmed}`;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
.menu-content-section__header {
|
.menu-content-section__header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.75rem;
|
gap: var(--menu-content-prefix-gap, 0.75rem);
|
||||||
margin-bottom: 1.25rem;
|
margin-bottom: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,29 @@
|
|||||||
<div class="purchase-item" [routerLink]="[purchase.id]" style="cursor: pointer;">
|
<div class="purchase-item" [routerLink]="[purchase.id]">
|
||||||
<div class="purchase-info">
|
<div class="purchase-info">
|
||||||
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
||||||
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="purchase-action">
|
|
||||||
<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow-icon">
|
@if (purchase.statusMessage) {
|
||||||
<path d="M1 1L7 7L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
<span class="purchase-status">{{ purchase.statusMessage }}</span>
|
||||||
</svg>
|
}
|
||||||
</div>
|
|
||||||
</div>
|
<div class="purchase-action">
|
||||||
|
<svg
|
||||||
|
width="8"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 8 14"
|
||||||
|
fill="none"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="arrow-icon"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M1 1L7 7L1 13"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|||||||
@@ -2,33 +2,57 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 16px;
|
gap: 16px;
|
||||||
padding-left:0;
|
padding: 16px;
|
||||||
transition: box-shadow 0.2s, border-radius 0.2s;
|
padding-left: 0;
|
||||||
|
transition:
|
||||||
|
box-shadow 0.2s,
|
||||||
|
border-radius 0.2s;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-item:hover {
|
.purchase-item:hover {
|
||||||
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
|
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-item:hover .arrow-icon {
|
.purchase-item:hover .arrow-icon {
|
||||||
color: #5b75ff; /* Blue on hover */
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-info {
|
.purchase-info {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-id {
|
.purchase-id {
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-date {
|
.purchase-date {
|
||||||
font-weight: 325;
|
font-weight: 325;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-status {
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 20px;
|
||||||
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-action {
|
||||||
|
display: flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
.arrow-icon {
|
.arrow-icon {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
height: 14px;
|
height: 14px;
|
||||||
|
|||||||
@@ -9,6 +9,5 @@ import { RouterLink } from '@angular/router';
|
|||||||
styleUrl: './purchase-list-item.scss',
|
styleUrl: './purchase-list-item.scss',
|
||||||
})
|
})
|
||||||
export class PurchaseListItem {
|
export class PurchaseListItem {
|
||||||
@Input() purchase!: { id: number; date: string };
|
@Input() purchase!: { id: number; date: string; statusMessage?: string | null };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,29 +1,36 @@
|
|||||||
<div class="purchase-list-container">
|
<div class="purchase-list-container">
|
||||||
<ng-container *ngIf="isLoading(); else contentTpl">
|
@if (isLoading()) {
|
||||||
<!-- Skeleton -->
|
@for (i of [1, 2, 3, 4]; track i) {
|
||||||
<div class="skeleton-item" *ngFor="let i of [1, 2, 3, 4]">
|
<div class="skeleton-item">
|
||||||
<div class="skeleton-info">
|
<div class="skeleton-info">
|
||||||
<div class="skeleton-id"></div>
|
<div class="skeleton-id"></div>
|
||||||
<div class="skeleton-date"></div>
|
<div class="skeleton-date"></div>
|
||||||
</div>
|
|
||||||
<div class="skeleton-action"></div>
|
|
||||||
</div>
|
</div>
|
||||||
</ng-container>
|
<div class="skeleton-action"></div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
@if (purchases().length > 0) {
|
||||||
|
@for (purchase of purchases(); track purchase.id; let last = $last) {
|
||||||
|
<app-purchase-list-item [purchase]="purchase"></app-purchase-list-item>
|
||||||
|
@if (!last) {
|
||||||
|
<div class="purchase-divider"></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<div class="empty-state">Aún no hay compras realizadas</div>
|
||||||
|
}
|
||||||
|
|
||||||
<ng-template #contentTpl>
|
@if (pagination(); as paginationData) {
|
||||||
<ng-container *ngIf="purchases().length > 0; else emptyTpl">
|
@if (paginationData.last_page > 1) {
|
||||||
<ng-container *ngFor="let purchase of purchases(); let last = last">
|
<app-paginator
|
||||||
<app-purchase-list-item
|
class="purchase-list__paginator"
|
||||||
[purchase]="purchase">
|
[page]="paginationData.current_page"
|
||||||
</app-purchase-list-item>
|
[totalPages]="paginationData.last_page"
|
||||||
<div class="purchase-divider" *ngIf="!last"></div>
|
[disabled]="isLoading()"
|
||||||
</ng-container>
|
(pageChange)="onPageChange($event)"
|
||||||
</ng-container>
|
></app-paginator>
|
||||||
</ng-template>
|
}
|
||||||
|
}
|
||||||
<ng-template #emptyTpl>
|
}
|
||||||
<div class="empty-state">
|
</div>
|
||||||
Aún no hay compras realizadas
|
|
||||||
</div>
|
|
||||||
</ng-template>
|
|
||||||
</div>
|
|
||||||
|
|||||||
@@ -4,9 +4,14 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-list__paginator {
|
||||||
|
align-self: center;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
.purchase-divider {
|
.purchase-divider {
|
||||||
height: 1px;
|
height: 1px;
|
||||||
background-color: #DDDDDD;
|
background-color: #dddddd;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +44,7 @@
|
|||||||
.skeleton-id {
|
.skeleton-id {
|
||||||
width: 100px;
|
width: 100px;
|
||||||
height: 1rem;
|
height: 1rem;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
@@ -47,7 +52,7 @@
|
|||||||
.skeleton-date {
|
.skeleton-date {
|
||||||
width: 150px;
|
width: 150px;
|
||||||
height: 0.8rem;
|
height: 0.8rem;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
@@ -55,19 +60,19 @@
|
|||||||
.skeleton-action {
|
.skeleton-action {
|
||||||
width: 24px;
|
width: 24px;
|
||||||
height: 24px;
|
height: 24px;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes pulse {
|
@keyframes pulse {
|
||||||
0% {
|
0% {
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
}
|
}
|
||||||
50% {
|
50% {
|
||||||
background-color: #E0E0E0;
|
background-color: #e0e0e0;
|
||||||
}
|
}
|
||||||
100% {
|
100% {
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,24 @@
|
|||||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
|
||||||
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
|
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
|
||||||
import { CheckoutService, PurchaseSummaryResponse } from '../../../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
PurchaseSummaryResponse,
|
||||||
|
} from '../../../../../../core/services/checkout.service';
|
||||||
import { ToastService } from '../../../../../../core/services/toast.service';
|
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||||
import { TenantService } from '../../../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||||
|
import { ApiPaginationMeta } from '../../../../../../core/services/api-paginated-response.interface';
|
||||||
|
import { PaginatorComponent } from '../../../../../../shared/components/paginator/paginator.component';
|
||||||
|
|
||||||
type PurchaseListViewModel = {
|
type PurchaseListViewModel = {
|
||||||
id: number;
|
id: number;
|
||||||
date: string;
|
date: string;
|
||||||
|
statusMessage: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-list',
|
selector: 'app-purchase-list',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, PurchaseListItem],
|
imports: [PurchaseListItem, PaginatorComponent],
|
||||||
templateUrl: './purchase-list.html',
|
templateUrl: './purchase-list.html',
|
||||||
styleUrl: './purchase-list.scss',
|
styleUrl: './purchase-list.scss',
|
||||||
})
|
})
|
||||||
@@ -22,21 +27,28 @@ export class PurchaseList implements OnInit {
|
|||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
|
||||||
purchases = signal<PurchaseListViewModel[]>([]);
|
protected readonly purchases = signal<PurchaseListViewModel[]>([]);
|
||||||
isLoading = signal<boolean>(true);
|
protected readonly pagination = signal<ApiPaginationMeta | null>(null);
|
||||||
|
protected readonly isLoading = signal(true);
|
||||||
|
|
||||||
async ngOnInit(): Promise<void> {
|
async ngOnInit(): Promise<void> {
|
||||||
|
await this.loadPurchases();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPageChange(page: number): Promise<void> {
|
||||||
|
await this.loadPurchases(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadPurchases(page = 1): Promise<void> {
|
||||||
|
this.isLoading.set(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const tenantCode = this.tenantService.tenant()?.codigo || '';
|
|
||||||
|
|
||||||
const response = await this.checkoutService
|
const response = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.getPurchases(tenantCode, 'paid');
|
.getPurchases(this.tenantCode(), 'paid,in_review', { page });
|
||||||
const mappedPurchases = response.data.map((purchase: PurchaseSummaryResponse) => ({
|
|
||||||
id: purchase.id,
|
this.purchases.set(this.mapPurchases(response.data));
|
||||||
date: this.formatDate(purchase.created_at),
|
this.pagination.set(response.meta);
|
||||||
}));
|
|
||||||
this.purchases.set(mappedPurchases);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.toastService.danger('Hubo un error al cargar las compras');
|
this.toastService.danger('Hubo un error al cargar las compras');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -44,6 +56,18 @@ export class PurchaseList implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private tenantCode(): string {
|
||||||
|
return this.tenantService.tenant()?.codigo || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapPurchases(purchases: PurchaseSummaryResponse[]): PurchaseListViewModel[] {
|
||||||
|
return purchases.map((purchase) => ({
|
||||||
|
id: purchase.id,
|
||||||
|
date: this.formatDate(purchase.created_at),
|
||||||
|
statusMessage: purchase.status === 'in_review' ? 'Esperando confirmación' : null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
private formatDate(value: string | null): string {
|
private formatDate(value: string | null): string {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return '-';
|
return '-';
|
||||||
|
|||||||
@@ -15,6 +15,27 @@
|
|||||||
@if (isLoading()) {
|
@if (isLoading()) {
|
||||||
<p class="purchase-loading">Cargando detalle de compra...</p>
|
<p class="purchase-loading">Cargando detalle de compra...</p>
|
||||||
} @else if (purchase(); as purchase) {
|
} @else if (purchase(); as purchase) {
|
||||||
|
@if (purchase.isInReview) {
|
||||||
|
<section class="purchase-review" aria-labelledby="purchase-review-title">
|
||||||
|
<h3 id="purchase-review-title" class="purchase-review__title">ESPERANDO CONFIRMACIÓN</h3>
|
||||||
|
<p class="purchase-review__message">
|
||||||
|
Tu compra aún no ha sido confirmada.<br />
|
||||||
|
Si no te contactaste con nosotros, podés hacerlo a través del siguiente WhatsApp
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (whatsappUrl()) {
|
||||||
|
<app-button
|
||||||
|
type="button"
|
||||||
|
variant="primary"
|
||||||
|
hostClass="purchase-review__button"
|
||||||
|
(click)="openWhatsApp()"
|
||||||
|
>
|
||||||
|
WhatsApp
|
||||||
|
</app-button>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="d-flex justify-content-between align-items-center mb-4 pb-3"
|
class="d-flex justify-content-between align-items-center mb-4 pb-3"
|
||||||
style="border-bottom: 1px solid #dddddd"
|
style="border-bottom: 1px solid #dddddd"
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.account-page {
|
.account-page {
|
||||||
|
--menu-content-prefix-gap: 0;
|
||||||
|
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 600px;
|
max-width: 600px;
|
||||||
@@ -50,6 +52,32 @@
|
|||||||
font-size: 17px;
|
font-size: 17px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-review {
|
||||||
|
padding-bottom: 2rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
border-bottom: 1px solid #dddddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__title {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__message {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: #777777;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__button {
|
||||||
|
width: 185px;
|
||||||
|
}
|
||||||
|
|
||||||
.purchase-loading,
|
.purchase-loading,
|
||||||
.purchase-empty {
|
.purchase-empty {
|
||||||
color: #666666;
|
color: #666666;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { CommonModule } from '@angular/common';
|
import { Component, OnInit, computed, inject, signal } from '@angular/core';
|
||||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
|
||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -8,6 +7,7 @@ import {
|
|||||||
} from '../../../../../../core/services/checkout.service';
|
} from '../../../../../../core/services/checkout.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 { ButtonComponent } from '../../../../../../shared/components/button/button.component';
|
||||||
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
|
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
|
||||||
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
|
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
|
||||||
|
|
||||||
@@ -16,12 +16,13 @@ type PurchaseDetailViewModel = {
|
|||||||
date: string;
|
date: string;
|
||||||
total: string;
|
total: string;
|
||||||
items: PurchaseItemViewModel[];
|
items: PurchaseItemViewModel[];
|
||||||
|
isInReview: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-detail-page',
|
selector: 'app-purchase-detail-page',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, RouterLink, PurchaseItem, MenuContentSectionComponent],
|
imports: [RouterLink, PurchaseItem, MenuContentSectionComponent, ButtonComponent],
|
||||||
templateUrl: './purchase-detail-page.html',
|
templateUrl: './purchase-detail-page.html',
|
||||||
styleUrl: './purchase-detail-page.scss',
|
styleUrl: './purchase-detail-page.scss',
|
||||||
})
|
})
|
||||||
@@ -34,6 +35,12 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
|
|
||||||
readonly isLoading = signal(true);
|
readonly isLoading = signal(true);
|
||||||
readonly purchase = signal<PurchaseDetailViewModel | null>(null);
|
readonly purchase = signal<PurchaseDetailViewModel | null>(null);
|
||||||
|
protected readonly whatsappUrl = computed(
|
||||||
|
() =>
|
||||||
|
this.tenantService
|
||||||
|
.tenant()
|
||||||
|
?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? null,
|
||||||
|
);
|
||||||
|
|
||||||
async ngOnInit(): Promise<void> {
|
async ngOnInit(): Promise<void> {
|
||||||
const purchaseId = this.route.snapshot.paramMap.get('id');
|
const purchaseId = this.route.snapshot.paramMap.get('id');
|
||||||
@@ -54,6 +61,7 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
date: this.formatDate(response.created_at),
|
date: this.formatDate(response.created_at),
|
||||||
total: response.total,
|
total: response.total,
|
||||||
items: this.mapItems(response),
|
items: this.mapItems(response),
|
||||||
|
isInReview: response.status === 'in_review',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to fetch purchase detail:', error);
|
console.error('Failed to fetch purchase detail:', error);
|
||||||
@@ -64,6 +72,14 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openWhatsApp(): void {
|
||||||
|
const url = this.whatsappUrl();
|
||||||
|
|
||||||
|
if (url) {
|
||||||
|
window.open(url, '_blank', 'noopener,noreferrer');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private formatDate(value: string | null): string {
|
private formatDate(value: string | null): string {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return '-';
|
return '-';
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ import {
|
|||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
isExpiredStockReservationResponse,
|
||||||
|
} from '../../../../core/services/checkout.service';
|
||||||
import {
|
import {
|
||||||
CatalogGroupLayout,
|
CatalogGroupLayout,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
@@ -167,10 +170,20 @@ export class CategoryItemsPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra directa.';
|
||||||
|
this.toastService.danger(message);
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,11 @@
|
|||||||
} @else {
|
} @else {
|
||||||
<div class="checkout-page">
|
<div class="checkout-page">
|
||||||
<div class="checkout-page__stepper-col">
|
<div class="checkout-page__stepper-col">
|
||||||
<app-stepper #stepper [initialStepIndex]="checkoutStepIndex()">
|
<app-stepper
|
||||||
|
#stepper
|
||||||
|
[initialStepIndex]="checkoutStepIndex()"
|
||||||
|
[disabled]="hasSubmittedTransfer()"
|
||||||
|
>
|
||||||
<app-step label="Datos" [isValid]="isStep1Valid()">
|
<app-step label="Datos" [isValid]="isStep1Valid()">
|
||||||
<app-checkout-data-step
|
<app-checkout-data-step
|
||||||
[form]="form"
|
[form]="form"
|
||||||
@@ -19,6 +23,7 @@
|
|||||||
<app-checkout-payment-step
|
<app-checkout-payment-step
|
||||||
[paymentMethods]="paymentMethods"
|
[paymentMethods]="paymentMethods"
|
||||||
[selectedPaymentMethod]="selectedPaymentMethod()"
|
[selectedPaymentMethod]="selectedPaymentMethod()"
|
||||||
|
[paymentMethodDisabled]="hasSubmittedTransfer()"
|
||||||
[copiedTransferField]="copiedTransferField()"
|
[copiedTransferField]="copiedTransferField()"
|
||||||
[transferAccount]="transferAccount()"
|
[transferAccount]="transferAccount()"
|
||||||
[transferDni]="transferDni()"
|
[transferDni]="transferDni()"
|
||||||
@@ -29,6 +34,7 @@
|
|||||||
[qrPaymentAmount]="cartTotal()"
|
[qrPaymentAmount]="cartTotal()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
[transferValidationStatus]="transferValidationStatus()"
|
[transferValidationStatus]="transferValidationStatus()"
|
||||||
|
[transferVerificationErrorTitle]="transferVerificationErrorTitle()"
|
||||||
(paymentMethodChange)="selectPaymentMethod($event)"
|
(paymentMethodChange)="selectPaymentMethod($event)"
|
||||||
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
||||||
(cancelStep)="onCancel()"
|
(cancelStep)="onCancel()"
|
||||||
@@ -41,6 +47,17 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="checkout-page__cart-col">
|
<div class="checkout-page__cart-col">
|
||||||
|
@if (checkoutRemainingTime(); as remainingTime) {
|
||||||
|
<div
|
||||||
|
class="checkout-page__mobile-countdown d-flex d-md-none align-items-baseline justify-content-center gap-3"
|
||||||
|
role="timer"
|
||||||
|
aria-label="Tiempo restante de compra"
|
||||||
|
>
|
||||||
|
<span class="checkout-page__mobile-countdown-label">Tiempo restante de compra:</span>
|
||||||
|
<span class="checkout-page__mobile-countdown-value">{{ remainingTime }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
<app-cart
|
<app-cart
|
||||||
title="COMPRA"
|
title="COMPRA"
|
||||||
[items]="mappedCartItems()"
|
[items]="mappedCartItems()"
|
||||||
@@ -51,7 +68,7 @@
|
|||||||
[allowModify]="true"
|
[allowModify]="true"
|
||||||
[showModifyWhenReadonly]="true"
|
[showModifyWhenReadonly]="true"
|
||||||
[modifyAsAction]="true"
|
[modifyAsAction]="true"
|
||||||
[editingDisabled]="isCancellingPurchase()"
|
[editingDisabled]="isPurchaseModificationDisabled()"
|
||||||
backgroundColor="transparent"
|
backgroundColor="transparent"
|
||||||
(modify)="onModifyPurchase()"
|
(modify)="onModifyPurchase()"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -28,6 +28,24 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&__mobile-countdown {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
color: var(--tenant-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__mobile-countdown-label {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__mobile-countdown-value {
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.checkout-page__loading {
|
.checkout-page__loading {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { signal } from '@angular/core';
|
|||||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
||||||
|
import { of } from 'rxjs';
|
||||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
@@ -11,7 +12,9 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
|
|||||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.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 { 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', () => {
|
||||||
@@ -30,7 +33,8 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
start: ReturnType<typeof vi.fn>;
|
start: ReturnType<typeof vi.fn>;
|
||||||
stop: ReturnType<typeof vi.fn>;
|
stop: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
||||||
|
let routeParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
let tenantState: ReturnType<
|
let tenantState: ReturnType<
|
||||||
typeof signal<{
|
typeof signal<{
|
||||||
@@ -62,7 +66,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
generatePaymentIntent: vi.fn().mockResolvedValue({
|
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||||
qr_data: { qr_code: 'qr-value' },
|
qr_data: { qr_code: 'qr-value' },
|
||||||
}),
|
}),
|
||||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'in_review' }),
|
||||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
withCustomLoading: vi.fn(),
|
withCustomLoading: vi.fn(),
|
||||||
};
|
};
|
||||||
@@ -70,7 +74,10 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
routerStub = { navigate: vi.fn() };
|
routerStub = { navigate: vi.fn() };
|
||||||
toastServiceStub = { danger: vi.fn() };
|
toastServiceStub = { danger: vi.fn() };
|
||||||
globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() };
|
globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() };
|
||||||
routeQueryParamMap = convertToParamMap({});
|
cartServiceStub = {
|
||||||
|
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
||||||
|
};
|
||||||
|
routeParamMap = convertToParamMap({});
|
||||||
authUserState = signal(null);
|
authUserState = signal(null);
|
||||||
tenantState = signal({
|
tenantState = signal({
|
||||||
codigo: 'tenant-test',
|
codigo: 'tenant-test',
|
||||||
@@ -92,12 +99,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
{ provide: AuthService, useValue: { user: authUserState } },
|
{ provide: AuthService, useValue: { user: authUserState } },
|
||||||
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
|
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
|
||||||
{ provide: ToastService, useValue: toastServiceStub },
|
{ provide: ToastService, useValue: toastServiceStub },
|
||||||
|
{ provide: CartService, useValue: cartServiceStub },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
snapshot: {
|
snapshot: {
|
||||||
get queryParamMap() {
|
get paramMap() {
|
||||||
return routeQueryParamMap;
|
return routeParamMap;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -122,6 +130,93 @@ 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('checks the purchase when the countdown expires and redirects to the expired status', async () => {
|
||||||
|
const countdown = TestBed.inject(CheckoutCountdownService);
|
||||||
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'expired' });
|
||||||
|
const { fixture, component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
expires_at: new Date(Date.now() + 1_000).toISOString(),
|
||||||
|
expires_in_seconds: 1,
|
||||||
|
server_time: new Date().toISOString(),
|
||||||
|
items: [],
|
||||||
|
subtotal: '0.00',
|
||||||
|
total: '0.00',
|
||||||
|
});
|
||||||
|
countdown.synchronize(component.createdPurchase());
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1_000);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledOnce();
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('checks the purchase only once when the expired countdown remains at zero', async () => {
|
||||||
|
const countdown = TestBed.inject(CheckoutCountdownService);
|
||||||
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
|
status: 'pending_payment',
|
||||||
|
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
||||||
|
expires_in_seconds: 0,
|
||||||
|
server_time: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
const { fixture, component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'pending_payment',
|
||||||
|
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
||||||
|
expires_in_seconds: 0,
|
||||||
|
server_time: new Date().toISOString(),
|
||||||
|
items: [],
|
||||||
|
subtotal: '0.00',
|
||||||
|
total: '0.00',
|
||||||
|
});
|
||||||
|
countdown.synchronize(component.createdPurchase());
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
await Promise.resolve();
|
||||||
|
fixture.detectChanges();
|
||||||
|
await vi.advanceTimersByTimeAsync(5_000);
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledOnce();
|
||||||
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
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' })
|
||||||
@@ -188,7 +283,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('polls a transfer every three seconds up to four attempts', async () => {
|
it('polls a transfer every three seconds for one minute', async () => {
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
@@ -198,19 +293,36 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
await vi.advanceTimersByTimeAsync(57_000);
|
||||||
await vi.advanceTimersByTimeAsync(3_000);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
expect(component.transferValidationStatus()).toBe('checking');
|
|
||||||
}
|
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(3_000);
|
await vi.advanceTimersByTimeAsync(3_000);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('prevents modifying the purchase after Ya transferí is clicked', async () => {
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
|
await component.onComplete();
|
||||||
|
|
||||||
|
expect(component.hasSubmittedTransfer()).toBe(true);
|
||||||
|
expect(component.isPurchaseModificationDisabled()).toBe(true);
|
||||||
|
|
||||||
|
await component.selectPaymentMethod('qr');
|
||||||
|
await component.onModifyPurchase();
|
||||||
|
|
||||||
|
expect(component.selectedPaymentMethod()).toBe('transfer');
|
||||||
|
expect(checkoutServiceStub.generatePaymentIntent).not.toHaveBeenCalled();
|
||||||
|
expect(checkoutServiceStub.cancelPurchase).not.toHaveBeenCalled();
|
||||||
|
expect(globalLoadingServiceStub.start).not.toHaveBeenCalled();
|
||||||
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('navigates after a transfer is confirmed as paid', async () => {
|
it('navigates after a transfer is confirmed as paid', async () => {
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
@@ -230,13 +342,43 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
await vi.advanceTimersByTimeAsync(12_000);
|
await vi.advanceTimersByTimeAsync(60_000);
|
||||||
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('uses the primary candidate reason when transfer polling times out', async () => {
|
||||||
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
|
status: 'in_review',
|
||||||
|
payment_verification: {
|
||||||
|
status: 'candidate',
|
||||||
|
candidate_count: 1,
|
||||||
|
primary: {
|
||||||
|
reason: 'exact_amount_near_dni',
|
||||||
|
dni_distance: 1,
|
||||||
|
payment_amount: '300000.00',
|
||||||
|
purchase_amount: '300000.00',
|
||||||
|
amount_difference: '0.00',
|
||||||
|
confidence: 'medium',
|
||||||
|
detected_at: '2026-08-27T18:00:00-03:00',
|
||||||
|
},
|
||||||
|
reasons: ['exact_amount_near_dni'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(60_000);
|
||||||
|
|
||||||
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
|
expect(component.transferVerificationErrorTitle()).toBe(
|
||||||
|
'El DNI no corresponde con el de la transferencia',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('does not poll when submitting a transfer for review fails', async () => {
|
it('does not poll when submitting a transfer for review fails', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
||||||
@@ -251,19 +393,11 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cancels transfer polling when the payment method changes or the component is destroyed', async () => {
|
it('cancels transfer polling when the component is destroyed', async () => {
|
||||||
const first = createComponent();
|
const checkout = createComponent();
|
||||||
first.component.selectedPaymentMethod.set('transfer');
|
checkout.component.selectedPaymentMethod.set('transfer');
|
||||||
first.component.onComplete();
|
await checkout.component.onComplete();
|
||||||
checkoutServiceStub.generatePaymentIntent.mockResolvedValueOnce({});
|
checkout.fixture.destroy();
|
||||||
await first.component.selectPaymentMethod('qr');
|
|
||||||
await vi.advanceTimersByTimeAsync(12_000);
|
|
||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
const second = createComponent();
|
|
||||||
second.component.selectedPaymentMethod.set('transfer');
|
|
||||||
second.component.onComplete();
|
|
||||||
second.fixture.destroy();
|
|
||||||
await vi.advanceTimersByTimeAsync(12_000);
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
@@ -299,7 +433,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
subtotal: '2501.00',
|
subtotal: '2501.00',
|
||||||
total: '2501.00',
|
total: '2501.00',
|
||||||
};
|
};
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
checkoutServiceStub.getPurchase.mockResolvedValue(purchase);
|
||||||
authUserState.set({
|
authUserState.set({
|
||||||
id: 7,
|
id: 7,
|
||||||
@@ -336,7 +470,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
|
|
||||||
it('keeps the checkout hidden while the purchase is loading', async () => {
|
it('keeps the checkout hidden while the purchase is loading', async () => {
|
||||||
let resolvePurchase!: (purchase: any) => void;
|
let resolvePurchase!: (purchase: any) => void;
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockReturnValue(
|
checkoutServiceStub.getPurchase.mockReturnValue(
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
resolvePurchase = resolve;
|
resolvePurchase = resolve;
|
||||||
@@ -357,12 +491,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
expect(component.isLoadingPurchase()).toBe(false);
|
expect(component.isLoadingPurchase()).toBe(false);
|
||||||
expect(component.checkoutStepIndex()).toBe(0);
|
expect(component.checkoutStepIndex()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
it('opens a pending purchase on the payment step and restores its payment method', async () => {
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -382,7 +517,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('generates a new QR when reopening a pending QR purchase', async () => {
|
it('generates a new QR when reopening a pending QR purchase', async () => {
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -406,7 +541,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
it.each(['paid', 'cancelled', 'rejected', 'expired'])(
|
||||||
'redirects a %s purchase to its status page',
|
'redirects a %s purchase to its status page',
|
||||||
async (status) => {
|
async (status) => {
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status,
|
status,
|
||||||
@@ -424,7 +559,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
it('redirects a submitted pending payment purchase to its status page', async () => {
|
it('redirects a submitted pending payment purchase to its status page', async () => {
|
||||||
routeQueryParamMap = convertToParamMap({ purchase: 25 });
|
routeParamMap = convertToParamMap({ id: 25 });
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||||
id: 25,
|
id: 25,
|
||||||
status: 'pending_payment',
|
status: 'pending_payment',
|
||||||
@@ -442,7 +577,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the API error in a toast when cancelling the purchase fails', async () => {
|
it('shows the API error and redirects to status when cancellation finds an expired purchase', async () => {
|
||||||
const message = 'La compra venció. Iniciá una nueva compra.';
|
const message = 'La compra venció. Iniciá una nueva compra.';
|
||||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||||
error: { code: 'purchase.expired', message },
|
error: { code: 'purchase.expired', message },
|
||||||
@@ -452,7 +587,9 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
await component.onModifyPurchase();
|
await component.onModifyPurchase();
|
||||||
|
|
||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
expect(component.isCancellingPurchase()).toBe(false);
|
expect(component.isCancellingPurchase()).toBe(false);
|
||||||
@@ -494,6 +631,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
|
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
expect(component.createdPurchaseId()).toBeNull();
|
||||||
@@ -508,7 +646,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
await component.canDeactivate();
|
await component.canDeactivate();
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updates customer data on the existing purchase before payment', async () => {
|
it('updates customer data on the existing purchase before payment', async () => {
|
||||||
@@ -551,6 +688,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
await expect(component.canDeactivate()).resolves.toBe(true);
|
||||||
|
|
||||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
expect(component.createdPurchaseId()).toBeNull();
|
||||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
@@ -568,7 +706,24 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.createdPurchaseId()).toBe(25);
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => {
|
it('allows leaving checkout when cancellation finds an expired stock reservation', async () => {
|
||||||
|
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
||||||
|
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||||
|
error: { code: 'stock_reservation.expired', message },
|
||||||
|
});
|
||||||
|
const { component } = createComponent();
|
||||||
|
|
||||||
|
await expect(component.canDeactivate()).resolves.toBe(true);
|
||||||
|
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
||||||
|
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||||
|
expect(component.createdPurchaseId()).toBeNull();
|
||||||
|
expect(component.createdPurchase()).toBeNull();
|
||||||
|
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||||
|
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the API message and redirects to status when a checkout operation finds an expired purchase', async () => {
|
||||||
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
||||||
new HttpErrorResponse({
|
new HttpErrorResponse({
|
||||||
status: 422,
|
status: 422,
|
||||||
@@ -585,10 +740,35 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
expect(component.isGeneratingIntent()).toBe(false);
|
expect(component.isGeneratingIntent()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('redirects to status when QR polling receives a purchase-expired response', async () => {
|
||||||
|
checkoutServiceStub.getPurchase.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
code: 'purchase.expired',
|
||||||
|
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { component } = createComponent();
|
||||||
|
|
||||||
|
await component.selectPaymentMethod('qr');
|
||||||
|
await vi.advanceTimersByTimeAsync(5_000);
|
||||||
|
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.createdPurchase.set({
|
component.createdPurchase.set({
|
||||||
@@ -616,6 +796,8 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
);
|
);
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
ChangeDetectionStrategy,
|
ChangeDetectionStrategy,
|
||||||
Component,
|
Component,
|
||||||
computed,
|
computed,
|
||||||
|
effect,
|
||||||
inject,
|
inject,
|
||||||
OnDestroy,
|
OnDestroy,
|
||||||
OnInit,
|
OnInit,
|
||||||
@@ -11,22 +12,26 @@ import {
|
|||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { FormBuilder, Validators } from '@angular/forms';
|
import { FormBuilder, Validators } from '@angular/forms';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { startWith } from 'rxjs';
|
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';
|
||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
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,
|
||||||
@@ -63,13 +68,15 @@ 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);
|
||||||
|
private readonly cartService = inject(CartService);
|
||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
private readonly qrPollingMaxAttempts = 9;
|
private readonly qrPollingMaxAttempts = 120;
|
||||||
private readonly transferPollingIntervalMs = 3_000;
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
private readonly transferPollingMaxAttempts = 4;
|
private readonly transferPollingMaxAttempts = 20;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
@@ -80,6 +87,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private paymentMethodRequestId = 0;
|
private paymentMethodRequestId = 0;
|
||||||
private navigationStarted = false;
|
private navigationStarted = false;
|
||||||
private cancelPurchasePromise: Promise<boolean> | null = null;
|
private cancelPurchasePromise: Promise<boolean> | null = null;
|
||||||
|
private expirationCheckPurchaseId: number | null = null;
|
||||||
|
|
||||||
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
||||||
|
|
||||||
@@ -93,6 +101,27 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||||
protected readonly isLoadingPurchase = signal(true);
|
protected readonly isLoadingPurchase = signal(true);
|
||||||
protected readonly checkoutStepIndex = signal(0);
|
protected readonly checkoutStepIndex = signal(0);
|
||||||
|
protected readonly checkoutRemainingTime = computed(() => {
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!purchase ||
|
||||||
|
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
||||||
|
|
||||||
|
if (remainingSeconds === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const minutes = Math.floor(remainingSeconds / 60);
|
||||||
|
const seconds = remainingSeconds % 60;
|
||||||
|
|
||||||
|
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||||
|
});
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
return purchase ? parseFloat(purchase.subtotal) : 0;
|
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||||
@@ -122,6 +151,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
protected readonly isUpdatingPurchase = signal(false);
|
protected readonly isUpdatingPurchase = signal(false);
|
||||||
protected readonly isCancellingPurchase = signal(false);
|
protected readonly isCancellingPurchase = signal(false);
|
||||||
|
protected readonly hasSubmittedTransfer = signal(false);
|
||||||
|
protected readonly isPurchaseModificationDisabled = computed(
|
||||||
|
() => this.isCancellingPurchase() || this.hasSubmittedTransfer(),
|
||||||
|
);
|
||||||
protected readonly createdPurchaseId = signal<number | null>(null);
|
protected readonly createdPurchaseId = signal<number | null>(null);
|
||||||
protected readonly isGeneratingIntent = signal(false);
|
protected readonly isGeneratingIntent = signal(false);
|
||||||
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
|
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
|
||||||
@@ -129,6 +162,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
||||||
protected readonly isCheckingQrPayment = signal(false);
|
protected readonly isCheckingQrPayment = signal(false);
|
||||||
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
|
||||||
|
private readonly transferPrimaryCandidateReason = signal<PurchasePaymentCandidateReason | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
protected readonly transferVerificationErrorTitle = computed(() =>
|
||||||
|
this.transferPrimaryCandidateReason() === 'exact_amount_near_dni'
|
||||||
|
? 'El DNI no corresponde con el de la transferencia'
|
||||||
|
: null,
|
||||||
|
);
|
||||||
protected readonly whatsappUrl = computed(
|
protected readonly whatsappUrl = computed(
|
||||||
() =>
|
() =>
|
||||||
this.tenantService
|
this.tenantService
|
||||||
@@ -137,6 +178,28 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
);
|
);
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
||||||
|
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id ?? null;
|
||||||
|
|
||||||
|
if (remainingSeconds !== null && remainingSeconds > 0) {
|
||||||
|
this.expirationCheckPurchaseId = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
remainingSeconds !== 0 ||
|
||||||
|
purchaseId === null ||
|
||||||
|
this.navigationStarted ||
|
||||||
|
this.expirationCheckPurchaseId === purchaseId
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.expirationCheckPurchaseId = purchaseId;
|
||||||
|
void this.checkPurchaseAfterCountdownExpiration(purchaseId);
|
||||||
|
});
|
||||||
|
|
||||||
this.form.statusChanges
|
this.form.statusChanges
|
||||||
.pipe(startWith(this.form.status))
|
.pipe(startWith(this.form.status))
|
||||||
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
.subscribe(() => this.isStep1Valid.set(this.form.valid));
|
||||||
@@ -155,7 +218,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const purchaseId = Number(this.route.snapshot.queryParamMap.get('purchase'));
|
const purchaseId = Number(this.route.snapshot.paramMap.get('id'));
|
||||||
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
if (!Number.isInteger(purchaseId) || purchaseId <= 0) {
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
return;
|
return;
|
||||||
@@ -187,7 +250,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async onModifyPurchase(): Promise<void> {
|
protected async onModifyPurchase(): Promise<void> {
|
||||||
if (this.isCancellingPurchase()) {
|
if (this.isPurchaseModificationDisabled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,6 +285,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
nombre_apellido: formValue.nombre,
|
nombre_apellido: formValue.nombre,
|
||||||
});
|
});
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
|
|
||||||
this.stepper.next();
|
this.stepper.next();
|
||||||
|
|
||||||
@@ -275,6 +339,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
if (!tenant || !purchaseId) {
|
if (!tenant || !purchaseId) {
|
||||||
|
this.checkoutCountdownService.clear();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,13 +347,28 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
||||||
|
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 {
|
||||||
@@ -297,7 +377,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||||
if (this.navigationStarted) {
|
if (this.navigationStarted || this.hasSubmittedTransfer()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,6 +429,10 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async generateTransferIntent(dni: string): Promise<void> {
|
protected async generateTransferIntent(dni: string): Promise<void> {
|
||||||
|
if (this.hasSubmittedTransfer()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const purchaseId = this.createdPurchaseId();
|
const purchaseId = this.createdPurchaseId();
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
@@ -359,6 +443,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.transferDni.set(dni);
|
this.transferDni.set(dni);
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
|
this.transferPrimaryCandidateReason.set(null);
|
||||||
this.isGeneratingIntent.set(true);
|
this.isGeneratingIntent.set(true);
|
||||||
try {
|
try {
|
||||||
const response = await this.checkoutService
|
const response = await this.checkoutService
|
||||||
@@ -413,7 +498,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.stopTransferPolling();
|
this.stopTransferPolling();
|
||||||
|
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;
|
||||||
@@ -427,6 +514,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
|
this.captureTransferCandidateReason(purchase);
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -476,12 +566,24 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
|
this.captureTransferCandidateReason(purchase);
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate transfer payment:', error);
|
console.error('Failed to validate transfer payment:', error);
|
||||||
|
if (this.isPurchaseExpiredError(error)) {
|
||||||
|
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (runId !== this.transferPollingRunId) {
|
if (runId !== this.transferPollingRunId) {
|
||||||
@@ -497,6 +599,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.scheduleTransferPoll(runId);
|
this.scheduleTransferPoll(runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
|
||||||
|
const reason = purchase.payment_verification?.primary?.reason;
|
||||||
|
|
||||||
|
if (reason) {
|
||||||
|
this.transferPrimaryCandidateReason.set(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private stopTransferPolling(): void {
|
private stopTransferPolling(): void {
|
||||||
this.transferPollingRunId += 1;
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
@@ -553,6 +663,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.handleConfirmedPayment(purchaseId);
|
this.handleConfirmedPayment(purchaseId);
|
||||||
return;
|
return;
|
||||||
@@ -563,8 +675,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.qrPaymentStatus.set('failed');
|
this.qrPaymentStatus.set('failed');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate QR payment:', error);
|
console.error('Failed to validate QR payment:', error);
|
||||||
|
if (this.isPurchaseExpiredError(error)) {
|
||||||
|
this.showRequestError(error, 'La compra venció. Iniciá una nueva compra.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (runId === this.qrPollingRunId) {
|
if (runId === this.qrPollingRunId) {
|
||||||
this.isCheckingQrPayment.set(false);
|
this.isCheckingQrPayment.set(false);
|
||||||
@@ -617,10 +738,40 @@ 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]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async checkPurchaseAfterCountdownExpiration(purchaseId: number): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
|
if (!tenant || this.navigationStarted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const purchase = await this.checkoutService
|
||||||
|
.withCustomLoading()
|
||||||
|
.getPurchase(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (this.navigationStarted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
this.navigateToExpiredPurchaseStatus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
|
} catch (error) {
|
||||||
|
if (this.isPurchaseExpiredError(error)) {
|
||||||
|
this.navigateToExpiredPurchaseStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async loadPurchase(purchaseId: number): Promise<void> {
|
private async loadPurchase(purchaseId: number): Promise<void> {
|
||||||
const tenant = this.tenantService.tenant();
|
const tenant = this.tenantService.tenant();
|
||||||
if (!tenant) {
|
if (!tenant) {
|
||||||
@@ -637,6 +788,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
(purchase.status === 'pending_payment' && purchase.expires_at === null) ||
|
(purchase.status === 'pending_payment' && purchase.expires_at === null) ||
|
||||||
|
purchase.status === 'in_review' ||
|
||||||
purchase.status === 'paid' ||
|
purchase.status === 'paid' ||
|
||||||
purchase.status === 'cancelled' ||
|
purchase.status === 'cancelled' ||
|
||||||
purchase.status === 'rejected' ||
|
purchase.status === 'rejected' ||
|
||||||
@@ -653,6 +805,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.createdPurchaseId.set(purchase.id);
|
this.createdPurchaseId.set(purchase.id);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
|
this.checkoutCountdownService.synchronize(purchase);
|
||||||
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -670,15 +823,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load purchase:', error);
|
console.error('Failed to load purchase:', error);
|
||||||
this.showRequestError(error, 'No se pudo cargar la compra.');
|
const expired = this.showRequestError(error, 'No se pudo cargar la compra.');
|
||||||
void this.router.navigate(['/']);
|
if (!expired) {
|
||||||
|
void this.router.navigate(['/']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private showRequestError(error: unknown, fallbackMessage: string): void {
|
private showRequestError(error: unknown, fallbackMessage: string): boolean {
|
||||||
const payload =
|
const payload =
|
||||||
typeof error === 'object' && error !== null && 'error' in error
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
? (error as { error?: { message?: unknown } }).error
|
? (error as { error?: ApiErrorResponse }).error
|
||||||
: undefined;
|
: undefined;
|
||||||
const message =
|
const message =
|
||||||
typeof payload?.message === 'string' && payload.message.trim()
|
typeof payload?.message === 'string' && payload.message.trim()
|
||||||
@@ -686,6 +841,13 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
: fallbackMessage;
|
: fallbackMessage;
|
||||||
|
|
||||||
this.toastService.danger(message);
|
this.toastService.danger(message);
|
||||||
|
|
||||||
|
if (payload?.code === 'purchase.expired') {
|
||||||
|
this.navigateToExpiredPurchaseStatus();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
||||||
@@ -704,7 +866,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
? response.message
|
? response.message
|
||||||
: 'La compra venció. Iniciá una nueva compra.',
|
: 'La compra venció. Iniciá una nueva compra.',
|
||||||
);
|
);
|
||||||
void this.router.navigate(['/']);
|
this.navigateToExpiredPurchaseStatus();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,6 +878,43 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private navigateToExpiredPurchaseStatus(): void {
|
||||||
|
const purchaseId = this.createdPurchaseId() ?? this.createdPurchase()?.id;
|
||||||
|
|
||||||
|
if (purchaseId) {
|
||||||
|
if (this.navigationStarted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.navigationStarted = true;
|
||||||
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
this.checkoutCountdownService.clear();
|
||||||
|
void this.router.navigate(['/checkout/status', purchaseId], {
|
||||||
|
queryParams: { status: 'expired' },
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void this.router.navigate(['/']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isPurchaseExpiredError(error: unknown): boolean {
|
||||||
|
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (error as { error?: ApiErrorResponse }).error?.code === 'purchase.expired';
|
||||||
|
}
|
||||||
|
|
||||||
|
private isStockReservationExpiredError(error: unknown): boolean {
|
||||||
|
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (error as { error?: ApiErrorResponse }).error?.code === 'stock_reservation.expired';
|
||||||
|
}
|
||||||
|
|
||||||
private hasExpiredPurchase(): boolean {
|
private hasExpiredPurchase(): boolean {
|
||||||
const purchase = this.createdPurchase();
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
|||||||
@@ -7,13 +7,18 @@
|
|||||||
|
|
||||||
<div class="payment-methods__list" role="radiogroup" aria-label="Metodo de pago">
|
<div class="payment-methods__list" role="radiogroup" aria-label="Metodo de pago">
|
||||||
@for (method of paymentMethods(); track method.id) {
|
@for (method of paymentMethods(); track method.id) {
|
||||||
<label class="payment-method" [class.is-selected]="selectedPaymentMethod() === method.id">
|
<label
|
||||||
|
class="payment-method"
|
||||||
|
[class.is-selected]="selectedPaymentMethod() === method.id"
|
||||||
|
[class.is-disabled]="paymentMethodDisabled()"
|
||||||
|
>
|
||||||
<input
|
<input
|
||||||
class="payment-method__radio"
|
class="payment-method__radio"
|
||||||
type="radio"
|
type="radio"
|
||||||
name="payment-method"
|
name="payment-method"
|
||||||
[value]="method.id"
|
[value]="method.id"
|
||||||
[checked]="selectedPaymentMethod() === method.id"
|
[checked]="selectedPaymentMethod() === method.id"
|
||||||
|
[disabled]="paymentMethodDisabled()"
|
||||||
(change)="selectPaymentMethod(method.id)"
|
(change)="selectPaymentMethod(method.id)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -48,6 +53,7 @@
|
|||||||
[validationStatus]="transferValidationStatus()"
|
[validationStatus]="transferValidationStatus()"
|
||||||
[paymentAmount]="qrPaymentAmount()"
|
[paymentAmount]="qrPaymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
|
[verificationErrorTitle]="transferVerificationErrorTitle()"
|
||||||
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
||||||
(submitDni)="generateTransferIntent.emit($event)"
|
(submitDni)="generateTransferIntent.emit($event)"
|
||||||
(completePurchase)="complete.emit()"
|
(completePurchase)="complete.emit()"
|
||||||
|
|||||||
@@ -63,10 +63,14 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: color 0.2s ease;
|
transition: color 0.2s ease;
|
||||||
|
|
||||||
&:hover {
|
&:not(.is-disabled):hover {
|
||||||
color: #4f4f4f;
|
color: #4f4f4f;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&.is-disabled {
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
&.is-selected {
|
&.is-selected {
|
||||||
color: var(--tenant-primary, #6376f3);
|
color: var(--tenant-primary, #6376f3);
|
||||||
}
|
}
|
||||||
@@ -79,6 +83,10 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&.is-disabled &__radio {
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
&__label {
|
&__label {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
@@ -91,11 +99,13 @@
|
|||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: translateX(-4px);
|
transform: translateX(-4px);
|
||||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
transition:
|
||||||
|
opacity 0.2s ease,
|
||||||
|
transform 0.2s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
&.is-selected &__chevron,
|
&.is-selected &__chevron,
|
||||||
&:hover &__chevron {
|
&:not(.is-disabled):hover &__chevron {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
transform: translateX(0);
|
transform: translateX(0);
|
||||||
}
|
}
|
||||||
@@ -140,6 +150,4 @@
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
line-height: 1.35;
|
line-height: 1.35;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,11 +17,12 @@ import {
|
|||||||
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent],
|
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent],
|
||||||
templateUrl: './checkout-payment-step.component.html',
|
templateUrl: './checkout-payment-step.component.html',
|
||||||
styleUrl: './checkout-payment-step.component.scss',
|
styleUrl: './checkout-payment-step.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class CheckoutPaymentStepComponent {
|
export class CheckoutPaymentStepComponent {
|
||||||
readonly paymentMethods = input.required<ReadonlyArray<PaymentMethodOption>>();
|
readonly paymentMethods = input.required<ReadonlyArray<PaymentMethodOption>>();
|
||||||
readonly selectedPaymentMethod = input.required<PaymentMethod>();
|
readonly selectedPaymentMethod = input.required<PaymentMethod>();
|
||||||
|
readonly paymentMethodDisabled = input<boolean>(false);
|
||||||
readonly copiedTransferField = input<TransferField | null>(null);
|
readonly copiedTransferField = input<TransferField | null>(null);
|
||||||
readonly transferAccount = input<TransferAccount | null>(null);
|
readonly transferAccount = input<TransferAccount | null>(null);
|
||||||
readonly transferDni = input<string>('');
|
readonly transferDni = input<string>('');
|
||||||
@@ -32,6 +33,7 @@ export class CheckoutPaymentStepComponent {
|
|||||||
readonly qrPaymentAmount = input<number>(0);
|
readonly qrPaymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
||||||
|
readonly transferVerificationErrorTitle = input<string | null>(null);
|
||||||
|
|
||||||
readonly paymentMethodChange = output<PaymentMethod>();
|
readonly paymentMethodChange = output<PaymentMethod>();
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
@@ -40,6 +42,10 @@ export class CheckoutPaymentStepComponent {
|
|||||||
readonly generateTransferIntent = output<string>();
|
readonly generateTransferIntent = output<string>();
|
||||||
|
|
||||||
protected selectPaymentMethod(method: PaymentMethod): void {
|
protected selectPaymentMethod(method: PaymentMethod): void {
|
||||||
|
if (this.paymentMethodDisabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.paymentMethodChange.emit(method);
|
this.paymentMethodChange.emit(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
<app-payment-verification-error
|
<app-payment-verification-error
|
||||||
[paymentAmount]="paymentAmount()"
|
[paymentAmount]="paymentAmount()"
|
||||||
[whatsappUrl]="whatsappUrl()"
|
[whatsappUrl]="whatsappUrl()"
|
||||||
|
[title]="verificationErrorTitle()"
|
||||||
/>
|
/>
|
||||||
} @else {
|
} @else {
|
||||||
<div class="dni-form-container">
|
<div class="dni-form-container">
|
||||||
|
|||||||
@@ -47,4 +47,23 @@ describe('CheckoutPaymentTransferComponent', () => {
|
|||||||
expect(whatsapp).toBeDefined();
|
expect(whatsapp).toBeDefined();
|
||||||
expect(element.querySelector('.payment-verification')).toBeNull();
|
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows a custom validation title for a near DNI candidate', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CheckoutPaymentTransferComponent],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||||
|
fixture.componentRef.setInput('validationStatus', 'error');
|
||||||
|
fixture.componentRef.setInput(
|
||||||
|
'verificationErrorTitle',
|
||||||
|
'El DNI no corresponde con el de la transferencia',
|
||||||
|
);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.textContent).toContain(
|
||||||
|
'El DNI no corresponde con el de la transferencia',
|
||||||
|
);
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export class CheckoutPaymentTransferComponent implements OnInit {
|
|||||||
readonly validationStatus = input<TransferValidationStatus>('idle');
|
readonly validationStatus = input<TransferValidationStatus>('idle');
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
|
readonly verificationErrorTitle = input<string | null>(null);
|
||||||
|
|
||||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||||
readonly submitDni = output<string>();
|
readonly submitDni = output<string>();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<div class="payment-timeout__icon" aria-hidden="true">
|
<div class="payment-timeout__icon" aria-hidden="true">
|
||||||
<i class="fa-solid fa-xmark"></i>
|
<i class="fa-solid fa-xmark"></i>
|
||||||
</div>
|
</div>
|
||||||
<h4 class="payment-timeout__title">No pudimos verificar el pago de {{ formattedAmount() }}.</h4>
|
<h4 class="payment-timeout__title">{{ displayTitle() }}</h4>
|
||||||
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
||||||
@if (whatsappUrl()) {
|
@if (whatsappUrl()) {
|
||||||
<app-button
|
<app-button
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { ButtonComponent } from '../../../../../../shared/components/button/butt
|
|||||||
export class PaymentVerificationErrorComponent {
|
export class PaymentVerificationErrorComponent {
|
||||||
readonly paymentAmount = input<number>(0);
|
readonly paymentAmount = input<number>(0);
|
||||||
readonly whatsappUrl = input<string | null>(null);
|
readonly whatsappUrl = input<string | null>(null);
|
||||||
|
readonly title = input<string | null>(null);
|
||||||
|
|
||||||
protected readonly formattedAmount = computed(() =>
|
protected readonly formattedAmount = computed(() =>
|
||||||
new Intl.NumberFormat('es-AR', {
|
new Intl.NumberFormat('es-AR', {
|
||||||
@@ -21,6 +22,9 @@ export class PaymentVerificationErrorComponent {
|
|||||||
maximumFractionDigits: 0,
|
maximumFractionDigits: 0,
|
||||||
}).format(this.paymentAmount()),
|
}).format(this.paymentAmount()),
|
||||||
);
|
);
|
||||||
|
protected readonly displayTitle = computed(
|
||||||
|
() => this.title() ?? `No pudimos verificar el pago de ${this.formattedAmount()}.`,
|
||||||
|
);
|
||||||
|
|
||||||
protected openWhatsApp(): void {
|
protected openWhatsApp(): void {
|
||||||
const url = this.whatsappUrl();
|
const url = this.whatsappUrl();
|
||||||
|
|||||||
@@ -507,9 +507,7 @@ describe('ProductDetailPageComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout'], {
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout', 44]);
|
||||||
queryParams: { purchase: 44 },
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||||
|
|||||||
@@ -358,9 +358,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.router.navigate(['/checkout'], {
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
queryParams: { purchase: purchase.id },
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
const message =
|
const message =
|
||||||
|
|||||||
@@ -17,7 +17,9 @@
|
|||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
@if (ticketsRoute()) {
|
@if (ticketsRoute()) {
|
||||||
<p class="status-content__message">A continuación, vas a poder ver los tickets que debés presentar en el evento.</p>
|
<p class="status-content__message">
|
||||||
|
A continuación, vas a poder ver los tickets que debés presentar en el evento.
|
||||||
|
</p>
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -29,7 +31,9 @@
|
|||||||
<span>Mis tickets</span>
|
<span>Mis tickets</span>
|
||||||
</app-button>
|
</app-button>
|
||||||
} @else if (whatsappUrl()) {
|
} @else if (whatsappUrl()) {
|
||||||
<p class="status-content__message">Comunicate con nosotros para coordinar el envío.</p>
|
<p class="status-content__message">
|
||||||
|
Comunicate con nosotros para coordinar el envío.
|
||||||
|
</p>
|
||||||
|
|
||||||
<app-button
|
<app-button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -51,13 +55,21 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
||||||
<p class="status-content__subtitle">Tu compra ya fue registrada y estamos esperando la confirmación del pago.</p>
|
<p class="status-content__subtitle">
|
||||||
|
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">
|
||||||
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
@if (paymentIssueMessage()) {
|
||||||
|
<p class="status-content__message">
|
||||||
|
{{ paymentIssueMessage() }} Estamos revisando el pago.
|
||||||
|
</p>
|
||||||
|
} @else {
|
||||||
|
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
} @else if (status() === 'expired') {
|
} @else if (status() === 'expired') {
|
||||||
<div class="status-content__section status-content__section--primary">
|
<div class="status-content__section status-content__section--primary">
|
||||||
@@ -65,13 +77,17 @@
|
|||||||
<i class="fa-solid fa-clock"></i>
|
<i class="fa-solid fa-clock"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
||||||
<p class="status-content__subtitle">El plazo de pago terminó y liberamos el stock reservado.</p>
|
<p class="status-content__subtitle">
|
||||||
|
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">Podés volver a la tienda e iniciar una nueva compra.</p>
|
<p class="status-content__message">
|
||||||
|
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">
|
||||||
@@ -79,7 +95,9 @@
|
|||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
||||||
<p class="status-content__subtitle">Revisá el medio de pago o comunicate con nosotros para continuar.</p>
|
<p class="status-content__subtitle">
|
||||||
|
Revisá el medio de pago o comunicate con nosotros para continuar.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
@@ -114,7 +132,9 @@
|
|||||||
<hr class="status-content__divider" />
|
<hr class="status-content__divider" />
|
||||||
|
|
||||||
<div class="status-content__section status-content__section--secondary">
|
<div class="status-content__section status-content__section--secondary">
|
||||||
<p class="status-content__message">Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.</p>
|
<p class="status-content__message">
|
||||||
|
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,6 +5,7 @@ import {
|
|||||||
CheckoutService,
|
CheckoutService,
|
||||||
PurchaseDetailResponse,
|
PurchaseDetailResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
||||||
@@ -66,9 +67,13 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function render(hasGeneratedTickets: boolean) {
|
async function render(
|
||||||
|
hasGeneratedTickets: boolean,
|
||||||
|
forcedStatus?: string,
|
||||||
|
purchaseResponse = purchase(hasGeneratedTickets),
|
||||||
|
) {
|
||||||
const checkoutService = {
|
const checkoutService = {
|
||||||
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
|
getPurchase: vi.fn().mockResolvedValue(purchaseResponse),
|
||||||
withCustomLoading() {
|
withCustomLoading() {
|
||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
@@ -77,15 +82,22 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
navigate: vi.fn().mockResolvedValue(true),
|
navigate: vi.fn().mockResolvedValue(true),
|
||||||
navigateByUrl: vi.fn().mockResolvedValue(true),
|
navigateByUrl: vi.fn().mockResolvedValue(true),
|
||||||
};
|
};
|
||||||
|
const cartService = { clearCart: vi.fn() };
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
|
{ provide: CartService, useValue: cartService },
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
useValue: {
|
||||||
|
snapshot: {
|
||||||
|
paramMap: convertToParamMap({ id: '42' }),
|
||||||
|
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{ provide: Router, useValue: router },
|
{ provide: Router, useValue: router },
|
||||||
],
|
],
|
||||||
@@ -100,15 +112,22 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
fixture,
|
fixture,
|
||||||
element: fixture.nativeElement as HTMLElement,
|
element: fixture.nativeElement as HTMLElement,
|
||||||
checkoutService,
|
checkoutService,
|
||||||
|
cartService,
|
||||||
router,
|
router,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it('clears the cart when the purchase is approved', async () => {
|
||||||
|
const { cartService } = await render(true);
|
||||||
|
|
||||||
|
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('shows the tickets action when this purchase generated tickets', async () => {
|
it('shows the tickets action when this purchase generated tickets', async () => {
|
||||||
const { element, checkoutService, router } = await render(true);
|
const { element, checkoutService, router } = await render(true);
|
||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||||
expect(element.textContent).toContain('Ver mis tickets');
|
expect(element.textContent).toContain('Mis tickets');
|
||||||
expect(element.textContent).not.toContain('WhatsApp');
|
expect(element.textContent).not.toContain('WhatsApp');
|
||||||
|
|
||||||
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
element.querySelector<HTMLButtonElement>('app-button button')?.click();
|
||||||
@@ -134,6 +153,38 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
openSpy.mockRestore();
|
openSpy.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the expired result without polling when checkout redirects after expiration', async () => {
|
||||||
|
const { element, checkoutService } = await render(false, 'expired');
|
||||||
|
|
||||||
|
expect(element.textContent).toContain('LA COMPRA VENCIÓ');
|
||||||
|
expect(element.textContent).not.toContain('ESTAMOS VERIFICANDO TU PAGO');
|
||||||
|
expect(checkoutService.getPurchase).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the primary transfer candidate issue while the purchase is in review', async () => {
|
||||||
|
const { element } = await render(false, undefined, {
|
||||||
|
status: 'in_review',
|
||||||
|
payment_verification: {
|
||||||
|
status: 'candidate',
|
||||||
|
candidate_count: 2,
|
||||||
|
primary: {
|
||||||
|
reason: 'exact_dni_near_amount',
|
||||||
|
dni_distance: 0,
|
||||||
|
payment_amount: '49000.00',
|
||||||
|
purchase_amount: '50000.00',
|
||||||
|
amount_difference: '1000.00',
|
||||||
|
confidence: 'high',
|
||||||
|
detected_at: '2026-08-27T18:00:00-03:00',
|
||||||
|
},
|
||||||
|
reasons: ['exact_dni_near_amount', 'exact_amount_near_dni'],
|
||||||
|
},
|
||||||
|
} as PurchaseDetailResponse);
|
||||||
|
|
||||||
|
expect(element.textContent).toContain('Encontramos 2 transferencias posibles.');
|
||||||
|
expect(element.textContent).toMatch(/diferencia de \$\s*1\.000/);
|
||||||
|
expect(element.textContent).toContain('Estamos revisando el pago.');
|
||||||
|
});
|
||||||
|
|
||||||
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
@@ -147,11 +198,13 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
return this;
|
return this;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
const cartService = { clearCart: vi.fn() };
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
|
{ provide: CartService, useValue: cartService },
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
@@ -174,6 +227,7 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
|
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
||||||
|
expect(cartService.clearCart).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(10_000);
|
await vi.advanceTimersByTimeAsync(10_000);
|
||||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||||
@@ -197,6 +251,7 @@ describe('PurchaseStatusPageComponent', () => {
|
|||||||
imports: [PurchaseStatusPageComponent],
|
imports: [PurchaseStatusPageComponent],
|
||||||
providers: [
|
providers: [
|
||||||
{ provide: CheckoutService, useValue: checkoutService },
|
{ provide: CheckoutService, useValue: checkoutService },
|
||||||
|
{ provide: CartService, useValue: { clearCart: vi.fn() } },
|
||||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
|
|||||||
@@ -13,8 +13,10 @@ import { ActivatedRoute, Router } from '@angular/router';
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
|
PurchasePaymentVerificationResponse,
|
||||||
PurchaseStatusResponse,
|
PurchaseStatusResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { findMenu } from '../../../../core/services/menu.utils';
|
import { findMenu } from '../../../../core/services/menu.utils';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
@@ -35,6 +37,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
|
private readonly cartService = inject(CartService);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||||
|
|
||||||
@@ -46,6 +49,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly isLoading = signal(true);
|
protected readonly isLoading = signal(true);
|
||||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||||
protected readonly hasGeneratedTickets = signal(false);
|
protected readonly hasGeneratedTickets = signal(false);
|
||||||
|
protected readonly paymentIssueMessage = signal<string | null>(null);
|
||||||
protected readonly ticketsRoute = computed(() => {
|
protected readonly ticketsRoute = computed(() => {
|
||||||
if (!this.hasGeneratedTickets()) {
|
if (!this.hasGeneratedTickets()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -72,6 +76,12 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
this.purchaseId = purchaseId;
|
this.purchaseId = purchaseId;
|
||||||
this.tenantCode = tenant.codigo;
|
this.tenantCode = tenant.codigo;
|
||||||
|
|
||||||
|
if (this.route.snapshot.queryParamMap?.get('status') === 'expired') {
|
||||||
|
this.status.set('expired');
|
||||||
|
this.isLoading.set(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
void this.loadStatus();
|
void this.loadStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,6 +107,11 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
const status = this.resolveStatus(purchase);
|
const status = this.resolveStatus(purchase);
|
||||||
this.status.set(status);
|
this.status.set(status);
|
||||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||||
|
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
|
||||||
|
|
||||||
|
if (status === 'approved') {
|
||||||
|
this.cartService.clearCart();
|
||||||
|
}
|
||||||
|
|
||||||
if (status === 'pending') {
|
if (status === 'pending') {
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
@@ -107,7 +122,10 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
console.error('Failed to fetch purchase status:', error);
|
console.error('Failed to fetch purchase status:', error);
|
||||||
|
|
||||||
if (!this.isDestroyed) {
|
if (!this.isDestroyed) {
|
||||||
if (isPolling) {
|
if (this.isPurchaseExpiredError(error)) {
|
||||||
|
this.status.set('expired');
|
||||||
|
this.stopPolling();
|
||||||
|
} else if (isPolling) {
|
||||||
this.schedulePolling();
|
this.schedulePolling();
|
||||||
} else {
|
} else {
|
||||||
this.status.set('error');
|
this.status.set('error');
|
||||||
@@ -154,6 +172,51 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
|||||||
return 'pending';
|
return 'pending';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private resolvePaymentIssueMessage(
|
||||||
|
verification?: PurchasePaymentVerificationResponse,
|
||||||
|
): string | null {
|
||||||
|
const primary = verification?.primary;
|
||||||
|
|
||||||
|
if (!primary) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryMessage = (() => {
|
||||||
|
switch (primary.reason) {
|
||||||
|
case 'ambiguous_exact_match':
|
||||||
|
return 'Encontramos una transferencia que también coincide con otra compra.';
|
||||||
|
case 'exact_dni_near_amount':
|
||||||
|
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
|
||||||
|
case 'exact_amount_near_dni':
|
||||||
|
return primary.dni_distance === null
|
||||||
|
? 'El monto coincide, pero el DNI del pagador es diferente.'
|
||||||
|
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (verification.candidate_count > 1) {
|
||||||
|
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return primaryMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatCurrency(amount: string): string {
|
||||||
|
return new Intl.NumberFormat('es-AR', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'ARS',
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
}).format(Number(amount));
|
||||||
|
}
|
||||||
|
|
||||||
|
private isPurchaseExpiredError(error: unknown): boolean {
|
||||||
|
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (error as { error?: { code?: string } }).error?.code === 'purchase.expired';
|
||||||
|
}
|
||||||
|
|
||||||
protected goToTickets(): void {
|
protected goToTickets(): void {
|
||||||
const route = this.ticketsRoute();
|
const route = this.ticketsRoute();
|
||||||
|
|
||||||
|
|||||||
@@ -38,11 +38,13 @@
|
|||||||
<label class="visually-hidden" for="register-password">Contraseña</label>
|
<label class="visually-hidden" for="register-password">Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password"
|
id="register-password"
|
||||||
type="password"
|
type="password-toggle"
|
||||||
placeholder="Contraseña"
|
placeholder="Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
|
[visible]="passwordVisible()"
|
||||||
(valueChange)="updateField('password', $event)"
|
(valueChange)="updateField('password', $event)"
|
||||||
|
(visibleChange)="setPasswordVisibility($event)"
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -51,11 +53,13 @@
|
|||||||
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="register-password-repeat"
|
id="register-password-repeat"
|
||||||
type="password"
|
type="password-toggle"
|
||||||
placeholder="Repetir Contraseña"
|
placeholder="Repetir Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
|
[visible]="passwordVisible()"
|
||||||
(valueChange)="updateField('password_confirmation', $event)"
|
(valueChange)="updateField('password_confirmation', $event)"
|
||||||
|
(visibleChange)="setPasswordVisibility($event)"
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -12,6 +12,48 @@ describe('RegisterPageComponent', () => {
|
|||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows and hides both password fields with either visibility control', async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [RegisterPageComponent],
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: AuthService, useValue: { register: vi.fn() } },
|
||||||
|
{ provide: ModalService, useValue: { openSimple: vi.fn() } },
|
||||||
|
{ provide: ToastService, useValue: { danger: vi.fn() } }
|
||||||
|
]
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const getPasswordInputs = () =>
|
||||||
|
Array.from(
|
||||||
|
fixture.nativeElement.querySelectorAll(
|
||||||
|
'input#register-password, input#register-password-repeat'
|
||||||
|
)
|
||||||
|
) as HTMLInputElement[];
|
||||||
|
const getVisibilityButtons = () =>
|
||||||
|
Array.from(
|
||||||
|
fixture.nativeElement.querySelectorAll('button[aria-label]')
|
||||||
|
) as HTMLButtonElement[];
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
||||||
|
|
||||||
|
getVisibilityButtons()[0].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
||||||
|
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
||||||
|
'Ocultar contraseña',
|
||||||
|
'Ocultar contraseña'
|
||||||
|
]);
|
||||||
|
|
||||||
|
getVisibilityButtons()[1].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
||||||
|
});
|
||||||
|
|
||||||
it('submits registration data and redirects to /login on success', async () => {
|
it('submits registration data and redirects to /login on success', async () => {
|
||||||
const authService = {
|
const authService = {
|
||||||
register: vi.fn().mockReturnValue(
|
register: vi.fn().mockReturnValue(
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export class RegisterPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
|
private readonly passwordVisibleState = signal(false);
|
||||||
|
|
||||||
protected readonly form = this.formBuilder.nonNullable.group({
|
protected readonly form = this.formBuilder.nonNullable.group({
|
||||||
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
||||||
@@ -67,6 +68,11 @@ export class RegisterPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
|
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
||||||
|
|
||||||
|
protected setPasswordVisibility(visible: boolean): void {
|
||||||
|
this.passwordVisibleState.set(visible);
|
||||||
|
}
|
||||||
|
|
||||||
goToLogin(): void {
|
goToLogin(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
|
|||||||
@@ -13,11 +13,13 @@
|
|||||||
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
<label class="visually-hidden" for="reset-password-new">Nueva Contraseña</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-new"
|
id="reset-password-new"
|
||||||
type="password"
|
type="password-toggle"
|
||||||
placeholder="Nueva Contraseña"
|
placeholder="Nueva Contraseña"
|
||||||
[value]="form.controls.password.value"
|
[value]="form.controls.password.value"
|
||||||
[invalid]="showControlError('password')"
|
[invalid]="showControlError('password')"
|
||||||
|
[visible]="passwordVisible()"
|
||||||
(valueChange)="updatePassword('password', $event)"
|
(valueChange)="updatePassword('password', $event)"
|
||||||
|
(visibleChange)="setPasswordVisibility($event)"
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password'); as errorMessage) {
|
@if (getControlError('password'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
@@ -30,11 +32,13 @@
|
|||||||
</label>
|
</label>
|
||||||
<app-input
|
<app-input
|
||||||
id="reset-password-confirmation"
|
id="reset-password-confirmation"
|
||||||
type="password"
|
type="password-toggle"
|
||||||
placeholder="Repetir Nueva Contraseña"
|
placeholder="Repetir Nueva Contraseña"
|
||||||
[value]="form.controls.password_confirmation.value"
|
[value]="form.controls.password_confirmation.value"
|
||||||
[invalid]="showControlError('password_confirmation')"
|
[invalid]="showControlError('password_confirmation')"
|
||||||
|
[visible]="passwordVisible()"
|
||||||
(valueChange)="updatePassword('password_confirmation', $event)"
|
(valueChange)="updatePassword('password_confirmation', $event)"
|
||||||
|
(visibleChange)="setPasswordVisibility($event)"
|
||||||
/>
|
/>
|
||||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||||
<small class="text-danger">{{ errorMessage }}</small>
|
<small class="text-danger">{{ errorMessage }}</small>
|
||||||
|
|||||||
@@ -50,6 +50,43 @@ describe('ResetPasswordPageComponent', () => {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it('shows and hides both password fields with either visibility control', async () => {
|
||||||
|
const modalService = {
|
||||||
|
openSimple: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [ResetPasswordPageComponent],
|
||||||
|
providers: resetProviders(modalService),
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(ResetPasswordPageComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const getPasswordInputs = () =>
|
||||||
|
Array.from(fixture.nativeElement.querySelectorAll('input')) as HTMLInputElement[];
|
||||||
|
const getVisibilityButtons = () =>
|
||||||
|
Array.from(
|
||||||
|
fixture.nativeElement.querySelectorAll('button[aria-label]'),
|
||||||
|
) as HTMLButtonElement[];
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
||||||
|
|
||||||
|
getVisibilityButtons()[0].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['text', 'text']);
|
||||||
|
expect(getVisibilityButtons().map((button) => button.getAttribute('aria-label'))).toEqual([
|
||||||
|
'Ocultar contraseña',
|
||||||
|
'Ocultar contraseña',
|
||||||
|
]);
|
||||||
|
|
||||||
|
getVisibilityButtons()[1].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(getPasswordInputs().map((input) => input.type)).toEqual(['password', 'password']);
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects passwords that do not match', async () => {
|
it('rejects passwords that do not match', async () => {
|
||||||
const modalService = {
|
const modalService = {
|
||||||
openSimple: vi.fn(),
|
openSimple: vi.fn(),
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ export class ResetPasswordPageComponent {
|
|||||||
private readonly submittedState = signal(false);
|
private readonly submittedState = signal(false);
|
||||||
private readonly isSubmittingState = signal(false);
|
private readonly isSubmittingState = signal(false);
|
||||||
private readonly serverErrorState = signal<string | null>(null);
|
private readonly serverErrorState = signal<string | null>(null);
|
||||||
|
private readonly passwordVisibleState = signal(false);
|
||||||
|
|
||||||
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
private readonly email = this.route.snapshot.queryParamMap.get('email') ?? '';
|
||||||
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
private readonly code = this.route.snapshot.queryParamMap.get('code') ?? '';
|
||||||
@@ -72,6 +73,11 @@ export class ResetPasswordPageComponent {
|
|||||||
protected readonly submitted = this.submittedState.asReadonly();
|
protected readonly submitted = this.submittedState.asReadonly();
|
||||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||||
|
protected readonly passwordVisible = this.passwordVisibleState.asReadonly();
|
||||||
|
|
||||||
|
protected setPasswordVisibility(visible: boolean): void {
|
||||||
|
this.passwordVisibleState.set(visible);
|
||||||
|
}
|
||||||
|
|
||||||
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
protected updatePassword(controlName: PasswordControlName, value: string | number): void {
|
||||||
this.form.controls[controlName].setValue(String(value));
|
this.form.controls[controlName].setValue(String(value));
|
||||||
|
|||||||
@@ -24,7 +24,10 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|||||||
|
|
||||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
isExpiredStockReservationResponse,
|
||||||
|
} from '../../../../core/services/checkout.service';
|
||||||
import {
|
import {
|
||||||
CatalogFeaturedItem,
|
CatalogFeaturedItem,
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
@@ -199,10 +202,20 @@ export class SearchPageComponent {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra directa.';
|
||||||
|
this.toastService.danger(message);
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.creatingDirectPurchase.set(false);
|
this.creatingDirectPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
|||||||
import { ToastService } from '../../../../core/services/toast.service';
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import {
|
import {
|
||||||
CheckoutService,
|
CheckoutService,
|
||||||
|
isExpiredStockReservationResponse,
|
||||||
isInsufficientStockResponse,
|
isInsufficientStockResponse,
|
||||||
} from '../../../../core/services/checkout.service';
|
} from '../../../../core/services/checkout.service';
|
||||||
import {
|
import {
|
||||||
@@ -217,10 +218,18 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
|||||||
tenant.codigo,
|
tenant.codigo,
|
||||||
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
reservedCartId !== null ? { cart_id: reservedCartId } : { direct_items: directItems },
|
||||||
);
|
);
|
||||||
await this.router.navigate(['/checkout'], { queryParams: { purchase: purchase.id } });
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create direct purchase:', error);
|
console.error('Failed to create direct purchase:', error);
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||||
|
this.toastService.danger(error.error.message);
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
if (error instanceof HttpErrorResponse && isInsufficientStockResponse(error.error)) {
|
||||||
const unavailableIds = error.error.unavailable_items
|
const unavailableIds = error.error.unavailable_items
|
||||||
.map((item) => item.variant_id)
|
.map((item) => item.variant_id)
|
||||||
|
|||||||
@@ -91,15 +91,6 @@ export const routes: Routes = [
|
|||||||
(m) => m.ProductDetailPageComponent,
|
(m) => m.ProductDetailPageComponent,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: 'checkout',
|
|
||||||
canActivate: [authGuard, hasMenuGuard('checkout')],
|
|
||||||
canDeactivate: [checkoutPendingPurchaseGuard],
|
|
||||||
loadComponent: () =>
|
|
||||||
import('./pages/checkout-page/checkout-page.component').then(
|
|
||||||
(m) => m.CheckoutPageComponent,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: 'checkout/status',
|
path: 'checkout/status',
|
||||||
component: SimpleLayoutComponent,
|
component: SimpleLayoutComponent,
|
||||||
@@ -113,6 +104,15 @@ export const routes: Routes = [
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'checkout/:id',
|
||||||
|
canActivate: [authGuard, hasMenuGuard('checkout')],
|
||||||
|
canDeactivate: [checkoutPendingPurchaseGuard],
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./pages/checkout-page/checkout-page.component').then(
|
||||||
|
(m) => m.CheckoutPageComponent,
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'ayuda',
|
path: 'ayuda',
|
||||||
canActivate: [hasMenuGuard('help')],
|
canActivate: [hasMenuGuard('help')],
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
[disabled]="disabled()"
|
[disabled]="disabled()"
|
||||||
|
[class.cart-icon--disabled]="disabled()"
|
||||||
[attr.aria-label]="ariaLabel()"
|
[attr.aria-label]="ariaLabel()"
|
||||||
|
[attr.aria-disabled]="disabled()"
|
||||||
class="cart-icon"
|
class="cart-icon"
|
||||||
>
|
>
|
||||||
<div class="cart-icon__container">
|
<div class="cart-icon__container">
|
||||||
|
|||||||
@@ -14,7 +14,9 @@
|
|||||||
color: #666666;
|
color: #666666;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
outline: none;
|
outline: none;
|
||||||
transition: color 0.15s ease-in-out, transform 0.1s ease-in-out;
|
transition:
|
||||||
|
color 0.15s ease-in-out,
|
||||||
|
transform 0.1s ease-in-out;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
|
|
||||||
// Active state subtle scale down
|
// Active state subtle scale down
|
||||||
@@ -29,10 +31,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Disabled state
|
// Disabled state
|
||||||
&:disabled {
|
&:disabled,
|
||||||
color: #A0A0A0;
|
&.cart-icon--disabled {
|
||||||
|
color: #b8b8b8;
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
|
opacity: 0.45;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +63,11 @@
|
|||||||
line-height: 1;
|
line-height: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cart-icon:disabled .cart-icon__glyph,
|
||||||
|
.cart-icon--disabled .cart-icon__glyph {
|
||||||
|
color: #b8b8b8;
|
||||||
|
}
|
||||||
|
|
||||||
.cart-icon__badge {
|
.cart-icon__badge {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: -8px;
|
top: -8px;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { CartIconComponent } from './cart-icon.component';
|
|||||||
describe('CartIconComponent', () => {
|
describe('CartIconComponent', () => {
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [CartIconComponent]
|
imports: [CartIconComponent],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ describe('CartIconComponent', () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
fixture,
|
fixture,
|
||||||
element: fixture.nativeElement as HTMLElement
|
element: fixture.nativeElement as HTMLElement,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,9 +47,11 @@ describe('CartIconComponent', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('disables the button when disabled is true', () => {
|
it('disables the button when disabled is true', () => {
|
||||||
const { element } = setup(undefined, true);
|
const { element } = setup(3, true);
|
||||||
const button = element.querySelector('button');
|
const button = element.querySelector('button');
|
||||||
expect(button?.disabled).toBe(true);
|
expect(button?.disabled).toBe(true);
|
||||||
|
expect(button?.classList).toContain('cart-icon--disabled');
|
||||||
|
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('enables the button when disabled is false', () => {
|
it('enables the button when disabled is false', () => {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ChangeDetectionStrategy, Component, computed, input } from '@angular/co
|
|||||||
imports: [],
|
imports: [],
|
||||||
templateUrl: './cart-icon.component.html',
|
templateUrl: './cart-icon.component.html',
|
||||||
styleUrl: './cart-icon.component.scss',
|
styleUrl: './cart-icon.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class CartIconComponent {
|
export class CartIconComponent {
|
||||||
readonly quantity = input<number | null | undefined>(undefined);
|
readonly quantity = input<number | null | undefined>(undefined);
|
||||||
@@ -13,6 +13,10 @@ export class CartIconComponent {
|
|||||||
readonly ariaLabel = input<string>('Carrito de compras');
|
readonly ariaLabel = input<string>('Carrito de compras');
|
||||||
|
|
||||||
protected readonly hasQuantity = computed(() => {
|
protected readonly hasQuantity = computed(() => {
|
||||||
|
if (this.disabled()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
const q = this.quantity();
|
const q = this.quantity();
|
||||||
return q !== null && q !== undefined && q > 0;
|
return q !== null && q !== undefined && q > 0;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -175,6 +175,63 @@ describe('CartComponent', () => {
|
|||||||
expect(removeItem).not.toHaveBeenCalled();
|
expect(removeItem).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('notifies the user and refreshes the cart when a mutation reports expiration', async () => {
|
||||||
|
const expirationMessage = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
||||||
|
const removeItem = vi.fn().mockReturnValue(
|
||||||
|
throwError(() => ({
|
||||||
|
error: {
|
||||||
|
code: 'stock_reservation.expired',
|
||||||
|
message: expirationMessage,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const loadCart = vi.fn().mockReturnValue(of({}));
|
||||||
|
const danger = vi.fn();
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [CartComponent],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: CartService,
|
||||||
|
useValue: {
|
||||||
|
cart: signal(null).asReadonly(),
|
||||||
|
loadCart,
|
||||||
|
updateItemQuantity: vi.fn(),
|
||||||
|
removeItem,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ModalService,
|
||||||
|
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ToastService,
|
||||||
|
useValue: { success: vi.fn(), info: vi.fn(), danger },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(CartComponent);
|
||||||
|
fixture.componentRef.setInput('items', [
|
||||||
|
{
|
||||||
|
cartItemId: 10,
|
||||||
|
imageUrl: null,
|
||||||
|
product: 'Producto vencido',
|
||||||
|
originalPrice: null,
|
||||||
|
discountedPrice: 1000,
|
||||||
|
discountPercentage: null,
|
||||||
|
attributes: [],
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
fixture.debugElement.query(By.css('app-cart-item')).triggerEventHandler('remove');
|
||||||
|
|
||||||
|
expect(danger).toHaveBeenCalledWith(expirationMessage);
|
||||||
|
expect(loadCart).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('optimistically updates quantity and rolls back on error', async () => {
|
it('optimistically updates quantity and rolls back on error', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
|
const updateItemQuantity = vi.fn().mockReturnValue(throwError(() => new Error('Error')));
|
||||||
|
|||||||
@@ -98,11 +98,12 @@ export class CartComponent {
|
|||||||
this.clearOverride(update.cartItemId);
|
this.clearOverride(update.cartItemId);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
console.error('Error updating cart quantity', err);
|
|
||||||
const msg =
|
|
||||||
err.error?.message || 'Error al actualizar la cantidad del producto.';
|
|
||||||
this.toastService.danger(msg);
|
|
||||||
this.clearOverride(update.cartItemId);
|
this.clearOverride(update.cartItemId);
|
||||||
|
this.handleMutationError(
|
||||||
|
err,
|
||||||
|
'Error al actualizar la cantidad del producto.',
|
||||||
|
'Error updating cart quantity',
|
||||||
|
);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
catchError(() => EMPTY),
|
catchError(() => EMPTY),
|
||||||
@@ -205,9 +206,12 @@ export class CartComponent {
|
|||||||
this.toastService.success(response.message || 'Variante actualizada.');
|
this.toastService.success(response.message || 'Variante actualizada.');
|
||||||
},
|
},
|
||||||
error: (error: HttpErrorResponse) => {
|
error: (error: HttpErrorResponse) => {
|
||||||
console.error('Error updating cart item variant', error);
|
|
||||||
this.clearVariantOverride(cartItemId);
|
this.clearVariantOverride(cartItemId);
|
||||||
this.toastService.danger(error.error?.message || 'No se pudo actualizar la variante.');
|
this.handleMutationError(
|
||||||
|
error,
|
||||||
|
'No se pudo actualizar la variante.',
|
||||||
|
'Error updating cart item variant',
|
||||||
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -305,10 +309,29 @@ export class CartComponent {
|
|||||||
this.toastService.info(msg);
|
this.toastService.info(msg);
|
||||||
},
|
},
|
||||||
error: (err: HttpErrorResponse) => {
|
error: (err: HttpErrorResponse) => {
|
||||||
console.error('Error removing item from cart', err);
|
this.handleMutationError(
|
||||||
const msg = err.error?.message || 'Error al eliminar el producto del carrito.';
|
err,
|
||||||
this.toastService.danger(msg);
|
'Error al eliminar el producto del carrito.',
|
||||||
|
'Error removing item from cart',
|
||||||
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private handleMutationError(
|
||||||
|
error: HttpErrorResponse,
|
||||||
|
fallbackMessage: string,
|
||||||
|
logMessage: string,
|
||||||
|
): void {
|
||||||
|
console.error(logMessage, error);
|
||||||
|
this.toastService.danger(error.error?.message || fallbackMessage);
|
||||||
|
|
||||||
|
if (error.error?.code !== 'stock_reservation.expired') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<div
|
||||||
|
class="image-modal"
|
||||||
|
[class.image-modal--gesturing]="gestureActive()"
|
||||||
|
[class.image-modal--settling]="swipeSettling()"
|
||||||
|
[style.transform]="swipeTransform()"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
#viewport
|
||||||
|
class="image-modal__viewport"
|
||||||
|
[class.image-modal__viewport--zoomed]="zoom() > data.minZoom"
|
||||||
|
(wheel)="onWheel($event)"
|
||||||
|
(dblclick)="onDoubleClick($event)"
|
||||||
|
(pointerdown)="onPointerDown($event)"
|
||||||
|
(pointermove)="onPointerMove($event)"
|
||||||
|
(pointerup)="onPointerUp($event)"
|
||||||
|
(pointercancel)="onPointerUp($event)"
|
||||||
|
>
|
||||||
|
@if (!imageFailed()) {
|
||||||
|
<img
|
||||||
|
#image
|
||||||
|
class="image-modal__image"
|
||||||
|
[src]="data.src"
|
||||||
|
[alt]="data.alt"
|
||||||
|
[style.transform]="transform()"
|
||||||
|
decoding="async"
|
||||||
|
draggable="false"
|
||||||
|
(load)="onImageLoad()"
|
||||||
|
(error)="imageFailed.set(true)"
|
||||||
|
/>
|
||||||
|
} @else {
|
||||||
|
<p class="image-modal__error" role="alert">No se pudo cargar la imagen.</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="image-modal__controls" aria-label="Controles de zoom">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="image-modal__control"
|
||||||
|
aria-label="Alejar"
|
||||||
|
[disabled]="zoom() <= data.minZoom"
|
||||||
|
(click)="zoomOut()"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
<button type="button" class="image-modal__zoom" aria-label="Restablecer zoom" (click)="reset()">
|
||||||
|
{{ zoomLabel() }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="image-modal__control"
|
||||||
|
aria-label="Acercar"
|
||||||
|
[disabled]="zoom() >= data.maxZoom"
|
||||||
|
(click)="zoomIn()"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
146
src/app/shared/components/image-modal/image-modal.component.scss
Normal file
146
src/app/shared/components/image-modal/image-modal.component.scss
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
:host {
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
background: black;
|
||||||
|
transform-origin: center top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal--settling {
|
||||||
|
transition: transform 180ms ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal--gesturing {
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__viewport {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
overflow: hidden;
|
||||||
|
cursor: zoom-in;
|
||||||
|
touch-action: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__viewport--zoomed {
|
||||||
|
cursor: grab;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__viewport--zoomed:active {
|
||||||
|
cursor: grabbing;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__image {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 100%;
|
||||||
|
object-fit: contain;
|
||||||
|
transform-origin: center;
|
||||||
|
transition: transform 120ms ease-out;
|
||||||
|
-webkit-user-drag: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal--gesturing .image-modal__image {
|
||||||
|
transition: none;
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__viewport:active .image-modal__image {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__error {
|
||||||
|
margin: 1rem;
|
||||||
|
color: #ffffff;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__controls {
|
||||||
|
position: absolute;
|
||||||
|
right: 50%;
|
||||||
|
bottom: max(1.25rem, env(safe-area-inset-bottom));
|
||||||
|
z-index: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.25);
|
||||||
|
border-radius: 2rem;
|
||||||
|
background: rgba(20, 20, 20, 0.78);
|
||||||
|
box-shadow: 0 0.25rem 1rem rgba(0, 0, 0, 0.3);
|
||||||
|
transform: translateX(50%);
|
||||||
|
backdrop-filter: blur(0.5rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__control,
|
||||||
|
.image-modal__zoom {
|
||||||
|
display: inline-flex;
|
||||||
|
height: 2.75rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 0;
|
||||||
|
color: #ffffff;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__control {
|
||||||
|
width: 2.75rem;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__zoom {
|
||||||
|
min-width: 4rem;
|
||||||
|
padding: 0 0.5rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__control:hover:not(:disabled),
|
||||||
|
.image-modal__zoom:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__control:focus-visible,
|
||||||
|
.image-modal__zoom:focus-visible {
|
||||||
|
outline: 2px solid #ffffff;
|
||||||
|
outline-offset: -3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-modal__control:disabled {
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 576px) {
|
||||||
|
.image-modal__controls {
|
||||||
|
bottom: max(1rem, env(safe-area-inset-bottom));
|
||||||
|
background: rgba(20, 20, 20, 0.94);
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (pointer: coarse) {
|
||||||
|
.image-modal__controls {
|
||||||
|
background: rgba(20, 20, 20, 0.94);
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.image-modal__image {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import '@angular/compiler';
|
||||||
|
import { ComponentFixture, TestBed, getTestBed } from '@angular/core/testing';
|
||||||
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { ImageModalData, MODAL_DATA, ModalRef } from '../../../core/services/modal.service';
|
||||||
|
import { ImageModalComponent } from './image-modal.component';
|
||||||
|
|
||||||
|
describe('ImageModalComponent', () => {
|
||||||
|
let fixture: ComponentFixture<ImageModalComponent>;
|
||||||
|
const modalRef = { dismiss: vi.fn() };
|
||||||
|
const data: ImageModalData = {
|
||||||
|
src: '/images/producto.webp',
|
||||||
|
alt: 'Vista frontal del producto',
|
||||||
|
initialZoom: 1,
|
||||||
|
minZoom: 1,
|
||||||
|
maxZoom: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
try {
|
||||||
|
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||||
|
} catch {
|
||||||
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
modalRef.dismiss.mockReset();
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [ImageModalComponent],
|
||||||
|
providers: [
|
||||||
|
{ provide: MODAL_DATA, useValue: data },
|
||||||
|
{ provide: ModalRef, useValue: modalRef },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
fixture = TestBed.createComponent(ImageModalComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fixture.destroy();
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the image and accessible zoom controls', () => {
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const image = element.querySelector('img') as HTMLImageElement;
|
||||||
|
|
||||||
|
expect(image.getAttribute('src')).toBe('/images/producto.webp');
|
||||||
|
expect(image.alt).toBe('Vista frontal del producto');
|
||||||
|
expect(element.querySelector('[aria-label="Acercar"]')).not.toBeNull();
|
||||||
|
expect(element.querySelector('[aria-label="Alejar"]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('zooms with controls, respects limits, and resets', () => {
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const zoomIn = element.querySelector('[aria-label="Acercar"]') as HTMLButtonElement;
|
||||||
|
const zoomOut = element.querySelector('[aria-label="Alejar"]') as HTMLButtonElement;
|
||||||
|
const reset = element.querySelector('[aria-label="Restablecer zoom"]') as HTMLButtonElement;
|
||||||
|
|
||||||
|
zoomIn.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(reset.textContent).toContain('150%');
|
||||||
|
expect(zoomOut.disabled).toBe(false);
|
||||||
|
|
||||||
|
zoomIn.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(reset.textContent).toContain('200%');
|
||||||
|
expect(zoomIn.disabled).toBe(true);
|
||||||
|
|
||||||
|
reset.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(reset.textContent).toContain('100%');
|
||||||
|
expect(zoomOut.disabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports pinch zoom through touch pointer events', async () => {
|
||||||
|
const viewport = fixture.nativeElement.querySelector('.image-modal__viewport') as HTMLElement;
|
||||||
|
const zoom = fixture.nativeElement.querySelector(
|
||||||
|
'[aria-label="Restablecer zoom"]',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerdown', 1, 100, 100));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerdown', 2, 200, 100));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointermove', 2, 250, 100));
|
||||||
|
await renderNextFrame();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(zoom.textContent).toContain('150%');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dismisses with a downward swipe while the image is at its base zoom', async () => {
|
||||||
|
const viewport = fixture.nativeElement.querySelector('.image-modal__viewport') as HTMLElement;
|
||||||
|
const modal = fixture.nativeElement.querySelector('.image-modal') as HTMLElement;
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerdown', 1, 150, 100));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointermove', 1, 155, 230));
|
||||||
|
await renderNextFrame();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(modal.style.transform).toBe('translate3d(0, 130px, 0)');
|
||||||
|
expect(Number(modal.style.opacity)).toBeLessThan(1);
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerup', 1, 155, 230));
|
||||||
|
|
||||||
|
expect(modalRef.dismiss).toHaveBeenCalledWith('swipe');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns smoothly to its position when the swipe is too short', async () => {
|
||||||
|
const viewport = fixture.nativeElement.querySelector('.image-modal__viewport') as HTMLElement;
|
||||||
|
const modal = fixture.nativeElement.querySelector('.image-modal') as HTMLElement;
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerdown', 1, 150, 100));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointermove', 1, 150, 160));
|
||||||
|
await renderNextFrame();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(modal.style.transform).toBe('translate3d(0, 60px, 0)');
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerup', 1, 150, 160));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(modalRef.dismiss).not.toHaveBeenCalled();
|
||||||
|
expect(modal.classList.contains('image-modal--settling')).toBe(true);
|
||||||
|
expect(modal.style.transform).toBe('translate3d(0, 0px, 0)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not dismiss with a downward gesture while the image is zoomed', () => {
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const viewport = element.querySelector('.image-modal__viewport') as HTMLElement;
|
||||||
|
const zoomIn = element.querySelector('[aria-label="Acercar"]') as HTMLButtonElement;
|
||||||
|
zoomIn.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerdown', 1, 150, 100));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointermove', 1, 155, 230));
|
||||||
|
viewport.dispatchEvent(pointerEvent('pointerup', 1, 155, 230));
|
||||||
|
|
||||||
|
expect(modalRef.dismiss).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a fallback when the image cannot be loaded', () => {
|
||||||
|
const image = fixture.nativeElement.querySelector('img') as HTMLImageElement;
|
||||||
|
image.dispatchEvent(new Event('error'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('[role="alert"]')?.textContent).toContain(
|
||||||
|
'No se pudo cargar la imagen',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function pointerEvent(type: string, pointerId: number, clientX: number, clientY: number): Event {
|
||||||
|
const event = new MouseEvent(type, { bubbles: true, clientX, clientY });
|
||||||
|
Object.defineProperties(event, {
|
||||||
|
pointerId: { value: pointerId },
|
||||||
|
pointerType: { value: 'touch' },
|
||||||
|
});
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderNextFrame(): Promise<void> {
|
||||||
|
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||||
|
}
|
||||||
395
src/app/shared/components/image-modal/image-modal.component.ts
Normal file
395
src/app/shared/components/image-modal/image-modal.component.ts
Normal file
@@ -0,0 +1,395 @@
|
|||||||
|
import {
|
||||||
|
ChangeDetectionStrategy,
|
||||||
|
Component,
|
||||||
|
DestroyRef,
|
||||||
|
ElementRef,
|
||||||
|
computed,
|
||||||
|
inject,
|
||||||
|
signal,
|
||||||
|
viewChild,
|
||||||
|
} from '@angular/core';
|
||||||
|
|
||||||
|
import { ImageModalData, MODAL_DATA, ModalRef } from '../../../core/services/modal.service';
|
||||||
|
|
||||||
|
const SWIPE_DISMISS_DISTANCE = 100;
|
||||||
|
const SWIPE_DIRECTION_RATIO = 1.25;
|
||||||
|
|
||||||
|
interface Point {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ViewerGeometry {
|
||||||
|
imageHeight: number;
|
||||||
|
imageWidth: number;
|
||||||
|
viewportHeight: number;
|
||||||
|
viewportLeft: number;
|
||||||
|
viewportTop: number;
|
||||||
|
viewportWidth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-image-modal',
|
||||||
|
templateUrl: './image-modal.component.html',
|
||||||
|
styleUrl: './image-modal.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
})
|
||||||
|
export class ImageModalComponent {
|
||||||
|
protected readonly data = inject<ImageModalData>(MODAL_DATA);
|
||||||
|
private readonly modalRef = inject<ModalRef<void>>(ModalRef);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
private readonly viewport = viewChild.required<ElementRef<HTMLElement>>('viewport');
|
||||||
|
private readonly image = viewChild<ElementRef<HTMLImageElement>>('image');
|
||||||
|
private readonly pointers = new Map<number, Point>();
|
||||||
|
|
||||||
|
protected readonly zoom = signal(this.data.initialZoom);
|
||||||
|
protected readonly offsetX = signal(0);
|
||||||
|
protected readonly offsetY = signal(0);
|
||||||
|
protected readonly imageFailed = signal(false);
|
||||||
|
protected readonly swipeOffsetY = signal(0);
|
||||||
|
protected readonly swipeSettling = signal(false);
|
||||||
|
protected readonly gestureActive = signal(false);
|
||||||
|
protected readonly transform = computed(
|
||||||
|
() => `translate3d(${this.offsetX()}px, ${this.offsetY()}px, 0) scale(${this.zoom()})`,
|
||||||
|
);
|
||||||
|
protected readonly zoomLabel = computed(() => `${Math.round(this.zoom() * 100)}%`);
|
||||||
|
protected readonly swipeTransform = computed(() => `translate3d(0, ${this.swipeOffsetY()}px, 0)`);
|
||||||
|
|
||||||
|
private dragStart: Point | null = null;
|
||||||
|
private dragOffset: Point = { x: 0, y: 0 };
|
||||||
|
private pinchDistance = 0;
|
||||||
|
private pinchZoom = 1;
|
||||||
|
private pinchLocal: Point = { x: 0, y: 0 };
|
||||||
|
private pointerDownAt: Point | null = null;
|
||||||
|
private gestureMoved = false;
|
||||||
|
private hadMultiplePointers = false;
|
||||||
|
private lastTapAt = 0;
|
||||||
|
private swipeStart: Point | null = null;
|
||||||
|
private geometry: ViewerGeometry | null = null;
|
||||||
|
private animationFrameId: number | null = null;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.destroyRef.onDestroy(() => this.cancelGestureFrame());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected zoomIn(): void {
|
||||||
|
this.setZoomAt(Math.min(this.data.maxZoom, this.zoom() + 0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected zoomOut(): void {
|
||||||
|
this.setZoomAt(Math.max(this.data.minZoom, this.zoom() - 0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected reset(): void {
|
||||||
|
this.zoom.set(this.data.initialZoom);
|
||||||
|
this.offsetX.set(0);
|
||||||
|
this.offsetY.set(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onWheel(event: WheelEvent): void {
|
||||||
|
event.preventDefault();
|
||||||
|
const factor = event.deltaY < 0 ? 1.15 : 1 / 1.15;
|
||||||
|
this.setZoomAt(this.zoom() * factor, event.clientX, event.clientY);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onDoubleClick(event: MouseEvent): void {
|
||||||
|
this.toggleZoom(event.clientX, event.clientY);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onPointerDown(event: PointerEvent): void {
|
||||||
|
if (event.pointerType === 'mouse' && event.button !== 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
if (this.pointers.size === 0) {
|
||||||
|
this.refreshGeometry();
|
||||||
|
this.gestureActive.set(true);
|
||||||
|
}
|
||||||
|
this.viewport().nativeElement.setPointerCapture?.(event.pointerId);
|
||||||
|
const point = { x: event.clientX, y: event.clientY };
|
||||||
|
this.pointers.set(event.pointerId, point);
|
||||||
|
this.pointerDownAt = point;
|
||||||
|
this.gestureMoved = false;
|
||||||
|
|
||||||
|
if (this.pointers.size === 1) {
|
||||||
|
this.swipeSettling.set(false);
|
||||||
|
this.dragStart = point;
|
||||||
|
this.dragOffset = { x: this.offsetX(), y: this.offsetY() };
|
||||||
|
this.swipeStart =
|
||||||
|
event.pointerType === 'touch' && this.zoom() <= this.data.minZoom + 0.01 ? point : null;
|
||||||
|
} else if (this.pointers.size === 2) {
|
||||||
|
this.hadMultiplePointers = true;
|
||||||
|
this.swipeStart = null;
|
||||||
|
this.swipeOffsetY.set(0);
|
||||||
|
this.beginPinch();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onPointerMove(event: PointerEvent): void {
|
||||||
|
if (!this.pointers.has(event.pointerId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const point = { x: event.clientX, y: event.clientY };
|
||||||
|
this.pointers.set(event.pointerId, point);
|
||||||
|
|
||||||
|
if (this.pointerDownAt && this.distance(this.pointerDownAt, point) > 4) {
|
||||||
|
this.gestureMoved = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleGestureFrame();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onPointerUp(event: PointerEvent): void {
|
||||||
|
const wasTouch = event.pointerType === 'touch';
|
||||||
|
const trackedPoint = this.pointers.get(event.pointerId);
|
||||||
|
const endPoint = trackedPoint ? { x: event.clientX, y: event.clientY } : null;
|
||||||
|
if (endPoint) {
|
||||||
|
this.pointers.set(event.pointerId, endPoint);
|
||||||
|
if (this.animationFrameId !== null) {
|
||||||
|
this.flushGestureFrame();
|
||||||
|
} else {
|
||||||
|
this.applyPointerMovement();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const shouldDismiss =
|
||||||
|
event.type === 'pointerup' &&
|
||||||
|
wasTouch &&
|
||||||
|
endPoint !== null &&
|
||||||
|
this.isSwipeDown(this.swipeStart, endPoint);
|
||||||
|
this.pointers.delete(event.pointerId);
|
||||||
|
const viewport = this.viewport().nativeElement;
|
||||||
|
if (viewport.hasPointerCapture?.(event.pointerId)) {
|
||||||
|
viewport.releasePointerCapture(event.pointerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldDismiss) {
|
||||||
|
this.resetGesture();
|
||||||
|
this.modalRef.dismiss('swipe');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasTouch && endPoint && !this.gestureMoved && !this.hadMultiplePointers) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - this.lastTapAt < 300) {
|
||||||
|
this.toggleZoom(endPoint.x, endPoint.y);
|
||||||
|
this.lastTapAt = 0;
|
||||||
|
} else {
|
||||||
|
this.lastTapAt = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.pointers.size === 1) {
|
||||||
|
const remaining = [...this.pointers.values()][0];
|
||||||
|
this.dragStart = remaining;
|
||||||
|
this.dragOffset = { x: this.offsetX(), y: this.offsetY() };
|
||||||
|
} else if (this.pointers.size === 0) {
|
||||||
|
this.dragStart = null;
|
||||||
|
this.pointerDownAt = null;
|
||||||
|
this.hadMultiplePointers = false;
|
||||||
|
this.swipeStart = null;
|
||||||
|
this.gestureActive.set(false);
|
||||||
|
if (this.swipeOffsetY() > 0) {
|
||||||
|
this.swipeSettling.set(true);
|
||||||
|
this.swipeOffsetY.set(0);
|
||||||
|
}
|
||||||
|
this.clampOffset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onImageLoad(): void {
|
||||||
|
this.imageFailed.set(false);
|
||||||
|
this.refreshGeometry();
|
||||||
|
this.clampOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private beginPinch(): void {
|
||||||
|
const [first, second] = [...this.pointers.values()];
|
||||||
|
const midpoint = this.midpoint(first, second);
|
||||||
|
const geometry = this.geometry ?? this.refreshGeometry();
|
||||||
|
if (!geometry) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pinchDistance = Math.max(1, this.distance(first, second));
|
||||||
|
this.pinchZoom = this.zoom();
|
||||||
|
this.pinchLocal = {
|
||||||
|
x:
|
||||||
|
(midpoint.x - (geometry.viewportLeft + geometry.viewportWidth / 2) - this.offsetX()) /
|
||||||
|
this.zoom(),
|
||||||
|
y:
|
||||||
|
(midpoint.y - (geometry.viewportTop + geometry.viewportHeight / 2) - this.offsetY()) /
|
||||||
|
this.zoom(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toggleZoom(clientX?: number, clientY?: number): void {
|
||||||
|
const target =
|
||||||
|
this.zoom() > this.data.minZoom + 0.01
|
||||||
|
? this.data.minZoom
|
||||||
|
: Math.min(this.data.maxZoom, Math.max(2, this.data.minZoom));
|
||||||
|
this.setZoomAt(target, clientX, clientY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private setZoomAt(value: number, clientX?: number, clientY?: number): void {
|
||||||
|
const nextZoom = this.clampZoom(value);
|
||||||
|
const currentZoom = this.zoom();
|
||||||
|
const geometry = this.refreshGeometry();
|
||||||
|
|
||||||
|
if (clientX !== undefined && clientY !== undefined && currentZoom > 0 && geometry) {
|
||||||
|
const pointX = clientX - (geometry.viewportLeft + geometry.viewportWidth / 2);
|
||||||
|
const pointY = clientY - (geometry.viewportTop + geometry.viewportHeight / 2);
|
||||||
|
const localX = (pointX - this.offsetX()) / currentZoom;
|
||||||
|
const localY = (pointY - this.offsetY()) / currentZoom;
|
||||||
|
this.offsetX.set(pointX - localX * nextZoom);
|
||||||
|
this.offsetY.set(pointY - localY * nextZoom);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.zoom.set(nextZoom);
|
||||||
|
if (nextZoom <= this.data.minZoom) {
|
||||||
|
this.offsetX.set(0);
|
||||||
|
this.offsetY.set(0);
|
||||||
|
}
|
||||||
|
this.clampOffset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private clampZoom(value: number): number {
|
||||||
|
return Math.min(this.data.maxZoom, Math.max(this.data.minZoom, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private clampOffset(): void {
|
||||||
|
const geometry = this.geometry;
|
||||||
|
if (!geometry) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxX = Math.max(0, (geometry.imageWidth * this.zoom() - geometry.viewportWidth) / 2);
|
||||||
|
const maxY = Math.max(0, (geometry.imageHeight * this.zoom() - geometry.viewportHeight) / 2);
|
||||||
|
|
||||||
|
this.offsetX.set(Math.min(maxX, Math.max(-maxX, this.offsetX())));
|
||||||
|
this.offsetY.set(Math.min(maxY, Math.max(-maxY, this.offsetY())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private midpoint(first: Point, second: Point): Point {
|
||||||
|
return { x: (first.x + second.x) / 2, y: (first.y + second.y) / 2 };
|
||||||
|
}
|
||||||
|
|
||||||
|
private distance(first: Point, second: Point): number {
|
||||||
|
return Math.hypot(second.x - first.x, second.y - first.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isSwipeDown(start: Point | null, end: Point): boolean {
|
||||||
|
if (!start || this.hadMultiplePointers || this.zoom() > this.data.minZoom + 0.01) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deltaX = Math.abs(end.x - start.x);
|
||||||
|
const deltaY = end.y - start.y;
|
||||||
|
return deltaY >= SWIPE_DISMISS_DISTANCE && deltaY >= deltaX * SWIPE_DIRECTION_RATIO;
|
||||||
|
}
|
||||||
|
|
||||||
|
private resetGesture(): void {
|
||||||
|
this.cancelGestureFrame();
|
||||||
|
this.pointers.clear();
|
||||||
|
this.dragStart = null;
|
||||||
|
this.pointerDownAt = null;
|
||||||
|
this.swipeStart = null;
|
||||||
|
this.hadMultiplePointers = false;
|
||||||
|
this.gestureActive.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleGestureFrame(): void {
|
||||||
|
if (this.animationFrameId !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.animationFrameId = requestAnimationFrame(() => {
|
||||||
|
this.animationFrameId = null;
|
||||||
|
this.applyPointerMovement();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private flushGestureFrame(): void {
|
||||||
|
if (this.animationFrameId === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelAnimationFrame(this.animationFrameId);
|
||||||
|
this.animationFrameId = null;
|
||||||
|
this.applyPointerMovement();
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelGestureFrame(): void {
|
||||||
|
if (this.animationFrameId !== null) {
|
||||||
|
cancelAnimationFrame(this.animationFrameId);
|
||||||
|
this.animationFrameId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyPointerMovement(): void {
|
||||||
|
if (this.pointers.size === 2) {
|
||||||
|
const [first, second] = [...this.pointers.values()];
|
||||||
|
const geometry = this.geometry;
|
||||||
|
if (!geometry) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const distance = this.distance(first, second);
|
||||||
|
const midpoint = this.midpoint(first, second);
|
||||||
|
const nextZoom = this.clampZoom(this.pinchZoom * (distance / this.pinchDistance));
|
||||||
|
|
||||||
|
this.zoom.set(nextZoom);
|
||||||
|
this.offsetX.set(
|
||||||
|
midpoint.x -
|
||||||
|
(geometry.viewportLeft + geometry.viewportWidth / 2) -
|
||||||
|
this.pinchLocal.x * nextZoom,
|
||||||
|
);
|
||||||
|
this.offsetY.set(
|
||||||
|
midpoint.y -
|
||||||
|
(geometry.viewportTop + geometry.viewportHeight / 2) -
|
||||||
|
this.pinchLocal.y * nextZoom,
|
||||||
|
);
|
||||||
|
this.clampOffset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.pointers.size !== 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const point = [...this.pointers.values()][0];
|
||||||
|
if (this.swipeStart) {
|
||||||
|
const deltaX = Math.abs(point.x - this.swipeStart.x);
|
||||||
|
const deltaY = point.y - this.swipeStart.y;
|
||||||
|
this.swipeOffsetY.set(deltaY > 0 && deltaY >= deltaX ? deltaY : 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.dragStart && this.zoom() > this.data.minZoom) {
|
||||||
|
this.offsetX.set(this.dragOffset.x + point.x - this.dragStart.x);
|
||||||
|
this.offsetY.set(this.dragOffset.y + point.y - this.dragStart.y);
|
||||||
|
this.clampOffset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private refreshGeometry(): ViewerGeometry | null {
|
||||||
|
const viewport = this.viewport().nativeElement;
|
||||||
|
const image = this.image()?.nativeElement;
|
||||||
|
if (!image) {
|
||||||
|
this.geometry = null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rect = viewport.getBoundingClientRect();
|
||||||
|
this.geometry = {
|
||||||
|
imageHeight: image.offsetHeight,
|
||||||
|
imageWidth: image.offsetWidth,
|
||||||
|
viewportHeight: viewport.clientHeight,
|
||||||
|
viewportLeft: rect.left,
|
||||||
|
viewportTop: rect.top,
|
||||||
|
viewportWidth: viewport.clientWidth,
|
||||||
|
};
|
||||||
|
return this.geometry;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
<app-modal-shell
|
<app-modal-shell
|
||||||
[title]="modal.config.title"
|
[title]="modal.config.title"
|
||||||
[size]="modal.config.size"
|
[size]="modal.config.size"
|
||||||
|
[presentation]="modal.config.presentation ?? 'dialog'"
|
||||||
[showCloseButton]="modal.config.showCloseButton"
|
[showCloseButton]="modal.config.showCloseButton"
|
||||||
(backdropClick)="onBackdropClick()"
|
(backdropClick)="onBackdropClick()"
|
||||||
(closeRequested)="onCloseRequested()"
|
(closeRequested)="onCloseRequested()"
|
||||||
|
|||||||
@@ -51,6 +51,10 @@ describe('ModalHostComponent', () => {
|
|||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
doc.body.style.overflow = '';
|
doc.body.style.overflow = '';
|
||||||
doc.body.style.paddingRight = '';
|
doc.body.style.paddingRight = '';
|
||||||
|
doc.body.style.position = '';
|
||||||
|
doc.body.style.top = '';
|
||||||
|
doc.body.style.left = '';
|
||||||
|
doc.body.style.width = '';
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,6 +103,10 @@ describe('ModalHostComponent', () => {
|
|||||||
expect(service.activeModal()).toBeNull();
|
expect(service.activeModal()).toBeNull();
|
||||||
expect(doc.body.style.overflow).toBe('');
|
expect(doc.body.style.overflow).toBe('');
|
||||||
expect(doc.body.style.paddingRight).toBe('');
|
expect(doc.body.style.paddingRight).toBe('');
|
||||||
|
expect(doc.body.style.position).toBe('');
|
||||||
|
expect(doc.body.style.top).toBe('');
|
||||||
|
expect(doc.body.style.left).toBe('');
|
||||||
|
expect(doc.body.style.width).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('closes on backdrop click when enabled', () => {
|
it('closes on backdrop click when enabled', () => {
|
||||||
|
|||||||
@@ -55,11 +55,23 @@ export class ModalHostComponent {
|
|||||||
const body = this.document.body;
|
const body = this.document.body;
|
||||||
const previousOverflow = body.style.overflow;
|
const previousOverflow = body.style.overflow;
|
||||||
const previousPaddingRight = body.style.paddingRight;
|
const previousPaddingRight = body.style.paddingRight;
|
||||||
|
const previousPosition = body.style.position;
|
||||||
|
const previousTop = body.style.top;
|
||||||
|
const previousLeft = body.style.left;
|
||||||
|
const previousWidth = body.style.width;
|
||||||
const view = this.document.defaultView;
|
const view = this.document.defaultView;
|
||||||
|
const scrollX = view?.scrollX ?? 0;
|
||||||
|
const scrollY = view?.scrollY ?? 0;
|
||||||
const scrollbarWidth = view
|
const scrollbarWidth = view
|
||||||
? Math.max(0, view.innerWidth - this.document.documentElement.clientWidth)
|
? Math.max(0, view.innerWidth - this.document.documentElement.clientWidth)
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
|
const activeElement = this.document.activeElement;
|
||||||
|
|
||||||
|
if (activeElement instanceof HTMLElement && activeElement !== body) {
|
||||||
|
activeElement.blur();
|
||||||
|
}
|
||||||
|
|
||||||
if (scrollbarWidth > 0 && view) {
|
if (scrollbarWidth > 0 && view) {
|
||||||
const currentPaddingRight =
|
const currentPaddingRight =
|
||||||
Number.parseFloat(view.getComputedStyle(body).paddingRight) || 0;
|
Number.parseFloat(view.getComputedStyle(body).paddingRight) || 0;
|
||||||
@@ -68,6 +80,47 @@ export class ModalHostComponent {
|
|||||||
|
|
||||||
body.style.overflow = 'hidden';
|
body.style.overflow = 'hidden';
|
||||||
|
|
||||||
|
const isIos = view
|
||||||
|
? /iPad|iPhone|iPod/.test(view.navigator.userAgent) ||
|
||||||
|
(view.navigator.platform === 'MacIntel' && view.navigator.maxTouchPoints > 1)
|
||||||
|
: false;
|
||||||
|
|
||||||
|
if (isIos) {
|
||||||
|
body.style.position = 'fixed';
|
||||||
|
body.style.top = `${-scrollY}px`;
|
||||||
|
body.style.left = `${-scrollX}px`;
|
||||||
|
body.style.width = '100%';
|
||||||
|
}
|
||||||
|
|
||||||
|
let viewportFrame: number | undefined;
|
||||||
|
const viewportSyncTimers: number[] = [];
|
||||||
|
const syncVisualViewport = () => {
|
||||||
|
if (!view) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (viewportFrame !== undefined) {
|
||||||
|
view.cancelAnimationFrame(viewportFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
viewportFrame = view.requestAnimationFrame(() => {
|
||||||
|
viewportFrame = undefined;
|
||||||
|
this.modalShell()?.setVisualViewport(view.visualViewport, view.scrollX, view.scrollY);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
view?.visualViewport?.addEventListener('resize', syncVisualViewport);
|
||||||
|
view?.visualViewport?.addEventListener('scroll', syncVisualViewport);
|
||||||
|
view?.addEventListener('orientationchange', syncVisualViewport);
|
||||||
|
syncVisualViewport();
|
||||||
|
|
||||||
|
if (view) {
|
||||||
|
viewportSyncTimers.push(
|
||||||
|
view.setTimeout(syncVisualViewport, 100),
|
||||||
|
view.setTimeout(syncVisualViewport, 300),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const onKeyDown = (event: KeyboardEvent) => {
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
if (event.key !== 'Escape' || !this.activeModal()?.config.closeOnEscape) {
|
if (event.key !== 'Escape' || !this.activeModal()?.config.closeOnEscape) {
|
||||||
return;
|
return;
|
||||||
@@ -82,8 +135,26 @@ export class ModalHostComponent {
|
|||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
this.document.removeEventListener('keydown', onKeyDown);
|
this.document.removeEventListener('keydown', onKeyDown);
|
||||||
|
view?.visualViewport?.removeEventListener('resize', syncVisualViewport);
|
||||||
|
view?.visualViewport?.removeEventListener('scroll', syncVisualViewport);
|
||||||
|
view?.removeEventListener('orientationchange', syncVisualViewport);
|
||||||
|
|
||||||
|
if (viewportFrame !== undefined) {
|
||||||
|
view?.cancelAnimationFrame(viewportFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
viewportSyncTimers.forEach((timer) => view?.clearTimeout(timer));
|
||||||
|
|
||||||
body.style.overflow = previousOverflow;
|
body.style.overflow = previousOverflow;
|
||||||
body.style.paddingRight = previousPaddingRight;
|
body.style.paddingRight = previousPaddingRight;
|
||||||
|
body.style.position = previousPosition;
|
||||||
|
body.style.top = previousTop;
|
||||||
|
body.style.left = previousLeft;
|
||||||
|
body.style.width = previousWidth;
|
||||||
|
|
||||||
|
if (isIos) {
|
||||||
|
view?.scrollTo(scrollX, scrollY);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
<div class="modal-shell" (click)="backdropClick.emit()">
|
<div
|
||||||
|
#shell
|
||||||
|
class="modal-shell"
|
||||||
|
[class.modal-shell--fullscreen-media]="presentation() === 'fullscreen-media'"
|
||||||
|
(click)="backdropClick.emit()"
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-shell__dialog"
|
class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-shell__dialog"
|
||||||
[ngClass]="dialogClass()"
|
[ngClass]="dialogClass()"
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
.modal-shell {
|
.modal-shell {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
top: var(--modal-viewport-top, 0);
|
||||||
|
left: var(--modal-viewport-left, 0);
|
||||||
|
width: var(--modal-viewport-width, 100vw);
|
||||||
|
height: var(--modal-viewport-height, 100dvh);
|
||||||
z-index: 2000;
|
z-index: 2000;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -109,6 +112,64 @@
|
|||||||
color: #303030;
|
color: #303030;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media {
|
||||||
|
padding: 1.5rem;
|
||||||
|
background: rgba(0, 0, 0, 0.92);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__dialog {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
height: calc(100dvh - 3rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__content {
|
||||||
|
min-height: 0;
|
||||||
|
height: 100%;
|
||||||
|
max-height: none;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
background: #111111;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__header {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 0 auto;
|
||||||
|
z-index: 2;
|
||||||
|
justify-content: flex-start;
|
||||||
|
height: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__title {
|
||||||
|
position: absolute;
|
||||||
|
top: max(1.25rem, env(safe-area-inset-top));
|
||||||
|
left: max(1.25rem, env(safe-area-inset-left));
|
||||||
|
width: auto;
|
||||||
|
max-width: calc(100% - 8rem);
|
||||||
|
overflow: hidden;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 1rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
text-align: left;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
text-shadow: 0 1px 3px #000000;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__header .btn-close {
|
||||||
|
top: max(1rem, env(safe-area-inset-top));
|
||||||
|
right: max(1rem, env(safe-area-inset-right));
|
||||||
|
filter: invert(1) grayscale(1) brightness(2) drop-shadow(0 1px 2px #000000);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__body {
|
||||||
|
min-height: 0;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 576px) {
|
@media (max-width: 576px) {
|
||||||
.modal-shell {
|
.modal-shell {
|
||||||
padding: 0.75rem;
|
padding: 0.75rem;
|
||||||
@@ -128,4 +189,18 @@
|
|||||||
max-height: min(100dvh - 1.5rem, 48rem);
|
max-height: min(100dvh - 1.5rem, 48rem);
|
||||||
border-radius: 1.25rem 1.25rem 0.75rem 0.75rem;
|
border-radius: 1.25rem 1.25rem 0.75rem 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media {
|
||||||
|
align-items: center;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__dialog {
|
||||||
|
height: 100dvh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-shell--fullscreen-media .modal-shell__content {
|
||||||
|
max-height: none;
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
viewChild,
|
viewChild,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
|
|
||||||
import { ModalSize } from '../../../core/services/modal.service';
|
import { ModalPresentation, ModalSize } from '../../../core/services/modal.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-modal-shell',
|
selector: 'app-modal-shell',
|
||||||
@@ -19,10 +19,12 @@ import { ModalSize } from '../../../core/services/modal.service';
|
|||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
})
|
})
|
||||||
export class ModalShellComponent {
|
export class ModalShellComponent {
|
||||||
|
private readonly shell = viewChild.required<ElementRef<HTMLElement>>('shell');
|
||||||
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
|
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
|
||||||
|
|
||||||
readonly title = input<string | undefined>();
|
readonly title = input<string | undefined>();
|
||||||
readonly size = input<ModalSize>('md');
|
readonly size = input<ModalSize>('md');
|
||||||
|
readonly presentation = input<ModalPresentation>('dialog');
|
||||||
readonly showCloseButton = input(true);
|
readonly showCloseButton = input(true);
|
||||||
|
|
||||||
readonly backdropClick = output<void>();
|
readonly backdropClick = output<void>();
|
||||||
@@ -46,6 +48,28 @@ export class ModalShellComponent {
|
|||||||
return this.title() ? this.titleId : null;
|
return this.title() ? this.titleId : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setVisualViewport(viewport: VisualViewport | null, layoutScrollX = 0, layoutScrollY = 0): void {
|
||||||
|
const shell = this.shell().nativeElement;
|
||||||
|
|
||||||
|
if (!viewport) {
|
||||||
|
shell.style.removeProperty('--modal-viewport-top');
|
||||||
|
shell.style.removeProperty('--modal-viewport-left');
|
||||||
|
shell.style.removeProperty('--modal-viewport-width');
|
||||||
|
shell.style.removeProperty('--modal-viewport-height');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageTop/pageLeft are a useful fallback for WebKit versions that update
|
||||||
|
// offsetTop/offsetLeft one frame late after dismissing a native control.
|
||||||
|
const top = Math.max(viewport.offsetTop, viewport.pageTop - layoutScrollY);
|
||||||
|
const left = Math.max(viewport.offsetLeft, viewport.pageLeft - layoutScrollX);
|
||||||
|
|
||||||
|
shell.style.setProperty('--modal-viewport-top', `${top}px`);
|
||||||
|
shell.style.setProperty('--modal-viewport-left', `${left}px`);
|
||||||
|
shell.style.setProperty('--modal-viewport-width', `${viewport.width}px`);
|
||||||
|
shell.style.setProperty('--modal-viewport-height', `${viewport.height}px`);
|
||||||
|
}
|
||||||
|
|
||||||
focusInitialElement(): void {
|
focusInitialElement(): void {
|
||||||
const panel = this.panel().nativeElement;
|
const panel = this.panel().nativeElement;
|
||||||
const focusTarget = panel.querySelector<HTMLElement>(
|
const focusTarget = panel.querySelector<HTMLElement>(
|
||||||
|
|||||||
@@ -31,9 +31,16 @@
|
|||||||
<div
|
<div
|
||||||
class="product-column-with-image__body p-3 d-flex flex-column align-items-center text-center flex-grow-1"
|
class="product-column-with-image__body p-3 d-flex flex-column align-items-center text-center flex-grow-1"
|
||||||
>
|
>
|
||||||
<h3 class="product-column-with-image__title text-uppercase text-black mb-4">{{ title() }}</h3>
|
<h3 class="product-column-with-image__title text-uppercase text-black mb-4">
|
||||||
|
{{ title() }}
|
||||||
|
@if (unavailableMessage(); as message) {
|
||||||
|
<app-tooltip [message]="message" />
|
||||||
|
}
|
||||||
|
</h3>
|
||||||
|
|
||||||
<div class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2">
|
<div
|
||||||
|
class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2"
|
||||||
|
>
|
||||||
<span class="product-column-with-image__price-discounted text-primary">
|
<span class="product-column-with-image__price-discounted text-primary">
|
||||||
{{ formattedDiscountedPrice() }}
|
{{ formattedDiscountedPrice() }}
|
||||||
</span>
|
</span>
|
||||||
@@ -53,7 +60,12 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="product-column-with-image__action mt-auto w-100">
|
<div class="product-column-with-image__action mt-auto w-100">
|
||||||
<app-button variant="primary" class="w-100" (click)="buy.emit()">
|
<app-button
|
||||||
|
variant="primary"
|
||||||
|
class="w-100"
|
||||||
|
[disabled]="!!unavailableMessage()"
|
||||||
|
(click)="onBuy()"
|
||||||
|
>
|
||||||
{{ buttonText() }}
|
{{ buttonText() }}
|
||||||
</app-button>
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ import { NgOptimizedImage } from '@angular/common';
|
|||||||
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||||
|
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
|
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-column-with-image',
|
selector: 'app-product-column-with-image',
|
||||||
imports: [ButtonComponent, NgOptimizedImage],
|
imports: [ButtonComponent, NgOptimizedImage, TooltipComponent],
|
||||||
templateUrl: './product-column-with-image.component.html',
|
templateUrl: './product-column-with-image.component.html',
|
||||||
styleUrl: './product-column-with-image.component.scss',
|
styleUrl: './product-column-with-image.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
@@ -18,9 +19,16 @@ export class ProductColumnWithImageComponent {
|
|||||||
readonly transferPrice = input<number | null>(null);
|
readonly transferPrice = input<number | null>(null);
|
||||||
readonly buttonText = input<string>('Comprar');
|
readonly buttonText = input<string>('Comprar');
|
||||||
readonly imagePriority = input<boolean>(false);
|
readonly imagePriority = input<boolean>(false);
|
||||||
|
readonly unavailableMessage = input<string | null>(null);
|
||||||
|
|
||||||
readonly buy = output<void>();
|
readonly buy = output<void>();
|
||||||
|
|
||||||
|
protected onBuy(): void {
|
||||||
|
if (this.unavailableMessage()) return;
|
||||||
|
|
||||||
|
this.buy.emit();
|
||||||
|
}
|
||||||
|
|
||||||
readonly discountedPrice = computed(() => {
|
readonly discountedPrice = computed(() => {
|
||||||
const original = this.originalPrice();
|
const original = this.originalPrice();
|
||||||
const discount = this.discount();
|
const discount = this.discount();
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
|
[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,6 +26,7 @@
|
|||||||
[description]="item.descripcion ?? ''"
|
[description]="item.descripcion ?? ''"
|
||||||
[price]="price(item)"
|
[price]="price(item)"
|
||||||
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
[maximumAddableQuantity]="item.maximum_addable_quantity ?? null"
|
||||||
|
[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)"
|
||||||
@@ -38,7 +40,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"
|
||||||
[disabled]="loading()"
|
[unavailableMessage]="item.unavailable_message ?? null"
|
||||||
|
[disabled]="loading() || !!item.unavailable_message"
|
||||||
(buy)="emitTicketBuy(item, $event)"
|
(buy)="emitTicketBuy(item, $event)"
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
@@ -47,6 +50,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"
|
||||||
[imagePriority]="loadImages() && index < 4"
|
[imagePriority]="loadImages() && index < 4"
|
||||||
(buy)="emitProductDetailBuy(item)"
|
(buy)="emitProductDetailBuy(item)"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -3,6 +3,9 @@
|
|||||||
<div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1">
|
<div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1">
|
||||||
<h3 class="product-row-card__title text-uppercase mb-1 m-0">
|
<h3 class="product-row-card__title text-uppercase mb-1 m-0">
|
||||||
{{ title() }}
|
{{ title() }}
|
||||||
|
@if (effectiveUnavailableMessage(); as message) {
|
||||||
|
<app-tooltip [message]="message" />
|
||||||
|
}
|
||||||
</h3>
|
</h3>
|
||||||
@if (effectiveDescription()) {
|
@if (effectiveDescription()) {
|
||||||
<p class="product-row-card__description m-0 mt-1">
|
<p class="product-row-card__description m-0 mt-1">
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
|
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||||
import {
|
import {
|
||||||
VariantSelectorComponent,
|
VariantSelectorComponent,
|
||||||
VariantSelectorVariant,
|
VariantSelectorVariant,
|
||||||
@@ -19,12 +20,13 @@ export interface Variant extends VariantSelectorVariant {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
maximum_addable_quantity?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-row-card',
|
selector: 'app-product-row-card',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
|
||||||
templateUrl: './product-row-card.component.html',
|
templateUrl: './product-row-card.component.html',
|
||||||
styleUrl: './product-row-card.component.scss',
|
styleUrl: './product-row-card.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
@@ -35,6 +37,7 @@ export class ProductRowCardComponent {
|
|||||||
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 maximumAddableQuantity = input<number | null>(null);
|
||||||
|
readonly unavailableMessage = input<string | null>(null);
|
||||||
readonly variants = input<Variant[]>([]);
|
readonly variants = input<Variant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -61,6 +64,13 @@ export class ProductRowCardComponent {
|
|||||||
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
);
|
);
|
||||||
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
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()));
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
<article class="ticket-selector">
|
<article class="ticket-selector">
|
||||||
<header class="ticket-selector__header">
|
<header class="ticket-selector__header">
|
||||||
<div>
|
<div>
|
||||||
<h3 class="ticket-selector__title">{{ title() }}</h3>
|
<h3 class="ticket-selector__title">
|
||||||
|
{{ title() }}
|
||||||
|
@if (unavailableMessage(); as message) {
|
||||||
|
<app-tooltip [message]="message" />
|
||||||
|
}
|
||||||
|
</h3>
|
||||||
@if (description()) {
|
@if (description()) {
|
||||||
<p class="ticket-selector__description">{{ description() }}</p>
|
<p class="ticket-selector__description">{{ description() }}</p>
|
||||||
}
|
}
|
||||||
@@ -102,6 +107,17 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (imageUrl(); as image) {
|
@if (imageUrl(); as image) {
|
||||||
<img class="ticket-selector__map" [src]="image" [alt]="'Plano de ubicaciones de ' + title()" />
|
<button
|
||||||
|
type="button"
|
||||||
|
class="ticket-selector__map-button"
|
||||||
|
aria-label="Ampliar plano de ubicaciones"
|
||||||
|
(click)="openImage(image)"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
class="ticket-selector__map"
|
||||||
|
[src]="image"
|
||||||
|
[alt]="'Plano de ubicaciones de ' + title()"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
}
|
}
|
||||||
</article>
|
</article>
|
||||||
|
|||||||
@@ -153,11 +153,27 @@
|
|||||||
margin-top: 0.75rem;
|
margin-top: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__map {
|
&__map-button {
|
||||||
display: block;
|
display: block;
|
||||||
width: min(100%, 720px);
|
width: min(100%, 720px);
|
||||||
max-height: 680px;
|
|
||||||
margin: 3rem auto 0;
|
margin: 3rem auto 0;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
background: transparent;
|
||||||
|
cursor: zoom-in;
|
||||||
|
|
||||||
|
&:focus-visible {
|
||||||
|
outline: 3px solid var(--tenant-primary);
|
||||||
|
outline-offset: 0.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&__map {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
max-height: 680px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,7 +204,7 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
&__map {
|
&__map-button {
|
||||||
margin-top: 2rem;
|
margin-top: 2rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -104,6 +104,10 @@ describe('ProductTicketSelectorComponent', () => {
|
|||||||
};
|
};
|
||||||
catalogService.withoutLoading.mockReturnValue(catalogService);
|
catalogService.withoutLoading.mockReturnValue(catalogService);
|
||||||
cartService.withoutLoading.mockReturnValue(cartService);
|
cartService.withoutLoading.mockReturnValue(cartService);
|
||||||
|
const modalService = {
|
||||||
|
openConfirmDelete: vi.fn().mockReturnValue(of(true)),
|
||||||
|
openImage: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
await TestBed.configureTestingModule({
|
await TestBed.configureTestingModule({
|
||||||
imports: [ProductTicketSelectorComponent],
|
imports: [ProductTicketSelectorComponent],
|
||||||
@@ -112,7 +116,7 @@ describe('ProductTicketSelectorComponent', () => {
|
|||||||
{ provide: CartService, useValue: cartService },
|
{ provide: CartService, useValue: cartService },
|
||||||
{
|
{
|
||||||
provide: ModalService,
|
provide: ModalService,
|
||||||
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
|
useValue: modalService,
|
||||||
},
|
},
|
||||||
{ provide: ToastService, useValue: { danger: toastDanger } },
|
{ provide: ToastService, useValue: { danger: toastDanger } },
|
||||||
],
|
],
|
||||||
@@ -125,7 +129,7 @@ describe('ProductTicketSelectorComponent', () => {
|
|||||||
await fixture.whenStable();
|
await fixture.whenStable();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
return { fixture, getVariantOptions, cartService, toastDanger };
|
return { fixture, getVariantOptions, cartService, toastDanger, modalService };
|
||||||
}
|
}
|
||||||
|
|
||||||
it('loads one map, recalculates the cascade locally and reserves only after the last select', async () => {
|
it('loads one map, recalculates the cascade locally and reserves only after the last select', async () => {
|
||||||
@@ -226,6 +230,25 @@ describe('ProductTicketSelectorComponent', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the zoomable image modal when the seating map is clicked', async () => {
|
||||||
|
const { fixture, modalService } = await createComponent({
|
||||||
|
maps: [mapResponse([variant(401, 'general', 'A', '1', '1')])],
|
||||||
|
});
|
||||||
|
fixture.componentRef.setInput('imageUrl', '/images/plano.png');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector(
|
||||||
|
'button[aria-label="Ampliar plano de ubicaciones"]',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
expect(modalService.openImage).toHaveBeenCalledWith({
|
||||||
|
title: 'Entrada',
|
||||||
|
src: '/images/plano.png',
|
||||||
|
alt: 'Plano de ubicaciones de Entrada',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('clears only the seat after a stock conflict when the row still has alternatives', async () => {
|
it('clears only the seat after a stock conflict when the row still has alternatives', async () => {
|
||||||
const failed = variant(401, 'general', 'A', '1', '1');
|
const failed = variant(401, 'general', 'A', '1', '1');
|
||||||
const alternative = variant(402, 'general', 'A', '1', '2');
|
const alternative = variant(402, 'general', 'A', '1', '2');
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { ModalService } from '../../../core/services/modal.service';
|
|||||||
import { ToastService } from '../../../core/services/toast.service';
|
import { ToastService } from '../../../core/services/toast.service';
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||||
|
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||||
|
|
||||||
type TicketSelectionStatus =
|
type TicketSelectionStatus =
|
||||||
| 'selecting'
|
| 'selecting'
|
||||||
@@ -56,7 +57,7 @@ interface TicketSelectionRow {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-ticket-selector',
|
selector: 'app-product-ticket-selector',
|
||||||
imports: [ButtonComponent, IconButtonComponent],
|
imports: [ButtonComponent, IconButtonComponent, TooltipComponent],
|
||||||
templateUrl: './product-ticket-selector.component.html',
|
templateUrl: './product-ticket-selector.component.html',
|
||||||
styleUrl: './product-ticket-selector.component.scss',
|
styleUrl: './product-ticket-selector.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
@@ -80,6 +81,7 @@ export class ProductTicketSelectorComponent {
|
|||||||
readonly price = input<number>(0);
|
readonly price = input<number>(0);
|
||||||
readonly imageUrl = input<string | null>(null);
|
readonly imageUrl = input<string | null>(null);
|
||||||
readonly disabled = input(false);
|
readonly disabled = input(false);
|
||||||
|
readonly unavailableMessage = input<string | null>(null);
|
||||||
|
|
||||||
readonly buy = output<number[]>();
|
readonly buy = output<number[]>();
|
||||||
|
|
||||||
@@ -152,6 +154,14 @@ export class ProductTicketSelectorComponent {
|
|||||||
if (this.hasSelection() && variantIds.length > 0) this.buy.emit(variantIds);
|
if (this.hasSelection() && variantIds.length > 0) this.buy.emit(variantIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openImage(src: string): void {
|
||||||
|
this.modalService.openImage({
|
||||||
|
title: this.title(),
|
||||||
|
src,
|
||||||
|
alt: `Plano de ubicaciones de ${this.title()}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected addRow(): void {
|
protected addRow(): void {
|
||||||
if (!this.canAddRow()) return;
|
if (!this.canAddRow()) return;
|
||||||
const row = this.createRow(this.nextRowId++);
|
const row = this.createRow(this.nextRowId++);
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
<article class="product-vertical-with-cart-card">
|
<article class="product-vertical-with-cart-card">
|
||||||
<div class="product-vertical-with-cart-card__content">
|
<div class="product-vertical-with-cart-card__content">
|
||||||
<h3 class="product-vertical-with-cart-card__title">{{ title() }}</h3>
|
<h3 class="product-vertical-with-cart-card__title">
|
||||||
|
{{ title() }}
|
||||||
|
@if (effectiveUnavailableMessage(); as message) {
|
||||||
|
<app-tooltip [message]="message" />
|
||||||
|
}
|
||||||
|
</h3>
|
||||||
|
|
||||||
@if (effectiveDescription()) {
|
@if (effectiveDescription()) {
|
||||||
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
|
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding: 30px 20px;
|
padding: 30px 20px;
|
||||||
overflow: hidden;
|
overflow: visible;
|
||||||
background-color: #ffffff;
|
background-color: #ffffff;
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 7px;
|
border-radius: 7px;
|
||||||
|
|||||||
@@ -56,6 +56,23 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
|||||||
).toBeNull();
|
).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the backend availability message with the reusable tooltip', async () => {
|
||||||
|
const fixture = await createComponent();
|
||||||
|
fixture.componentRef.setInput('maximumAddableQuantity', 0);
|
||||||
|
fixture.componentRef.setInput(
|
||||||
|
'unavailableMessage',
|
||||||
|
'Alcanzaste el cupo máximo permitido para este producto.',
|
||||||
|
);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');
|
||||||
|
|
||||||
|
expect(tooltip?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
|
||||||
|
expect(tooltip?.textContent).toContain(
|
||||||
|
'Alcanzaste el cupo máximo permitido para este producto.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('updates the quantity with the reusable quantity selector', async () => {
|
it('updates the quantity with the reusable quantity selector', async () => {
|
||||||
const fixture = await createComponent();
|
const fixture = await createComponent();
|
||||||
const buttons = fixture.nativeElement.querySelectorAll(
|
const buttons = fixture.nativeElement.querySelectorAll(
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
|
|
||||||
import { ButtonComponent } from '../button/button.component';
|
import { ButtonComponent } from '../button/button.component';
|
||||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||||
|
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||||
import {
|
import {
|
||||||
VariantSelectorComponent,
|
VariantSelectorComponent,
|
||||||
VariantSelectorVariant,
|
VariantSelectorVariant,
|
||||||
@@ -19,11 +20,12 @@ export interface VerticalCartVariant extends VariantSelectorVariant {
|
|||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio?: string | number;
|
precio?: string | number;
|
||||||
maximum_addable_quantity?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-vertical-with-cart-card',
|
selector: 'app-product-vertical-with-cart-card',
|
||||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
|
||||||
templateUrl: './product-vertical-with-cart-card.component.html',
|
templateUrl: './product-vertical-with-cart-card.component.html',
|
||||||
styleUrl: './product-vertical-with-cart-card.component.scss',
|
styleUrl: './product-vertical-with-cart-card.component.scss',
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
@@ -33,6 +35,7 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
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 maximumAddableQuantity = input<number | null>(null);
|
||||||
|
readonly unavailableMessage = input<string | null>(null);
|
||||||
readonly variants = input<VerticalCartVariant[]>([]);
|
readonly variants = input<VerticalCartVariant[]>([]);
|
||||||
readonly saving = input(false);
|
readonly saving = input(false);
|
||||||
|
|
||||||
@@ -59,6 +62,13 @@ export class ProductVerticalWithCartCardComponent {
|
|||||||
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
() => this.selectedVariantData()?.maximum_addable_quantity ?? this.maximumAddableQuantity(),
|
||||||
);
|
);
|
||||||
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
protected readonly unavailable = computed(() => this.effectiveMaximum() === 0);
|
||||||
|
protected readonly effectiveUnavailableMessage = computed(() => {
|
||||||
|
const selectedVariant = this.selectedVariantData();
|
||||||
|
|
||||||
|
return selectedVariant
|
||||||
|
? (selectedVariant.unavailable_message ?? null)
|
||||||
|
: this.unavailableMessage();
|
||||||
|
});
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
|
|||||||
@@ -1,25 +1,27 @@
|
|||||||
<div class="stepper-container">
|
<div class="stepper-container">
|
||||||
|
|
||||||
<!-- Horizontal indicator bar -->
|
<!-- Horizontal indicator bar -->
|
||||||
<div class="stepper-header">
|
<div class="stepper-header" [class.is-disabled]="disabled()" [attr.aria-disabled]="disabled()">
|
||||||
@for (step of steps(); track step; let i = $index; let last = $last) {
|
@for (step of steps(); track step; let i = $index; let last = $last) {
|
||||||
<div
|
<div
|
||||||
class="stepper-header__item"
|
class="stepper-header__item"
|
||||||
[ngClass]="{
|
[ngClass]="{
|
||||||
'is-active': currentStepIndex() === i,
|
'is-active': currentStepIndex() === i,
|
||||||
'is-completed': currentStepIndex() > i
|
'is-completed': currentStepIndex() > i,
|
||||||
}"
|
}"
|
||||||
>
|
>
|
||||||
<!-- Connecting line before (except first) -->
|
<!-- Connecting line before (except first) -->
|
||||||
@if (i > 0) {
|
@if (i > 0) {
|
||||||
<div class="stepper-header__line" [ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"></div>
|
<div
|
||||||
|
class="stepper-header__line"
|
||||||
|
[ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"
|
||||||
|
></div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<!-- Circle indicator -->
|
<!-- Circle indicator -->
|
||||||
<div
|
<div
|
||||||
class="stepper-header__circle"
|
class="stepper-header__circle"
|
||||||
[attr.aria-label]="step.label()"
|
[attr.aria-label]="step.label()"
|
||||||
[class.is-clickable]="currentStepIndex() > i"
|
[class.is-clickable]="!disabled() && currentStepIndex() > i"
|
||||||
(click)="goToStep(i)"
|
(click)="goToStep(i)"
|
||||||
></div>
|
></div>
|
||||||
|
|
||||||
@@ -33,5 +35,4 @@
|
|||||||
<div class="stepper-body">
|
<div class="stepper-body">
|
||||||
<ng-content></ng-content>
|
<ng-content></ng-content>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -13,6 +13,14 @@
|
|||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
position: relative;
|
position: relative;
|
||||||
|
|
||||||
|
&.is-disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
|
||||||
|
.stepper-header__circle {
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
&__item {
|
&__item {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { StepComponent } from './step.component';
|
|||||||
@Component({
|
@Component({
|
||||||
imports: [StepperComponent, StepComponent],
|
imports: [StepperComponent, StepComponent],
|
||||||
template: `
|
template: `
|
||||||
<app-stepper #stepper>
|
<app-stepper #stepper [disabled]="stepperDisabled()">
|
||||||
<app-step label="Step 1" [isValid]="step1Valid()">
|
<app-step label="Step 1" [isValid]="step1Valid()">
|
||||||
<div id="content-1">Content 1</div>
|
<div id="content-1">Content 1</div>
|
||||||
</app-step>
|
</app-step>
|
||||||
@@ -20,6 +20,7 @@ class TestHostComponent {
|
|||||||
@ViewChild('stepper') stepper!: StepperComponent;
|
@ViewChild('stepper') stepper!: StepperComponent;
|
||||||
step1Valid = signal(true);
|
step1Valid = signal(true);
|
||||||
step2Valid = signal(true);
|
step2Valid = signal(true);
|
||||||
|
stepperDisabled = signal(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('StepperComponent & StepComponent', () => {
|
describe('StepperComponent & StepComponent', () => {
|
||||||
@@ -137,4 +138,28 @@ describe('StepperComponent & StepComponent', () => {
|
|||||||
expect(component.stepper.currentStepIndex()).toBe(0);
|
expect(component.stepper.currentStepIndex()).toBe(0);
|
||||||
expect(fixture.nativeElement.querySelector('#content-1')).not.toBeNull();
|
expect(fixture.nativeElement.querySelector('#content-1')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('blocks all navigation and shows visual feedback while disabled', async () => {
|
||||||
|
const { fixture, component } = await setup();
|
||||||
|
component.stepperDisabled.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
component.stepper.next();
|
||||||
|
expect(component.stepper.currentStepIndex()).toBe(0);
|
||||||
|
|
||||||
|
component.stepperDisabled.set(false);
|
||||||
|
fixture.detectChanges();
|
||||||
|
component.stepper.next();
|
||||||
|
expect(component.stepper.currentStepIndex()).toBe(1);
|
||||||
|
|
||||||
|
component.stepperDisabled.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
component.stepper.previous();
|
||||||
|
component.stepper.goToStep(0);
|
||||||
|
|
||||||
|
expect(component.stepper.currentStepIndex()).toBe(1);
|
||||||
|
const header = fixture.nativeElement.querySelector('.stepper-header');
|
||||||
|
expect(header.classList.contains('is-disabled')).toBe(true);
|
||||||
|
expect(header.getAttribute('aria-disabled')).toBe('true');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,9 +18,12 @@ import { NgClass } from '@angular/common';
|
|||||||
export class StepperComponent {
|
export class StepperComponent {
|
||||||
readonly steps = contentChildren(StepComponent);
|
readonly steps = contentChildren(StepComponent);
|
||||||
readonly initialStepIndex = input(0);
|
readonly initialStepIndex = input(0);
|
||||||
|
readonly disabled = input(false);
|
||||||
readonly currentStepIndex = linkedSignal(() => this.initialStepIndex());
|
readonly currentStepIndex = linkedSignal(() => this.initialStepIndex());
|
||||||
|
|
||||||
next() {
|
next() {
|
||||||
|
if (this.disabled()) return;
|
||||||
|
|
||||||
const currentSteps = this.steps();
|
const currentSteps = this.steps();
|
||||||
const currentIndex = this.currentStepIndex();
|
const currentIndex = this.currentStepIndex();
|
||||||
if (currentIndex < currentSteps.length - 1) {
|
if (currentIndex < currentSteps.length - 1) {
|
||||||
@@ -32,6 +35,8 @@ export class StepperComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
previous() {
|
previous() {
|
||||||
|
if (this.disabled()) return;
|
||||||
|
|
||||||
const currentIndex = this.currentStepIndex();
|
const currentIndex = this.currentStepIndex();
|
||||||
if (currentIndex > 0) {
|
if (currentIndex > 0) {
|
||||||
this.currentStepIndex.set(currentIndex - 1);
|
this.currentStepIndex.set(currentIndex - 1);
|
||||||
@@ -39,6 +44,8 @@ export class StepperComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
goToStep(index: number) {
|
goToStep(index: number) {
|
||||||
|
if (this.disabled()) return;
|
||||||
|
|
||||||
const targetIndex = index;
|
const targetIndex = index;
|
||||||
// Only allow navigating to completed steps or the current one
|
// Only allow navigating to completed steps or the current one
|
||||||
if (targetIndex < this.currentStepIndex()) {
|
if (targetIndex < this.currentStepIndex()) {
|
||||||
|
|||||||
11
src/app/shared/components/tooltip/tooltip.component.html
Normal file
11
src/app/shared/components/tooltip/tooltip.component.html
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="tooltip-trigger"
|
||||||
|
[attr.aria-describedby]="tooltipId"
|
||||||
|
[attr.aria-label]="message()"
|
||||||
|
>
|
||||||
|
<i class="fa-solid fa-circle-info" aria-hidden="true"></i>
|
||||||
|
<span class="tooltip-message" [id]="tooltipId" role="tooltip">
|
||||||
|
{{ message() }}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
62
src/app/shared/components/tooltip/tooltip.component.scss
Normal file
62
src/app/shared/components/tooltip/tooltip.component.scss
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
:host {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
margin-left: 0.25rem;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tooltip-trigger {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--tenant-primary, var(--color-primary, #0d6efd));
|
||||||
|
font-size: 1em;
|
||||||
|
line-height: inherit;
|
||||||
|
|
||||||
|
&:focus-visible {
|
||||||
|
border-radius: 50%;
|
||||||
|
outline: 2px solid currentColor;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover .tooltip-message,
|
||||||
|
&:focus-visible .tooltip-message {
|
||||||
|
visibility: visible;
|
||||||
|
opacity: 1;
|
||||||
|
transform: translate(-50%, -0.25rem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.tooltip-message {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 1100;
|
||||||
|
bottom: calc(100% + 0.625rem);
|
||||||
|
left: 50%;
|
||||||
|
width: max-content;
|
||||||
|
max-width: min(16rem, 75vw);
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
border: 1px solid var(--tenant-primary, var(--color-primary, #0d6efd));
|
||||||
|
background: #fff;
|
||||||
|
color: #212529;
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.35;
|
||||||
|
text-align: center;
|
||||||
|
text-transform: none;
|
||||||
|
letter-spacing: normal;
|
||||||
|
white-space: normal;
|
||||||
|
visibility: hidden;
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translate(-50%, 0);
|
||||||
|
transition:
|
||||||
|
opacity 0.15s ease,
|
||||||
|
transform 0.15s ease,
|
||||||
|
visibility 0.15s ease;
|
||||||
|
}
|
||||||
32
src/app/shared/components/tooltip/tooltip.component.spec.ts
Normal file
32
src/app/shared/components/tooltip/tooltip.component.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
|
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { TooltipComponent } from './tooltip.component';
|
||||||
|
|
||||||
|
describe('TooltipComponent', () => {
|
||||||
|
beforeAll(() => {
|
||||||
|
try {
|
||||||
|
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||||
|
} catch {
|
||||||
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => TestBed.resetTestingModule());
|
||||||
|
|
||||||
|
it('renders the reusable danger information tooltip', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [TooltipComponent] }).compileComponents();
|
||||||
|
const fixture = TestBed.createComponent(TooltipComponent);
|
||||||
|
fixture.componentRef.setInput('message', 'Este producto no tiene stock disponible.');
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const trigger = element.querySelector('.tooltip-trigger');
|
||||||
|
const message = element.querySelector('.tooltip-message');
|
||||||
|
|
||||||
|
expect(trigger?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
|
||||||
|
expect(message?.textContent?.trim()).toBe('Este producto no tiene stock disponible.');
|
||||||
|
expect(trigger?.getAttribute('aria-describedby')).toBe(message?.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
14
src/app/shared/components/tooltip/tooltip.component.ts
Normal file
14
src/app/shared/components/tooltip/tooltip.component.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
||||||
|
|
||||||
|
let nextTooltipId = 0;
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-tooltip',
|
||||||
|
templateUrl: './tooltip.component.html',
|
||||||
|
styleUrl: './tooltip.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
})
|
||||||
|
export class TooltipComponent {
|
||||||
|
readonly message = input.required<string>();
|
||||||
|
protected readonly tooltipId = `app-tooltip-${nextTooltipId++}`;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
export const environment = {
|
export const environment = {
|
||||||
production: false,
|
production: true,
|
||||||
nombre:"Homologación - activo",
|
nombre:"Homologación - activo",
|
||||||
url:"https://backend.qa.shopit.com.ar/api/",
|
url:"https://backend.qa.shopit.com.ar/api/",
|
||||||
urlDescarga:"url/"
|
urlDescarga:"url/"
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user