18 Commits

Author SHA1 Message Date
eb3a084d18 Merge branch 'fix/cart-expiration-notification' of https://gitea.quo.ar/tbianchini/shopit-front into fix/cart-expiration-notification 2026-08-26 16:19:11 -03:00
e4f9d38e82 fix(checkout): refresh expired carts 2026-08-26 16:19:08 -03:00
b0e2efbdd1 fix(checkout): show backend start errors 2026-08-26 16:18:48 -03:00
1ad7bccf16 fix(checkout): refresh expired carts 2026-08-26 16:16:46 -03:00
a1d6585b54 fix(checkout): show backend start errors 2026-08-26 16:16:32 -03:00
38d03588b1 Merge branch 'fix/cart-expiration-notification' of https://gitea.quo.ar/tbianchini/shopit-front into fix/cart-expiration-notification 2026-08-26 10:25:23 -03:00
8e987d0ce6 fix(purchase-status): clear cart on approved purchase 2026-08-26 10:25:16 -03:00
e171b9a233 refactor(checkout): use purchase id route segment 2026-08-26 10:25:16 -03:00
643d43adea fix(checkout): handle expired purchase exits 2026-08-26 10:25:16 -03:00
d89d01b511 fix(checkout): refresh expired carts 2026-08-26 10:25:16 -03:00
eeb245209b fix(checkout): show backend start errors 2026-08-26 10:25:16 -03:00
9d3754c2d8 fix(cart): refresh state after expiration 2026-08-26 10:25:16 -03:00
6f4aa3b1bd fix(purchase-status): clear cart on approved purchase 2026-08-26 10:02:26 -03:00
2b342ec235 refactor(checkout): use purchase id route segment 2026-08-25 17:06:07 -03:00
d06b146104 fix(checkout): handle expired purchase exits 2026-08-25 17:05:59 -03:00
f4e0a9e028 fix(checkout): refresh expired carts 2026-08-25 16:47:17 -03:00
8c2b738806 fix(checkout): show backend start errors 2026-08-25 16:46:12 -03:00
1362d0c163 fix(cart): refresh state after expiration 2026-08-25 16:33:44 -03:00
74 changed files with 170 additions and 2326 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,7 +12,7 @@ import {
UrlSerializer, UrlSerializer,
} from '@angular/router'; } from '@angular/router';
import { BehaviorSubject, of, throwError } from 'rxjs'; import { BehaviorSubject, of } from 'rxjs';
import { Tenant } from '../../services/tenant.interface'; import { Tenant } from '../../services/tenant.interface';
import { TenantService } from '../../services/tenant.service'; import { TenantService } from '../../services/tenant.service';
@@ -24,7 +24,6 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
import { StoreLayoutComponent } from './store-layout.component'; import { StoreLayoutComponent } from './store-layout.component';
import { StoreHeaderComponent } from './store-header/store-header.component'; import { StoreHeaderComponent } from './store-header/store-header.component';
import { CheckoutService } from '../../services/checkout.service'; import { CheckoutService } from '../../services/checkout.service';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
import { TenantUrlSerializer } from '../../services/tenant-url.serializer'; import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
const tenant: Tenant = { const tenant: Tenant = {
@@ -151,7 +150,6 @@ describe('StoreLayoutComponent', () => {
let tenantState = signal<Tenant | null>(tenant); let tenantState = signal<Tenant | null>(tenant);
let cartState = signal<Cart | null>(null); let cartState = signal<Cart | null>(null);
let authUserState = signal<AuthUser | null>(null); let authUserState = signal<AuthUser | null>(null);
let checkoutRemainingSecondsState = signal<number | null>(null);
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> }; let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
let queryParamMapState: BehaviorSubject<ParamMap>; let queryParamMapState: BehaviorSubject<ParamMap>;
@@ -159,7 +157,6 @@ describe('StoreLayoutComponent', () => {
tenantState = signal<Tenant | null>(tenant); tenantState = signal<Tenant | null>(tenant);
cartState = signal<Cart | null>(null); cartState = signal<Cart | null>(null);
authUserState = signal<AuthUser | null>(null); authUserState = signal<AuthUser | null>(null);
checkoutRemainingSecondsState = signal<number | null>(null);
queryParamMapState = new BehaviorSubject(convertToParamMap({})); queryParamMapState = new BehaviorSubject(convertToParamMap({}));
const isAuthenticatedState = signal(false); const isAuthenticatedState = signal(false);
checkoutServiceStub = { checkoutServiceStub = {
@@ -211,19 +208,13 @@ describe('StoreLayoutComponent', () => {
useValue: { useValue: {
user: authUserState, user: authUserState,
isAuthenticated: isAuthenticatedState, isAuthenticated: isAuthenticatedState,
logout: vi.fn().mockReturnValue(of({ message: 'Sesión cerrada correctamente.' })), logout: vi.fn().mockReturnValue(of(void 0)),
}, },
}, },
{ {
provide: CheckoutService, provide: CheckoutService,
useValue: checkoutServiceStub, useValue: checkoutServiceStub,
}, },
{
provide: CheckoutCountdownService,
useValue: {
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
},
},
], ],
}).compileComponents(); }).compileComponents();
}); });
@@ -280,22 +271,6 @@ describe('StoreLayoutComponent', () => {
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull(); expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
}); });
it('shows the synchronized countdown in the header whenever one is active', () => {
checkoutRemainingSecondsState.set(587);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
'Tiempo restante de compra:',
);
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
'09:47',
);
});
it('hides the configured header elements when the tenant disables them', () => { it('hides the configured header elements when the tenant disables them', () => {
tenantState.set({ tenantState.set({
...tenant, ...tenant,
@@ -574,24 +549,6 @@ describe('StoreLayoutComponent', () => {
expect(authService.logout).toHaveBeenCalled(); expect(authService.logout).toHaveBeenCalled();
expect(cartService.clearCart).toHaveBeenCalled(); expect(cartService.clearCart).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']); expect(router.navigate).toHaveBeenCalledWith(['/']);
expect(TestBed.inject(ToastService).info).toHaveBeenCalledWith(
'Sesión cerrada correctamente.',
);
});
it('shows a danger toast when logout fails', async () => {
const authService = TestBed.inject(AuthService);
const message = 'La sesión no pudo cerrarse en el servidor.';
(authService.logout as any).mockReturnValue(
throwError(() => ({ error: { message } })),
);
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
await (fixture.componentInstance as any).onLogoutClick();
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
}); });
it('provides account actions from the footer', () => { it('provides account actions from the footer', () => {

View File

@@ -24,7 +24,6 @@ import {
} from '../../services/checkout.service'; } from '../../services/checkout.service';
import { ToastService } from '../../services/toast.service'; import { ToastService } from '../../services/toast.service';
import { Category } from '../../services/tenant.interface'; import { Category } from '../../services/tenant.interface';
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
@Component({ @Component({
selector: 'app-store-layout', selector: 'app-store-layout',
@@ -43,7 +42,6 @@ export class StoreLayoutComponent implements OnInit {
private readonly cartService = inject(CartService); private readonly cartService = inject(CartService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
@@ -51,7 +49,6 @@ export class StoreLayoutComponent implements OnInit {
protected readonly isCartOpen = signal(false); protected readonly isCartOpen = signal(false);
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url)); protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
protected readonly isCreatingPurchase = signal(false); protected readonly isCreatingPurchase = signal(false);
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true); protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null); protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
@@ -236,39 +233,23 @@ export class StoreLayoutComponent implements OnInit {
const navigationSucceeded = await this.router.navigate(['/']); const navigationSucceeded = await this.router.navigate(['/']);
if (!navigationSucceeded) { if (!navigationSucceeded) {
this.toastService.danger('No se pudo cerrar la sesión. Intentá nuevamente.');
return; return;
} }
} }
this.authService.logout().subscribe({ this.authService.logout().subscribe({
next: ({ message }) => { next: () => {
this.cartService.clearCart(); this.cartService.clearCart();
this.isCartOpen.set(false); this.isCartOpen.set(false);
this.toastService.info(message || 'Sesión cerrada correctamente.');
if (!isLeavingCheckout) { if (!isLeavingCheckout) {
void this.router.navigate(['/']); void this.router.navigate(['/']);
} }
}, },
error: (error: unknown) => { error: (err) => console.error('Error logging out', err),
this.toastService.danger(this.resolveLogoutErrorMessage(error));
console.error('Error logging out', error);
},
}); });
} }
private resolveLogoutErrorMessage(error: unknown): string {
const payload =
typeof error === 'object' && error !== null && 'error' in error
? (error as { error?: { message?: unknown } }).error
: undefined;
return typeof payload?.message === 'string' && payload.message.trim()
? payload.message
: 'No se pudo cerrar la sesión. Intentá nuevamente.';
}
protected async onCheckoutClick(): Promise<void> { protected async onCheckoutClick(): Promise<void> {
if (this.isCreatingPurchase()) { if (this.isCreatingPurchase()) {
return; return;
@@ -306,7 +287,7 @@ export class StoreLayoutComponent implements OnInit {
this.toastService.danger(message); this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) { if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
} }

View File

@@ -33,10 +33,6 @@ export interface LoginResponse {
user: AuthUser; user: AuthUser;
} }
export interface LogoutResponse {
message: string;
}
export interface RegisterResponse { export interface RegisterResponse {
message: string; message: string;
data: AuthUser; data: AuthUser;

View File

@@ -10,7 +10,6 @@ import {
AuthUser, AuthUser,
LoginPayload, LoginPayload,
LoginResponse, LoginResponse,
LogoutResponse,
RegisterPayload, RegisterPayload,
RegisterResponse, RegisterResponse,
ResetPasswordPayload, ResetPasswordPayload,
@@ -156,14 +155,14 @@ export class AuthService extends BaseApiService {
.pipe(tap((user) => this.userState.set(user))); .pipe(tap((user) => this.userState.set(user)));
} }
logout(): Observable<LogoutResponse> { logout(): Observable<void> {
if (!this.tokenState()) { if (!this.tokenState()) {
this.clearSession(); this.clearSession();
return of({ message: 'Sesión cerrada correctamente.' }); return of(void 0);
} }
return this.http return this.http
.post<LogoutResponse>(`${environment.url}logout`, {}) .post<void>(`${environment.url}logout`, {})
.pipe(tap(() => this.clearSession())); .pipe(tap(() => this.clearSession()));
} }

View File

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

View File

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

View File

@@ -72,7 +72,7 @@ export interface CatalogItemVariant {
maximum_use_date?: string | null; maximum_use_date?: string | null;
effective_minimum_use_date?: string | null; effective_minimum_use_date?: string | null;
effective_maximum_use_date?: string | null; effective_maximum_use_date?: string | null;
values: Record<string, CatalogVariantValue>; values: Record<string, string | string[]>;
} }
export interface SelectedCatalogItemVariant extends CatalogItemVariant { export interface SelectedCatalogItemVariant extends CatalogItemVariant {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,7 +7,6 @@ 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';
@@ -259,36 +258,6 @@ 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({

View File

@@ -2,19 +2,16 @@ 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' | 'swipe'; export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced';
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;
@@ -65,25 +62,6 @@ 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>;
@@ -217,33 +195,6 @@ 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;

View File

@@ -113,7 +113,6 @@ export interface Tenant {
dominio: string; dominio: string;
base_path?: string; base_path?: string;
site_title?: string | null; site_title?: string | null;
asset_url?: string | null;
address?: string | null; address?: string | null;
phone?: string | null; phone?: string | null;
favicon?: string | null; favicon?: string | null;

View File

@@ -15,7 +15,6 @@ const tenant: Tenant = {
codigo: 'test', codigo: 'test',
nombre: 'Test Tenant', nombre: 'Test Tenant',
dominio: 'localhost', dominio: 'localhost',
asset_url: 'https://s3.example.com/assets',
primary_color: '#6376F3', primary_color: '#6376F3',
secondary_color: '#A0A0A0', secondary_color: '#A0A0A0',
danger_color: '#FF8888', danger_color: '#FF8888',
@@ -45,7 +44,6 @@ const tenantResponse: TenantBootstrapResponse = {
describe('TenantService', () => { describe('TenantService', () => {
beforeEach(() => { beforeEach(() => {
document.head.querySelectorAll('link[rel="preconnect"]').forEach((link) => link.remove());
try { try {
window.history.replaceState({}, '', 'http://localhost:4200/'); window.history.replaceState({}, '', 'http://localhost:4200/');
} catch (e) { } catch (e) {
@@ -74,9 +72,6 @@ describe('TenantService', () => {
expect(service.status()).toBe('ready'); expect(service.status()).toBe('ready');
expect(service.tenant()).toEqual(tenant); expect(service.tenant()).toEqual(tenant);
expect(service.getTenant()).toEqual(tenant); expect(service.getTenant()).toEqual(tenant);
expect(
document.head.querySelector('link[rel="preconnect"][href="https://s3.example.com/"]'),
).not.toBeNull();
httpController.verify(); httpController.verify();
}); });

View File

@@ -1,4 +1,4 @@
import { DOCUMENT, isPlatformBrowser, isPlatformServer } from '@angular/common'; import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { import {
inject, inject,
@@ -26,7 +26,6 @@ import {
providedIn: 'root', providedIn: 'root',
}) })
export class TenantService extends BaseApiService { export class TenantService extends BaseApiService {
private readonly document = inject(DOCUMENT);
private readonly platformId = inject(PLATFORM_ID); private readonly platformId = inject(PLATFORM_ID);
private readonly request = inject(REQUEST, { optional: true }); private readonly request = inject(REQUEST, { optional: true });
private readonly responseInit = inject(RESPONSE_INIT, { optional: true }); private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
@@ -183,40 +182,10 @@ export class TenantService extends BaseApiService {
} }
private setReady(tenant: Tenant): void { private setReady(tenant: Tenant): void {
this.ensureAssetPreconnect(tenant.asset_url);
this.tenantState.set(tenant); this.tenantState.set(tenant);
this.statusState.set('ready'); this.statusState.set('ready');
} }
private ensureAssetPreconnect(assetUrl: string | null | undefined): void {
if (!assetUrl) {
return;
}
let origin: string;
try {
const url = new URL(assetUrl);
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return;
}
origin = url.origin;
} catch {
return;
}
const existingPreconnects =
this.document.head.querySelectorAll<HTMLLinkElement>('link[rel="preconnect"]');
if ([...existingPreconnects].some((link) => link.href === `${origin}/`)) {
return;
}
const link = this.document.createElement('link');
link.rel = 'preconnect';
link.href = origin;
this.document.head.append(link);
}
private setNotFound(): void { private setNotFound(): void {
this.tenantState.set(null); this.tenantState.set(null);
this.statusState.set('not-found'); this.statusState.set('not-found');

View File

@@ -1,4 +1,3 @@
import { DOCUMENT } from '@angular/common';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { vi } from 'vitest'; import { vi } from 'vitest';
import { ToastService } from './toast.service'; import { ToastService } from './toast.service';
@@ -7,16 +6,14 @@ describe('ToastService', () => {
let service: ToastService; let service: ToastService;
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ToastService] providers: [ToastService]
}); });
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
service = TestBed.inject(ToastService); service = TestBed.inject(ToastService);
vi.useFakeTimers();
}); });
afterEach(() => { afterEach(() => {
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
vi.useRealTimers(); vi.useRealTimers();
}); });
@@ -101,23 +98,4 @@ describe('ToastService', () => {
expect(service.toasts().length).toBe(1); expect(service.toasts().length).toBe(1);
}); });
it('should restore a toast queued for after a full page reload', () => {
service.showAfterReload('Sesión iniciada correctamente.', 'success', 0);
TestBed.resetTestingModule();
TestBed.configureTestingModule({ providers: [ToastService] });
service = TestBed.inject(ToastService);
expect(service.toasts()).toEqual([
expect.objectContaining({
message: 'Sesión iniciada correctamente.',
type: 'success',
duration: 0,
}),
]);
expect(
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.getItem('shopit.pending-toast'),
).toBeNull();
});
}); });

View File

@@ -1,7 +1,4 @@
import { DOCUMENT, isPlatformBrowser } from '@angular/common'; import { Injectable, signal } from '@angular/core';
import { inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
const PENDING_TOAST_STORAGE_KEY = 'shopit.pending-toast';
export interface Toast { export interface Toast {
id: string; id: string;
@@ -14,15 +11,9 @@ export interface Toast {
providedIn: 'root' providedIn: 'root'
}) })
export class ToastService { export class ToastService {
private readonly document = inject(DOCUMENT);
private readonly platformId = inject(PLATFORM_ID);
private readonly toastsSignal = signal<Toast[]>([]); private readonly toastsSignal = signal<Toast[]>([]);
readonly toasts = this.toastsSignal.asReadonly(); readonly toasts = this.toastsSignal.asReadonly();
constructor() {
this.restorePendingToast();
}
show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string { show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string {
const id = Math.random().toString(36).substring(2, 9); const id = Math.random().toString(36).substring(2, 9);
const newToast: Toast = { id, message, type, duration }; const newToast: Toast = { id, message, type, duration };
@@ -50,50 +41,7 @@ export class ToastService {
return this.show(message, 'success', duration); return this.show(message, 'success', duration);
} }
showAfterReload(
message: string,
type: Toast['type'] = 'info',
duration = 3000,
): void {
if (!isPlatformBrowser(this.platformId)) {
return;
}
this.document.defaultView?.sessionStorage.setItem(
PENDING_TOAST_STORAGE_KEY,
JSON.stringify({ message, type, duration }),
);
}
dismiss(id: string): void { dismiss(id: string): void {
this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id)); this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id));
} }
private restorePendingToast(): void {
if (!isPlatformBrowser(this.platformId)) {
return;
}
const storage = this.document.defaultView?.sessionStorage;
const pendingToast = storage?.getItem(PENDING_TOAST_STORAGE_KEY);
if (!pendingToast) {
return;
}
storage?.removeItem(PENDING_TOAST_STORAGE_KEY);
try {
const parsed = JSON.parse(pendingToast) as Partial<Toast>;
if (
typeof parsed.message === 'string' &&
(parsed.type === 'success' || parsed.type === 'danger' || parsed.type === 'info')
) {
this.show(parsed.message, parsed.type, parsed.duration);
}
} catch {
// Ignore malformed session data left by an older or interrupted client.
}
}
} }

View File

@@ -83,9 +83,6 @@
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 }}

View File

@@ -51,7 +51,6 @@ 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)),
}; };
} }
@@ -282,9 +281,6 @@ 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.',
@@ -294,8 +290,6 @@ 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',
@@ -308,11 +302,6 @@ 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',
); );

View File

@@ -493,14 +493,6 @@ 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}`;

View File

@@ -1,10 +1,7 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it } from 'vitest'; import { beforeEach, describe, expect, it } from 'vitest';
import { import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
CatalogItemVariant,
ProductAttribute,
} from '../../../../core/services/catalog/catalog.interface';
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component'; import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
describe('ProductAttributeSelectorComponent', () => { describe('ProductAttributeSelectorComponent', () => {
@@ -27,63 +24,6 @@ describe('ProductAttributeSelectorComponent', () => {
}).compileComponents(); }).compileComponents();
}); });
it.each([{ size: { value: 'S', label: 'Small' } }, { size: [{ value: 'S', label: 'Small' }] }])(
'initializes and matches structured variant values: %j',
(values) => {
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
const variant: CatalogItemVariant = { id: 1, maximum_addable_quantity: null, values };
const emittedIds: Array<number | null> = [];
fixture.componentInstance.variantChange.subscribe((selected) =>
emittedIds.push(selected?.id ?? null),
);
fixture.componentRef.setInput('attributes', [sizeAttribute]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [variant]);
fixture.componentRef.setInput('selectedVariant', variant);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector(
'.attribute-selector__text-option',
) as HTMLButtonElement;
expect(button.getAttribute('aria-pressed')).toBe('true');
expect(button.disabled).toBe(false);
expect(emittedIds.at(-1)).toBe(1);
},
);
it.each([0, 2, null])(
'uses maximum quantity %s for alternatives to a preselected option',
(maximum) => {
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
const variants: CatalogItemVariant[] = [
{ id: 1, maximum_addable_quantity: 3, values: { size: { value: 'S', label: 'Small' } } },
{
id: 2,
maximum_addable_quantity: maximum,
values: { size: { value: 'M', label: 'Medium' } },
},
];
const emittedIds: Array<number | null> = [];
fixture.componentInstance.variantChange.subscribe((variant) =>
emittedIds.push(variant?.id ?? null),
);
fixture.componentRef.setInput('attributes', [sizeAttribute]);
fixture.componentRef.setInput('inventoryPolicy', maximum === null ? 'unlimited' : 'tracked');
fixture.componentRef.setInput('variants', variants);
fixture.componentRef.setInput('selectedVariant', variants[0]);
fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll(
'.attribute-selector__text-option',
) as NodeListOf<HTMLButtonElement>;
expect(buttons[1].disabled).toBe(maximum === 0);
buttons[1].click();
fixture.detectChanges();
expect(emittedIds.at(-1)).toBe(maximum === 0 ? 1 : 2);
expect(buttons[0].disabled).toBe(false);
},
);
it('keeps an unlimited option available when maximum quantity is null', () => { it('keeps an unlimited option available when maximum quantity is null', () => {
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent); const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
fixture.componentRef.setInput('attributes', [sizeAttribute]); fixture.componentRef.setInput('attributes', [sizeAttribute]);
@@ -154,16 +94,7 @@ describe('ProductAttributeSelectorComponent', () => {
fixture.componentRef.setInput('variants', [ fixture.componentRef.setInput('variants', [
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } }, { id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } }, { id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
{ { id: 3, maximum_addable_quantity: null, values: { event_date: ['1', '2'] } },
id: 3,
maximum_addable_quantity: null,
values: {
event_date: [
{ value: '1', label: '09/10/2026' },
{ value: '2', label: '10/10/2026' },
],
},
},
]); ]);
fixture.detectChanges(); fixture.detectChanges();

View File

@@ -51,15 +51,22 @@ export class ProductAttributeSelectorComponent {
const optionNormalized = this.normalizeText(option.value || option.label); const optionNormalized = this.normalizeText(option.value || option.label);
const selectedForAttribute = selections[attribute.codigo] ?? []; const selectedForAttribute = selections[attribute.codigo] ?? [];
if (
!attribute.allow_multi_select &&
selectedForAttribute.length >= 1 &&
!selectedForAttribute.includes(option.id)
) {
availability[attribute.codigo][option.id] = false;
continue;
}
const isAvailable = variants.some((variant) => { const isAvailable = variants.some((variant) => {
if (!this.isVariantAvailable(variant)) return false; if (!this.isVariantAvailable(variant)) return false;
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values); const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
const desiredOptionIds = !attribute.allow_multi_select const desiredOptionIds = selectedForAttribute.includes(option.id)
? [option.id] ? selectedForAttribute
: selectedForAttribute.includes(option.id) : [...selectedForAttribute, option.id];
? selectedForAttribute
: [...selectedForAttribute, option.id];
const desiredValues = desiredOptionIds const desiredValues = desiredOptionIds
.map((id) => attribute.options.find((candidate) => candidate.id === id)) .map((id) => attribute.options.find((candidate) => candidate.id === id))
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined) .filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
@@ -195,7 +202,7 @@ export class ProductAttributeSelectorComponent {
private getVariantAttributeValues( private getVariantAttributeValues(
attribute: ProductAttribute, attribute: ProductAttribute,
variantAttributes: CatalogItemVariant['values'], variantAttributes: Record<string, string | string[]>,
): string[] { ): string[] {
const normalizedCodigo = this.normalizeText(attribute.codigo); const normalizedCodigo = this.normalizeText(attribute.codigo);
const normalizedNombre = this.normalizeText(attribute.nombre); const normalizedNombre = this.normalizeText(attribute.nombre);
@@ -204,9 +211,7 @@ export class ProductAttributeSelectorComponent {
const normalizedKey = this.normalizeText(key); const normalizedKey = this.normalizeText(key);
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) { if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
return (Array.isArray(value) ? value : [value]).map((item) => return (Array.isArray(value) ? value : [value]).map((item) => this.normalizeText(item));
this.normalizeText(typeof item === 'string' ? item : item.value || item.label),
);
} }
} }

View File

@@ -54,7 +54,7 @@
<!-- Thumbnails Row --> <!-- Thumbnails Row -->
@if (images().length > 1) { @if (images().length > 1) {
<div class="product-carousel__thumbnails"> <div class="product-carousel__thumbnails">
@for (image of images(); track $index; let idx = $index) { @for (image of images(); track image; let idx = $index) {
<button <button
type="button" type="button"
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light" class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"

View File

@@ -180,7 +180,7 @@ export class CategoryItemsPageComponent {
this.toastService.danger(message); this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) { if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
} }

View File

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

View File

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

View File

@@ -14,7 +14,6 @@ import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { CartEditingPolicy } from '../../../../core/services/tenant.interface'; import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
import { CheckoutPageComponent } from './checkout-page.component'; import { CheckoutPageComponent } from './checkout-page.component';
describe('CheckoutPageComponent payment validation', () => { describe('CheckoutPageComponent payment validation', () => {
@@ -130,93 +129,6 @@ describe('CheckoutPageComponent payment validation', () => {
return { fixture, component: fixture.componentInstance as any }; return { fixture, component: fixture.componentInstance as any };
} }
it('does not expose an active countdown until the purchase timing is loaded', async () => {
const countdown = TestBed.inject(CheckoutCountdownService);
countdown.synchronize({
expires_at: null,
expires_in_seconds: 600,
server_time: new Date().toISOString(),
});
checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25,
status: 'created',
expires_at: '2026-08-27T15:10:00.000Z',
expires_in_seconds: 600,
server_time: '2026-08-27T15:00:00.000Z',
items: [],
subtotal: '0.00',
total: '0.00',
});
routeParamMap = convertToParamMap({ id: 25 });
const { component } = createComponent();
expect(component.checkoutRemainingTime()).toBeNull();
await Promise.resolve();
expect(countdown.remainingSeconds()).toBe(600);
expect(component.checkoutRemainingTime()).toBe('10:00');
});
it('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' })
@@ -283,7 +195,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
}); });
it('polls a transfer every three seconds for one minute', async () => { it('polls a transfer every three seconds up to four attempts', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' }); checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
const { component } = createComponent(); const { component } = createComponent();
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
@@ -293,12 +205,14 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled(); expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(57_000); for (let attempt = 1; attempt <= 3; attempt += 1) {
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19); await vi.advanceTimersByTimeAsync(3_000);
expect(component.transferValidationStatus()).toBe('checking'); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
expect(component.transferValidationStatus()).toBe('checking');
}
await vi.advanceTimersByTimeAsync(3_000); await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25); expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
@@ -342,43 +256,13 @@ describe('CheckoutPageComponent payment validation', () => {
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
await component.onComplete(); await component.onComplete();
await vi.advanceTimersByTimeAsync(60_000); await vi.advanceTimersByTimeAsync(12_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
it('uses the primary candidate reason when transfer polling times out', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({
status: 'in_review',
payment_verification: {
status: 'candidate',
candidate_count: 1,
primary: {
reason: 'exact_amount_near_dni',
dni_distance: 1,
payment_amount: '300000.00',
purchase_amount: '300000.00',
amount_difference: '0.00',
confidence: 'medium',
detected_at: '2026-08-27T18:00:00-03:00',
},
reasons: ['exact_amount_near_dni'],
},
});
const { component } = createComponent();
component.selectedPaymentMethod.set('transfer');
await component.onComplete();
await vi.advanceTimersByTimeAsync(60_000);
expect(component.transferValidationStatus()).toBe('error');
expect(component.transferVerificationErrorTitle()).toBe(
'El DNI no corresponde con el de la transferencia',
);
});
it('does not poll when submitting a transfer for review fails', async () => { it('does not poll when submitting a transfer for review fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined); vi.spyOn(console, 'error').mockImplementation(() => undefined);
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error')); checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));

View File

@@ -2,7 +2,6 @@ import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
computed, computed,
effect,
inject, inject,
OnDestroy, OnDestroy,
OnInit, OnInit,
@@ -17,10 +16,8 @@ import { firstValueFrom, startWith } from 'rxjs';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { import {
CheckoutService, CheckoutService,
PurchasePaymentCandidateReason,
PurchaseDetailItemResponse, PurchaseDetailItemResponse,
PurchaseDetailResponse, PurchaseDetailResponse,
PurchaseStatusResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service'; import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
@@ -31,7 +28,6 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component'; import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
import { CheckoutDataStepComponent } from './checkout-data-step.component'; import { CheckoutDataStepComponent } from './checkout-data-step.component';
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component'; import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
import { import {
CheckoutForm, CheckoutForm,
PaymentMethod, PaymentMethod,
@@ -68,7 +64,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly tenantService = inject(TenantService); private readonly tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly globalLoadingService = inject(GlobalLoadingService); private readonly globalLoadingService = inject(GlobalLoadingService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
@@ -76,7 +71,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
private readonly qrPollingMaxAttempts = 120; private readonly qrPollingMaxAttempts = 120;
private readonly transferPollingIntervalMs = 3_000; private readonly transferPollingIntervalMs = 3_000;
private readonly transferPollingMaxAttempts = 20; private readonly transferPollingMaxAttempts = 209;
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null; private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
private qrPollingAttempts = 0; private qrPollingAttempts = 0;
@@ -87,7 +82,6 @@ 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;
@@ -101,27 +95,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null); protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
protected readonly isLoadingPurchase = signal(true); protected readonly isLoadingPurchase = signal(true);
protected readonly checkoutStepIndex = signal(0); protected readonly checkoutStepIndex = signal(0);
protected readonly checkoutRemainingTime = computed(() => {
const purchase = this.createdPurchase();
if (
!purchase ||
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
) {
return null;
}
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
if (remainingSeconds === null) {
return null;
}
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
});
protected readonly cartSubtotal = computed(() => { protected readonly cartSubtotal = computed(() => {
const purchase = this.createdPurchase(); const purchase = this.createdPurchase();
return purchase ? parseFloat(purchase.subtotal) : 0; return purchase ? parseFloat(purchase.subtotal) : 0;
@@ -162,14 +135,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle'); protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
protected readonly isCheckingQrPayment = signal(false); protected readonly isCheckingQrPayment = signal(false);
protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle'); protected readonly transferValidationStatus = signal<TransferValidationStatus>('idle');
private readonly transferPrimaryCandidateReason = signal<PurchasePaymentCandidateReason | null>(
null,
);
protected readonly transferVerificationErrorTitle = computed(() =>
this.transferPrimaryCandidateReason() === 'exact_amount_near_dni'
? 'El DNI no corresponde con el de la transferencia'
: null,
);
protected readonly whatsappUrl = computed( protected readonly whatsappUrl = computed(
() => () =>
this.tenantService this.tenantService
@@ -178,28 +143,6 @@ 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));
@@ -285,7 +228,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
nombre_apellido: formValue.nombre, nombre_apellido: formValue.nombre,
}); });
this.createdPurchase.set(purchase); this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.stepper.next(); this.stepper.next();
@@ -339,7 +281,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
const tenant = this.tenantService.tenant(); const tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId(); const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) { if (!tenant || !purchaseId) {
this.checkoutCountdownService.clear();
return true; return true;
} }
@@ -350,7 +291,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
await firstValueFrom(this.cartService.loadCart()); await firstValueFrom(this.cartService.loadCart());
this.createdPurchaseId.set(null); this.createdPurchaseId.set(null);
this.createdPurchase.set(null); this.createdPurchase.set(null);
this.checkoutCountdownService.clear();
this.navigationStarted = true; this.navigationStarted = true;
return true; return true;
@@ -359,12 +299,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
if (this.isStockReservationExpiredError(error)) { if (this.isStockReservationExpiredError(error)) {
this.showRequestError(error, 'La reserva de stock venció.'); this.showRequestError(error, 'La reserva de stock venció.');
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
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;
} }
@@ -443,7 +382,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.transferDni.set(dni); this.transferDni.set(dni);
this.stopTransferPolling(); this.stopTransferPolling();
this.transferValidationStatus.set('idle'); this.transferValidationStatus.set('idle');
this.transferPrimaryCandidateReason.set(null);
this.isGeneratingIntent.set(true); this.isGeneratingIntent.set(true);
try { try {
const response = await this.checkoutService const response = await this.checkoutService
@@ -500,7 +438,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.stopTransferPolling(); this.stopTransferPolling();
this.hasSubmittedTransfer.set(true); this.hasSubmittedTransfer.set(true);
this.transferValidationStatus.set('checking'); this.transferValidationStatus.set('checking');
this.transferPrimaryCandidateReason.set(null);
this.transferPollingAttempts = 0; this.transferPollingAttempts = 0;
const runId = this.transferPollingRunId; const runId = this.transferPollingRunId;
@@ -514,9 +451,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
this.captureTransferCandidateReason(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
@@ -566,9 +500,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
this.captureTransferCandidateReason(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
@@ -599,14 +530,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.scheduleTransferPoll(runId); this.scheduleTransferPoll(runId);
} }
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
const reason = purchase.payment_verification?.primary?.reason;
if (reason) {
this.transferPrimaryCandidateReason.set(reason);
}
}
private stopTransferPolling(): void { private stopTransferPolling(): void {
this.transferPollingRunId += 1; this.transferPollingRunId += 1;
@@ -663,8 +586,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
return; return;
} }
this.checkoutCountdownService.synchronize(purchase);
if (purchase.status === 'paid') { if (purchase.status === 'paid') {
this.handleConfirmedPayment(purchaseId); this.handleConfirmedPayment(purchaseId);
return; return;
@@ -738,40 +659,10 @@ 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) {
@@ -805,7 +696,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.createdPurchaseId.set(purchase.id); this.createdPurchaseId.set(purchase.id);
this.createdPurchase.set(purchase); this.createdPurchase.set(purchase);
this.checkoutCountdownService.synchronize(purchase);
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0); this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
if ( if (
@@ -889,7 +779,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.navigationStarted = true; this.navigationStarted = true;
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling(); this.stopTransferPolling();
this.checkoutCountdownService.clear();
void this.router.navigate(['/checkout/status', purchaseId], { void this.router.navigate(['/checkout/status', purchaseId], {
queryParams: { status: 'expired' }, queryParams: { status: 'expired' },
}); });

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,21 +3,11 @@ import { provideRouter, Router } from '@angular/router';
import { of, throwError } from 'rxjs'; import { of, throwError } from 'rxjs';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { ToastService } from '../../../../core/services/toast.service';
import { LoginPageComponent } from './login-page.component'; import { LoginPageComponent } from './login-page.component';
describe('LoginPageComponent', () => { describe('LoginPageComponent', () => {
let toastService: {
danger: ReturnType<typeof vi.fn>;
showAfterReload: ReturnType<typeof vi.fn>;
};
beforeEach(() => { beforeEach(() => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
toastService = {
danger: vi.fn(),
showAfterReload: vi.fn(),
};
}); });
it('submits credentials and redirects to home with a full page reload on success', async () => { it('submits credentials and redirects to home with a full page reload on success', async () => {
@@ -26,18 +16,14 @@ describe('LoginPageComponent', () => {
of({ of({
id: 1, id: 1,
nombre_apellido: 'Ada Lovelace', nombre_apellido: 'Ada Lovelace',
email: 'ada@example.com', email: 'ada@example.com'
}), })
), )
}; };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [LoginPageComponent], imports: [LoginPageComponent],
providers: [ providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
provideRouter([]),
{ provide: AuthService, useValue: authService },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents(); }).compileComponents();
const fixture = TestBed.createComponent(LoginPageComponent); const fixture = TestBed.createComponent(LoginPageComponent);
@@ -48,56 +34,17 @@ describe('LoginPageComponent', () => {
component.form.setValue({ component.form.setValue({
email: 'ada@example.com', email: 'ada@example.com',
password: 'secret123', password: 'secret123'
}); });
component.onSubmit(); component.onSubmit();
expect(authService.login).toHaveBeenCalledWith({ expect(authService.login).toHaveBeenCalledWith({
email: 'ada@example.com', email: 'ada@example.com',
password: 'secret123', password: 'secret123'
}); });
expect(redirectSpy).toHaveBeenCalled(); expect(redirectSpy).toHaveBeenCalled();
expect(navigateSpy).not.toHaveBeenCalled(); expect(navigateSpy).not.toHaveBeenCalled();
expect(toastService.showAfterReload).toHaveBeenCalledWith(
'Sesión iniciada correctamente.',
'success',
);
});
it('serializes a stored return URL before reloading so tenant base paths are restored', async () => {
await TestBed.configureTestingModule({
imports: [LoginPageComponent],
providers: [
provideRouter([]),
{ provide: AuthService, useValue: {} },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents();
const fixture = TestBed.createComponent(LoginPageComponent);
const component = fixture.componentInstance as any;
const router = TestBed.inject(Router);
const assign = vi.fn();
const parsedUrl = router.parseUrl('/');
component.document = {
defaultView: {
sessionStorage: {
getItem: vi.fn().mockReturnValue('/'),
removeItem: vi.fn(),
},
},
location: { assign },
};
const parseUrlSpy = vi.spyOn(router, 'parseUrl').mockReturnValue(parsedUrl);
const serializeUrlSpy = vi.spyOn(router, 'serializeUrl').mockReturnValue('/sonder');
component.redirectToHome();
expect(parseUrlSpy).toHaveBeenCalledWith('/');
expect(serializeUrlSpy).toHaveBeenCalledWith(parsedUrl);
expect(assign).toHaveBeenCalledWith('/sonder');
}); });
it('surfaces backend login errors', async () => { it('surfaces backend login errors', async () => {
@@ -106,20 +53,16 @@ describe('LoginPageComponent', () => {
throwError(() => ({ throwError(() => ({
error: { error: {
errors: { errors: {
email: ['Las credenciales son invalidas.'], email: ['Las credenciales son invalidas.']
}, }
}, }
})), }))
), )
}; };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [LoginPageComponent], imports: [LoginPageComponent],
providers: [ providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
provideRouter([]),
{ provide: AuthService, useValue: authService },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents(); }).compileComponents();
const fixture = TestBed.createComponent(LoginPageComponent); const fixture = TestBed.createComponent(LoginPageComponent);
@@ -127,27 +70,22 @@ describe('LoginPageComponent', () => {
component.form.setValue({ component.form.setValue({
email: 'ada@example.com', email: 'ada@example.com',
password: 'wrong-password', password: 'wrong-password'
}); });
component.onSubmit(); component.onSubmit();
expect(component.serverError()).toBe('Las credenciales son invalidas.'); expect(component.serverError()).toBe('Las credenciales son invalidas.');
expect(toastService.danger).toHaveBeenCalledWith('Las credenciales son invalidas.');
}); });
it('validates email length and password minimum length before submit', async () => { it('validates email length and password minimum length before submit', async () => {
const authService = { const authService = {
login: vi.fn(), login: vi.fn()
}; };
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [LoginPageComponent], imports: [LoginPageComponent],
providers: [ providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
provideRouter([]),
{ provide: AuthService, useValue: authService },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents(); }).compileComponents();
const fixture = TestBed.createComponent(LoginPageComponent); const fixture = TestBed.createComponent(LoginPageComponent);
@@ -155,15 +93,12 @@ describe('LoginPageComponent', () => {
component.form.setValue({ component.form.setValue({
email: `${'a'.repeat(250)}@example.com`, email: `${'a'.repeat(250)}@example.com`,
password: '1234567', password: '1234567'
}); });
component.onSubmit(); component.onSubmit();
expect(authService.login).not.toHaveBeenCalled(); expect(authService.login).not.toHaveBeenCalled();
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.'); expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.'); expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
expect(toastService.danger).toHaveBeenCalledWith(
'Revisá los datos ingresados para iniciar sesión.',
);
}); });
}); });

View File

@@ -4,7 +4,6 @@ import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component'; import { ButtonComponent } from '../../../../shared/components/button/button.component';
import { InputComponent } from '../../../../shared/components/input/input.component'; import { InputComponent } from '../../../../shared/components/input/input.component';
@@ -17,14 +16,13 @@ const POST_LOGIN_RETURN_URL_KEY = 'shopit.auth.return-url';
imports: [ReactiveFormsModule, InputComponent, ButtonComponent], imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
templateUrl: './login-page.component.html', templateUrl: './login-page.component.html',
styleUrl: './login-page.component.scss', styleUrl: './login-page.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class LoginPageComponent { export class LoginPageComponent {
private readonly formBuilder = inject(FormBuilder); private readonly formBuilder = inject(FormBuilder);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly toastService = inject(ToastService);
private readonly document = inject(DOCUMENT); private readonly document = inject(DOCUMENT);
private readonly platformId = inject(PLATFORM_ID); private readonly platformId = inject(PLATFORM_ID);
@@ -34,7 +32,7 @@ export class LoginPageComponent {
protected readonly form = this.formBuilder.nonNullable.group({ protected readonly form = this.formBuilder.nonNullable.group({
email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]], email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]],
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]], password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]]
}); });
protected readonly submitted = this.submittedState.asReadonly(); protected readonly submitted = this.submittedState.asReadonly();
protected readonly serverError = this.serverErrorState.asReadonly(); protected readonly serverError = this.serverErrorState.asReadonly();
@@ -66,7 +64,6 @@ export class LoginPageComponent {
if (this.form.invalid) { if (this.form.invalid) {
this.form.markAllAsTouched(); this.form.markAllAsTouched();
this.toastService.danger('Revisá los datos ingresados para iniciar sesión.');
return; return;
} }
@@ -75,13 +72,12 @@ export class LoginPageComponent {
this.authService.login(this.form.getRawValue()).subscribe({ this.authService.login(this.form.getRawValue()).subscribe({
next: () => { next: () => {
this.isSubmittingState.set(false); this.isSubmittingState.set(false);
this.toastService.showAfterReload('Sesión iniciada correctamente.', 'success');
this.redirectToHome(); this.redirectToHome();
}, },
error: (error: unknown) => { error: (error: unknown) => {
this.isSubmittingState.set(false); this.isSubmittingState.set(false);
this.showLoginError(error); this.serverErrorState.set(this.resolveErrorMessage(error));
}, }
}); });
} }
@@ -95,7 +91,7 @@ export class LoginPageComponent {
} }
this.authService.loginWithGoogle(); this.authService.loginWithGoogle();
} catch (error: unknown) { } catch (error: unknown) {
this.showLoginError(error); this.serverErrorState.set(this.resolveErrorMessage(error));
} }
} }
@@ -143,9 +139,10 @@ export class LoginPageComponent {
const requestedUrl = const requestedUrl =
this.route.snapshot.queryParamMap.get('returnUrl') ?? this.route.snapshot.queryParamMap.get('returnUrl') ??
this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY); this.document.defaultView?.sessionStorage.getItem(POST_LOGIN_RETURN_URL_KEY);
const internalDestination = const destination =
requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//') ? requestedUrl : '/'; requestedUrl?.startsWith('/') && !requestedUrl.startsWith('//')
const destination = this.router.serializeUrl(this.router.parseUrl(internalDestination)); ? requestedUrl
: this.router.serializeUrl(this.router.createUrlTree(['/']));
this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY); this.document.defaultView?.sessionStorage.removeItem(POST_LOGIN_RETURN_URL_KEY);
this.document.location.assign(destination); this.document.location.assign(destination);
@@ -158,22 +155,15 @@ export class LoginPageComponent {
this.authService.completeGoogleLogin(oauthCode).subscribe({ this.authService.completeGoogleLogin(oauthCode).subscribe({
next: () => { next: () => {
this.isSubmittingState.set(false); this.isSubmittingState.set(false);
this.toastService.showAfterReload('Sesión iniciada correctamente.', 'success');
this.redirectToHome(); this.redirectToHome();
}, },
error: (error: unknown) => { error: (error: unknown) => {
this.isSubmittingState.set(false); this.isSubmittingState.set(false);
this.showLoginError(error); this.serverErrorState.set(this.resolveErrorMessage(error));
}, }
}); });
} }
private showLoginError(error: unknown): void {
const message = this.resolveErrorMessage(error);
this.serverErrorState.set(message);
this.toastService.danger(message);
}
private resolveErrorMessage(error: unknown): string { private resolveErrorMessage(error: unknown): string {
const errorPayload = const errorPayload =
typeof error === 'object' && error !== null && 'error' in error typeof error === 'object' && error !== null && 'error' in error

View File

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

View File

@@ -67,13 +67,9 @@ describe('PurchaseStatusPageComponent', () => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
async function render( async function render(hasGeneratedTickets: boolean, forcedStatus?: string) {
hasGeneratedTickets: boolean,
forcedStatus?: string,
purchaseResponse = purchase(hasGeneratedTickets),
) {
const checkoutService = { const checkoutService = {
getPurchase: vi.fn().mockResolvedValue(purchaseResponse), getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
withCustomLoading() { withCustomLoading() {
return this; return this;
}, },
@@ -95,7 +91,9 @@ describe('PurchaseStatusPageComponent', () => {
useValue: { useValue: {
snapshot: { snapshot: {
paramMap: convertToParamMap({ id: '42' }), paramMap: convertToParamMap({ id: '42' }),
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}), queryParamMap: convertToParamMap(
forcedStatus ? { status: forcedStatus } : {},
),
}, },
}, },
}, },
@@ -161,30 +159,6 @@ describe('PurchaseStatusPageComponent', () => {
expect(checkoutService.getPurchase).not.toHaveBeenCalled(); 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();

View File

@@ -13,7 +13,6 @@ 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 { CartService } from '../../../../core/services/cart/cart.service';
@@ -49,7 +48,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
protected readonly isLoading = signal(true); protected readonly isLoading = signal(true);
protected readonly status = signal<PurchaseStatusView>('pending'); protected readonly status = signal<PurchaseStatusView>('pending');
protected readonly hasGeneratedTickets = signal(false); protected readonly hasGeneratedTickets = signal(false);
protected readonly paymentIssueMessage = signal<string | null>(null);
protected readonly ticketsRoute = computed(() => { protected readonly ticketsRoute = computed(() => {
if (!this.hasGeneratedTickets()) { if (!this.hasGeneratedTickets()) {
return null; return null;
@@ -107,7 +105,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
const status = this.resolveStatus(purchase); const status = this.resolveStatus(purchase);
this.status.set(status); this.status.set(status);
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true); this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
if (status === 'approved') { if (status === 'approved') {
this.cartService.clearCart(); this.cartService.clearCart();
@@ -172,43 +169,6 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
return 'pending'; return 'pending';
} }
private resolvePaymentIssueMessage(
verification?: PurchasePaymentVerificationResponse,
): string | null {
const primary = verification?.primary;
if (!primary) {
return null;
}
const primaryMessage = (() => {
switch (primary.reason) {
case 'ambiguous_exact_match':
return 'Encontramos una transferencia que también coincide con otra compra.';
case 'exact_dni_near_amount':
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
case 'exact_amount_near_dni':
return primary.dni_distance === null
? 'El monto coincide, pero el DNI del pagador es diferente.'
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
}
})();
if (verification.candidate_count > 1) {
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
}
return primaryMessage;
}
private formatCurrency(amount: string): string {
return new Intl.NumberFormat('es-AR', {
style: 'currency',
currency: 'ARS',
maximumFractionDigits: 2,
}).format(Number(amount));
}
private isPurchaseExpiredError(error: unknown): boolean { private isPurchaseExpiredError(error: unknown): boolean {
if (typeof error !== 'object' || error === null || !('error' in error)) { if (typeof error !== 'object' || error === null || !('error' in error)) {
return false; return false;

View File

@@ -212,7 +212,7 @@ export class SearchPageComponent {
this.toastService.danger(message); this.toastService.danger(message);
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) { if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
} }

View File

@@ -22,7 +22,7 @@
No hay productos disponibles en este momento. No hay productos disponibles en este momento.
</p> </p>
} @else { } @else {
@for (group of catalog(); track group.id; let first = $first) { @for (group of catalog(); track group.id) {
<app-store-section [attr.id]="group.code" [title]="group.title"> <app-store-section [attr.id]="group.code" [title]="group.title">
<app-product-list <app-product-list
[layout]="group.layout" [layout]="group.layout"
@@ -30,7 +30,6 @@
[items]="group.items" [items]="group.items"
[loading]="isGroupLoading(group.id)" [loading]="isGroupLoading(group.id)"
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()" [loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
[prioritizeFirstImage]="first && !hasMainCarouselImages()"
[unavailableVariantIds]="unavailableVariantIds()" [unavailableVariantIds]="unavailableVariantIds()"
[savingProductIds]="savingProductIds()" [savingProductIds]="savingProductIds()"
(buy)="onBuyProduct($event)" (buy)="onBuyProduct($event)"

View File

@@ -224,7 +224,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) { if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
this.toastService.danger(error.error.message); this.toastService.danger(error.error.message);
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
return; return;

View File

@@ -330,7 +330,7 @@ export class CartComponent {
return; return;
} }
this.cartService.loadCart(true).subscribe({ this.cartService.loadCart().subscribe({
error: (refreshError) => console.error('Error refreshing expired cart', refreshError), error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
}); });
} }

View File

@@ -1,8 +1,5 @@
<div class="hero-banner-container"> <div class="hero-banner-container">
<div <div class="hero-banner position-relative rounded">
class="hero-banner position-relative rounded"
[class.hero-banner--with-media]="desktopImageUrl"
>
@if (desktopImageUrl) { @if (desktopImageUrl) {
<picture class="hero-media" aria-hidden="true"> <picture class="hero-media" aria-hidden="true">
@if (mobileImageUrl) { @if (mobileImageUrl) {

View File

@@ -7,23 +7,23 @@
min-height: 400px; min-height: 400px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
&--with-media {
min-height: 0;
}
} }
.hero-media { .hero-media {
position: relative; position: absolute;
inset: 0;
display: block; display: block;
width: 100%;
overflow: hidden; overflow: hidden;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
border-radius: inherit; border-radius: inherit;
img { img {
display: block; display: block;
width: 100%; width: 100%;
height: auto; height: 100%;
object-fit: cover;
} }
&::after { &::after {
@@ -52,11 +52,6 @@
flex-grow: 1; flex-grow: 1;
} }
.hero-banner--with-media .hero-content {
position: absolute;
inset: 0;
}
::ng-deep .hero-title, ::ng-deep .hero-title,
.hero-title { .hero-title {
color: #666666; color: #666666;
@@ -184,29 +179,24 @@
inset: auto; inset: auto;
flex: 0 0 auto; flex: 0 0 auto;
width: 100%; width: 100%;
overflow: visible; height: clamp(8.75rem, 44vw, 211px);
background-position: center center;
background-size: 140% auto;
border-radius: 0; border-radius: 0;
} }
.hero-media::after { .hero-media::after {
top: auto; top: auto;
bottom: -2px; height: 48%;
height: calc(48% + 2px);
background: linear-gradient( background: linear-gradient(
to bottom, to bottom,
rgba(245, 245, 245, 0) 0%, rgba(245, 245, 245, 0) 0%,
rgba(245, 245, 245, 0.78) 55%, rgba(245, 245, 245, 0.78) 55%,
#f5f5f5 96%,
#f5f5f5 100% #f5f5f5 100%
); );
border-radius: 0; border-radius: 0;
} }
.hero-banner--with-media .hero-content {
position: relative;
inset: auto;
}
.hero-content { .hero-content {
justify-content: center !important; justify-content: center !important;
height: auto !important; height: auto !important;

View File

@@ -22,21 +22,6 @@ describe('HeroBannerComponent', () => {
expect(element.querySelector('img')?.getAttribute('src')).toBe( expect(element.querySelector('img')?.getAttribute('src')).toBe(
'https://example.com/desktop.jpg', 'https://example.com/desktop.jpg',
); );
expect(element.querySelector('.hero-banner')?.classList).toContain(
'hero-banner--with-media',
);
});
it('keeps the fallback banner sizing when there is no image', async () => {
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
const fixture = TestBed.createComponent(HeroBannerComponent);
fixture.componentRef.setInput('heroConfig', { title_html: 'Banner sin imagen' });
fixture.detectChanges();
const banner = (fixture.nativeElement as HTMLElement).querySelector('.hero-banner');
expect(banner?.classList).not.toContain('hero-banner--with-media');
}); });
it('expands and collapses the event schedules', async () => { it('expands and collapses the event schedules', async () => {

View File

@@ -1,58 +0,0 @@
<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()"
>
&minus;
</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()"
>
&plus;
</button>
</div>
</div>

View File

@@ -1,146 +0,0 @@
: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;
}
}

View File

@@ -1,165 +0,0 @@
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()));
}

View File

@@ -1,395 +0,0 @@
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;
}
}

View File

@@ -2,7 +2,6 @@
<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()"

View File

@@ -51,10 +51,6 @@ 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();
}); });
@@ -103,10 +99,6 @@ 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', () => {

View File

@@ -55,23 +55,11 @@ 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;
@@ -80,47 +68,6 @@ 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;
@@ -135,26 +82,8 @@ 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);
}
}); });
}); });
} }

View File

@@ -1,9 +1,4 @@
<div <div class="modal-shell" (click)="backdropClick.emit()">
#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()"

View File

@@ -4,10 +4,7 @@
.modal-shell { .modal-shell {
position: fixed; position: fixed;
top: var(--modal-viewport-top, 0); inset: 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;
@@ -112,64 +109,6 @@
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;
@@ -189,18 +128,4 @@
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;
}
} }

View File

@@ -9,7 +9,7 @@ import {
viewChild, viewChild,
} from '@angular/core'; } from '@angular/core';
import { ModalPresentation, ModalSize } from '../../../core/services/modal.service'; import { ModalSize } from '../../../core/services/modal.service';
@Component({ @Component({
selector: 'app-modal-shell', selector: 'app-modal-shell',
@@ -19,12 +19,10 @@ import { ModalPresentation, ModalSize } from '../../../core/services/modal.servi
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>();
@@ -48,28 +46,6 @@ 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>(

View File

@@ -51,9 +51,7 @@
[title]="item.nombre" [title]="item.nombre"
[originalPrice]="price(item)" [originalPrice]="price(item)"
[unavailableMessage]="item.unavailable_message ?? null" [unavailableMessage]="item.unavailable_message ?? null"
[imagePriority]=" [imagePriority]="loadImages() && index < 4"
loadImages() && prioritizeFirstImage() && groupLayout() !== 'carousel' && index === 0
"
(buy)="emitProductDetailBuy(item)" (buy)="emitProductDetailBuy(item)"
/> />
} }

View File

@@ -143,14 +143,6 @@ describe('ProductListComponent', () => {
expect(element.querySelector('.product-list--column')).not.toBeNull(); expect(element.querySelector('.product-list--column')).not.toBeNull();
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2); expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
expect(element.querySelectorAll('img[fetchpriority="high"]')).toHaveLength(1);
});
it('does not prioritize images rendered in a circular carousel', async () => {
const fixture = await render('column_with_image', items, 'carousel');
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelectorAll('img[fetchpriority="high"]')).toHaveLength(0);
}); });
it('renders cart products next to each other in the column grid', async () => { it('renders cart products next to each other in the column grid', async () => {

View File

@@ -68,7 +68,6 @@ export class ProductListComponent {
readonly items = input.required<CatalogFeaturedItems>(); readonly items = input.required<CatalogFeaturedItems>();
readonly loading = input(false); readonly loading = input(false);
readonly loadImages = input(true); readonly loadImages = input(true);
readonly prioritizeFirstImage = input(true);
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>()); readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
readonly savingProductIds = input<ReadonlySet<number>>(new Set<number>()); readonly savingProductIds = input<ReadonlySet<number>>(new Set<number>());

View File

@@ -107,17 +107,6 @@
</div> </div>
@if (imageUrl(); as image) { @if (imageUrl(); as image) {
<button <img class="ticket-selector__map" [src]="image" [alt]="'Plano de ubicaciones de ' + title()" />
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>

View File

@@ -153,27 +153,11 @@
margin-top: 0.75rem; margin-top: 0.75rem;
} }
&__map-button {
display: block;
width: min(100%, 720px);
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 { &__map {
display: block; display: block;
width: 100%; width: min(100%, 720px);
max-height: 680px; max-height: 680px;
margin: 3rem auto 0;
object-fit: contain; object-fit: contain;
} }
} }
@@ -204,7 +188,7 @@
display: none; display: none;
} }
&__map-button { &__map {
margin-top: 2rem; margin-top: 2rem;
} }
} }

View File

@@ -104,10 +104,6 @@ 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],
@@ -116,7 +112,7 @@ describe('ProductTicketSelectorComponent', () => {
{ provide: CartService, useValue: cartService }, { provide: CartService, useValue: cartService },
{ {
provide: ModalService, provide: ModalService,
useValue: modalService, useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
}, },
{ provide: ToastService, useValue: { danger: toastDanger } }, { provide: ToastService, useValue: { danger: toastDanger } },
], ],
@@ -129,7 +125,7 @@ describe('ProductTicketSelectorComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
return { fixture, getVariantOptions, cartService, toastDanger, modalService }; return { fixture, getVariantOptions, cartService, toastDanger };
} }
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 () => {
@@ -230,25 +226,6 @@ 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');

View File

@@ -154,14 +154,6 @@ 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++);

View File

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

View File

@@ -1,16 +1,13 @@
<!doctype html> <!doctype html>
<html lang="es"> <html lang="es">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8">
<title>ShopitFront</title> <title>ShopitFront</title>
<base href="/" /> <base href="/">
<meta <meta name="viewport" content="width=device-width, initial-scale=1">
name="viewport" <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E">
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" </head>
/> <body>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E" /> <app-root></app-root>
</head> </body>
<body>
<app-root></app-root>
</body>
</html> </html>

View File

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