Compare commits
22 Commits
fix/cart-e
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ec48f7e21 | |||
| 07972760fc | |||
| 848c3b280f | |||
| c387a01d62 | |||
| 5d9adc0494 | |||
| 593580d648 | |||
| eb524c7d99 | |||
| 65e8436ae1 | |||
| 07500f699d | |||
| 4997665da6 | |||
| dbfadf417a | |||
| dddb086cd8 | |||
| a825b3693b | |||
| 679342ec8d | |||
| a5420e6a42 | |||
| 91b8788c91 | |||
| b6a52ceb8c | |||
| 51d051733c | |||
| f62cd08807 | |||
| d61b1e4b0a | |||
| 1bffefece3 | |||
| b0d2cd05bc |
@@ -152,9 +152,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (displayCategories()) {
|
||||
<div class="store-layout__categories d-none d-md-block">
|
||||
<div class="container-xl px-3 px-md-4">
|
||||
<div class="store-layout__categories d-none d-md-block">
|
||||
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
|
||||
@if (displayCategories()) {
|
||||
<div class="store-layout__category-menu">
|
||||
<button
|
||||
type="button"
|
||||
@@ -175,7 +175,18 @@
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (checkoutRemainingTime(); as remainingTime) {
|
||||
<div
|
||||
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
|
||||
role="timer"
|
||||
aria-label="Tiempo restante de compra"
|
||||
>
|
||||
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
|
||||
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -10,6 +10,26 @@
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.store-layout__categories {
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.store-layout__checkout-timer {
|
||||
color: var(--tenant-primary);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-layout__checkout-timer-label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.store-layout__checkout-timer-value {
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.store-layout__brand-slot {
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
|
||||
import {
|
||||
Component,
|
||||
computed,
|
||||
ElementRef,
|
||||
HostListener,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||
@@ -40,6 +49,7 @@ export class StoreHeaderComponent {
|
||||
readonly displaySeachBar = input(true);
|
||||
readonly displayCart = input(true);
|
||||
readonly cartDisabled = input(false);
|
||||
readonly checkoutRemainingSeconds = input<number | null>(null);
|
||||
readonly cartClick = output<void>();
|
||||
readonly ticketsClick = output<void>();
|
||||
readonly loginClick = output<void>();
|
||||
@@ -53,6 +63,18 @@ export class StoreHeaderComponent {
|
||||
protected readonly minSearchLength = 3;
|
||||
protected readonly showSearchError = signal(false);
|
||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
||||
protected readonly checkoutRemainingTime = computed(() => {
|
||||
const remainingSeconds = this.checkoutRemainingSeconds();
|
||||
|
||||
if (remainingSeconds === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(remainingSeconds / 60);
|
||||
const seconds = remainingSeconds % 60;
|
||||
|
||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
});
|
||||
|
||||
protected onCartClick(): void {
|
||||
if (this.cartDisabled()) {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||
[displayCart]="displayCart()"
|
||||
[cartDisabled]="isCheckoutRoute()"
|
||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
||||
(cartClick)="onCartClick()"
|
||||
(ticketsClick)="onTicketsClick()"
|
||||
(loginClick)="onLoginClick()"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
:host {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 100dvh;
|
||||
background: #f5f5f5;
|
||||
color: #202020;
|
||||
@@ -7,6 +9,8 @@
|
||||
|
||||
.store-layout {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.store-layout__cart-overlay {
|
||||
|
||||
@@ -24,6 +24,7 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
|
||||
import { StoreLayoutComponent } from './store-layout.component';
|
||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||
import { CheckoutService } from '../../services/checkout.service';
|
||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
||||
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
||||
|
||||
const tenant: Tenant = {
|
||||
@@ -150,6 +151,7 @@ describe('StoreLayoutComponent', () => {
|
||||
let tenantState = signal<Tenant | null>(tenant);
|
||||
let cartState = signal<Cart | null>(null);
|
||||
let authUserState = signal<AuthUser | null>(null);
|
||||
let checkoutRemainingSecondsState = signal<number | null>(null);
|
||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||
|
||||
@@ -157,6 +159,7 @@ describe('StoreLayoutComponent', () => {
|
||||
tenantState = signal<Tenant | null>(tenant);
|
||||
cartState = signal<Cart | null>(null);
|
||||
authUserState = signal<AuthUser | null>(null);
|
||||
checkoutRemainingSecondsState = signal<number | null>(null);
|
||||
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||
const isAuthenticatedState = signal(false);
|
||||
checkoutServiceStub = {
|
||||
@@ -215,6 +218,12 @@ describe('StoreLayoutComponent', () => {
|
||||
provide: CheckoutService,
|
||||
useValue: checkoutServiceStub,
|
||||
},
|
||||
{
|
||||
provide: CheckoutCountdownService,
|
||||
useValue: {
|
||||
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
});
|
||||
@@ -271,6 +280,22 @@ describe('StoreLayoutComponent', () => {
|
||||
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the synchronized countdown in the header whenever one is active', () => {
|
||||
checkoutRemainingSecondsState.set(587);
|
||||
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
|
||||
'Tiempo restante de compra:',
|
||||
);
|
||||
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
|
||||
'09:47',
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the configured header elements when the tenant disables them', () => {
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from '../../services/checkout.service';
|
||||
import { ToastService } from '../../services/toast.service';
|
||||
import { Category } from '../../services/tenant.interface';
|
||||
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-store-layout',
|
||||
@@ -42,6 +43,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
@@ -49,6 +51,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
|
||||
protected readonly isCartOpen = signal(false);
|
||||
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
|
||||
protected readonly isCreatingPurchase = signal(false);
|
||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||
@@ -287,7 +290,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
this.toastService.danger(message);
|
||||
|
||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,6 +83,20 @@ describe('CartService', () => {
|
||||
req.flush({ data: mockCart });
|
||||
});
|
||||
|
||||
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
|
||||
const availabilityChanged = vi.fn();
|
||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||
|
||||
service.loadCart(true).subscribe();
|
||||
|
||||
expect(availabilityChanged).not.toHaveBeenCalled();
|
||||
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
|
||||
req.flush({ data: mockCart });
|
||||
|
||||
expect(service.cart()).toEqual(mockCart);
|
||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('propagates a custom loading mode to the request context', () => {
|
||||
service.withCustomLoading().loadCart().subscribe();
|
||||
|
||||
|
||||
@@ -34,14 +34,19 @@ export class CartService extends BaseApiService {
|
||||
});
|
||||
}
|
||||
|
||||
loadCart(): Observable<Cart> {
|
||||
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
||||
return this.http
|
||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => response.data),
|
||||
tap((cart) => this.cartState.set(cart)),
|
||||
tap((cart) => {
|
||||
this.cartState.set(cart);
|
||||
if (refreshCatalogAvailability) {
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
CatalogItemDetail,
|
||||
CatalogVariantOptionsResponse,
|
||||
CategoryItemsResponse,
|
||||
Product,
|
||||
} from './catalog.interface';
|
||||
|
||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||
@@ -33,12 +32,6 @@ export class CatalogService extends BaseApiService {
|
||||
return this.tenantService.getTenantApiUrl();
|
||||
}
|
||||
|
||||
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
|
||||
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
|
||||
params: this.buildHttpParams(params),
|
||||
});
|
||||
}
|
||||
|
||||
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
||||
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
||||
}
|
||||
|
||||
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CheckoutCountdownService } from './checkout-countdown.service';
|
||||
|
||||
describe('CheckoutCountdownService', () => {
|
||||
let service: CheckoutCountdownService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
|
||||
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
|
||||
service = TestBed.inject(CheckoutCountdownService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
service.clear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('counts down from the checkout server timing without depending on the client clock', () => {
|
||||
service.synchronize({
|
||||
expires_at: '2026-08-27T15:10:00.000Z',
|
||||
expires_in_seconds: 600,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(service.remainingSeconds()).toBe(600);
|
||||
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
expect(service.remainingSeconds()).toBe(599);
|
||||
});
|
||||
|
||||
it('recalculates against the deadline after a delayed browser interval', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: 10,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
expect(service.remainingSeconds()).toBe(2);
|
||||
});
|
||||
|
||||
it('clears the countdown when checkout has no expiration', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: null,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(service.remainingSeconds()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: 10,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
service.synchronize({});
|
||||
|
||||
expect(service.remainingSeconds()).toBe(10);
|
||||
});
|
||||
});
|
||||
97
src/app/core/services/checkout-countdown.service.ts
Normal file
97
src/app/core/services/checkout-countdown.service.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Injectable, OnDestroy, signal } from '@angular/core';
|
||||
|
||||
export interface CheckoutTiming {
|
||||
expires_at: string | null;
|
||||
expires_in_seconds: number | null;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CheckoutCountdownService implements OnDestroy {
|
||||
private readonly remainingSecondsState = signal<number | null>(null);
|
||||
private deadlineMs: number | null = null;
|
||||
private intervalId: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
|
||||
|
||||
synchronize(timing: Partial<CheckoutTiming>): void {
|
||||
const remainingSeconds = this.resolveRemainingSeconds(timing);
|
||||
|
||||
if (remainingSeconds === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (remainingSeconds === null) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
this.stopInterval();
|
||||
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
|
||||
this.updateRemainingSeconds();
|
||||
|
||||
if (remainingSeconds > 0) {
|
||||
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.stopInterval();
|
||||
this.deadlineMs = null;
|
||||
this.remainingSecondsState.set(null);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.clear();
|
||||
}
|
||||
|
||||
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
|
||||
if (timing.expires_at === null && timing.expires_in_seconds === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const expiresAt =
|
||||
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
|
||||
const serverTime =
|
||||
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
|
||||
|
||||
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
|
||||
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
|
||||
}
|
||||
|
||||
if (
|
||||
typeof timing.expires_in_seconds === 'number' &&
|
||||
Number.isFinite(timing.expires_in_seconds)
|
||||
) {
|
||||
return Math.max(0, Math.ceil(timing.expires_in_seconds));
|
||||
}
|
||||
|
||||
if (Number.isFinite(expiresAt)) {
|
||||
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private updateRemainingSeconds(): void {
|
||||
if (this.deadlineMs === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
|
||||
this.remainingSecondsState.set(remainingSeconds);
|
||||
|
||||
if (remainingSeconds === 0) {
|
||||
this.stopInterval();
|
||||
}
|
||||
}
|
||||
|
||||
private stopInterval(): void {
|
||||
if (this.intervalId !== null) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||
import { CheckoutService } from './checkout.service';
|
||||
|
||||
describe('CheckoutService', () => {
|
||||
@@ -38,4 +39,59 @@ describe('CheckoutService', () => {
|
||||
|
||||
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||
});
|
||||
|
||||
it('refreshes catalog availability when starting checkout fails', async () => {
|
||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||
const notifyAvailabilityChanged = vi.spyOn(
|
||||
catalogAvailabilityService,
|
||||
'notifyAvailabilityChanged',
|
||||
);
|
||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||
|
||||
request.flush(
|
||||
{ message: 'No hay stock disponible.' },
|
||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||
);
|
||||
|
||||
await expect(purchasePromise).rejects.toBeTruthy();
|
||||
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
|
||||
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||
const notifyAvailabilityChanged = vi.spyOn(
|
||||
catalogAvailabilityService,
|
||||
'notifyAvailabilityChanged',
|
||||
);
|
||||
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||
|
||||
request.flush(
|
||||
{
|
||||
code: 'stock_reservation.expired',
|
||||
message: 'La reserva de stock venció.',
|
||||
},
|
||||
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||
);
|
||||
|
||||
await expect(purchasePromise).rejects.toBeTruthy();
|
||||
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves checkout timing fields when completing a purchase', async () => {
|
||||
const purchasePromise = service.completePurchase('desfile', 55);
|
||||
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
|
||||
const response = {
|
||||
status: 'pending_payment',
|
||||
expires_at: '2026-08-26T20:00:00.000Z',
|
||||
expires_in_seconds: 900,
|
||||
server_time: '2026-08-26T19:45:00.000Z',
|
||||
};
|
||||
|
||||
expect(request.request.method).toBe('POST');
|
||||
request.flush({ data: response });
|
||||
|
||||
await expect(purchasePromise).resolves.toEqual(response);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
||||
import { BaseApiService } from './base-api.service';
|
||||
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||
|
||||
export interface UpdatePurchaseCustomerPayload {
|
||||
dni: string;
|
||||
@@ -70,6 +71,32 @@ export type StartCheckoutPayload =
|
||||
|
||||
export interface PurchaseStatusResponse {
|
||||
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 {
|
||||
@@ -106,7 +133,6 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
||||
user_id: number;
|
||||
created_at: string | null;
|
||||
payment_method: string | null;
|
||||
expires_at: string | null;
|
||||
dni: string | null;
|
||||
transfer_payer_dni: string | null;
|
||||
telefono: string | null;
|
||||
@@ -124,24 +150,34 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CheckoutService extends BaseApiService {
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
|
||||
async startCheckout(
|
||||
tenantCode: string,
|
||||
payload: StartCheckoutPayload,
|
||||
): Promise<PurchaseDetailResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||
payload,
|
||||
),
|
||||
);
|
||||
try {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||
payload,
|
||||
),
|
||||
);
|
||||
|
||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||
|
||||
if (!purchase?.id) {
|
||||
throw new Error('Error al crear la compra.');
|
||||
if (!purchase?.id) {
|
||||
throw new Error('Error al crear la compra.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
} catch (error) {
|
||||
const responseBody = (error as { error?: unknown } | null)?.error;
|
||||
if (!isExpiredStockReservationResponse(responseBody)) {
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async generatePaymentIntent(
|
||||
@@ -186,25 +222,6 @@ export class CheckoutService extends BaseApiService {
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
||||
{},
|
||||
),
|
||||
);
|
||||
|
||||
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
||||
|
||||
if (!purchase) {
|
||||
throw new Error('Error al finalizar la compra.');
|
||||
}
|
||||
|
||||
return {
|
||||
status: purchase.status ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async submitPurchaseForReview(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
@@ -221,7 +238,7 @@ export class CheckoutService extends BaseApiService {
|
||||
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
||||
}
|
||||
|
||||
return { status: purchase.status ?? null };
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||
@@ -237,7 +254,7 @@ export class CheckoutService extends BaseApiService {
|
||||
throw new Error('Error al cancelar la compra.');
|
||||
}
|
||||
|
||||
return { status: purchase.status ?? null };
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async getPurchases(
|
||||
|
||||
@@ -180,7 +180,7 @@ export class CategoryItemsPageComponent {
|
||||
this.toastService.danger(message);
|
||||
|
||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
[qrPaymentAmount]="cartTotal()"
|
||||
[whatsappUrl]="whatsappUrl()"
|
||||
[transferValidationStatus]="transferValidationStatus()"
|
||||
[transferVerificationErrorTitle]="transferVerificationErrorTitle()"
|
||||
(paymentMethodChange)="selectPaymentMethod($event)"
|
||||
(copyTransferValue)="copyTransferValue($event.field, $event.value)"
|
||||
(cancelStep)="onCancel()"
|
||||
@@ -46,6 +47,17 @@
|
||||
</div>
|
||||
|
||||
<div class="checkout-page__cart-col">
|
||||
@if (checkoutRemainingTime(); as remainingTime) {
|
||||
<div
|
||||
class="checkout-page__mobile-countdown d-flex d-md-none align-items-baseline justify-content-center gap-3"
|
||||
role="timer"
|
||||
aria-label="Tiempo restante de compra"
|
||||
>
|
||||
<span class="checkout-page__mobile-countdown-label">Tiempo restante de compra:</span>
|
||||
<span class="checkout-page__mobile-countdown-value">{{ remainingTime }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<app-cart
|
||||
title="COMPRA"
|
||||
[items]="mappedCartItems()"
|
||||
|
||||
@@ -28,6 +28,24 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&__mobile-countdown {
|
||||
flex: 0 0 auto;
|
||||
margin-bottom: 1.5rem;
|
||||
color: var(--tenant-primary);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&__mobile-countdown-label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__mobile-countdown-value {
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
}
|
||||
|
||||
.checkout-page__loading {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
||||
import { CheckoutPageComponent } from './checkout-page.component';
|
||||
|
||||
describe('CheckoutPageComponent payment validation', () => {
|
||||
@@ -129,6 +130,35 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
return { fixture, component: fixture.componentInstance as any };
|
||||
}
|
||||
|
||||
it('does not expose an active countdown until the purchase timing is loaded', async () => {
|
||||
const countdown = TestBed.inject(CheckoutCountdownService);
|
||||
countdown.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: 600,
|
||||
server_time: new Date().toISOString(),
|
||||
});
|
||||
checkoutServiceStub.getPurchase.mockResolvedValue({
|
||||
id: 25,
|
||||
status: 'created',
|
||||
expires_at: '2026-08-27T15:10:00.000Z',
|
||||
expires_in_seconds: 600,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
items: [],
|
||||
subtotal: '0.00',
|
||||
total: '0.00',
|
||||
});
|
||||
routeParamMap = convertToParamMap({ id: 25 });
|
||||
|
||||
const { component } = createComponent();
|
||||
|
||||
expect(component.checkoutRemainingTime()).toBeNull();
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
expect(countdown.remainingSeconds()).toBe(600);
|
||||
expect(component.checkoutRemainingTime()).toBe('10:00');
|
||||
});
|
||||
|
||||
it('polls QR after five seconds and navigates only when payment is paid', async () => {
|
||||
checkoutServiceStub.getPurchase
|
||||
.mockResolvedValueOnce({ status: 'pending_payment' })
|
||||
@@ -195,7 +225,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||
it('polls a transfer every three seconds for one minute', async () => {
|
||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
@@ -205,14 +235,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(attempt);
|
||||
expect(component.transferValidationStatus()).toBe('checking');
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(57_000);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(19);
|
||||
expect(component.transferValidationStatus()).toBe('checking');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||
expect(component.transferValidationStatus()).toBe('error');
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
@@ -256,13 +284,43 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
await vi.advanceTimersByTimeAsync(12_000);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(20);
|
||||
expect(component.transferValidationStatus()).toBe('error');
|
||||
expect(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 () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
checkoutServiceStub.submitPurchaseForReview.mockRejectedValue(new Error('network error'));
|
||||
|
||||
@@ -16,8 +16,10 @@ import { firstValueFrom, startWith } from 'rxjs';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import {
|
||||
CheckoutService,
|
||||
PurchasePaymentCandidateReason,
|
||||
PurchaseDetailItemResponse,
|
||||
PurchaseDetailResponse,
|
||||
PurchaseStatusResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||
@@ -28,6 +30,7 @@ import { StepComponent } from '../../../../shared/components/stepper/step.compon
|
||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||
import { CheckoutDataStepComponent } from './checkout-data-step.component';
|
||||
import { CheckoutPaymentStepComponent } from './checkout-payment-step.component';
|
||||
import { CheckoutCountdownService } from '../../../../core/services/checkout-countdown.service';
|
||||
import {
|
||||
CheckoutForm,
|
||||
PaymentMethod,
|
||||
@@ -64,6 +67,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
private readonly router = inject(Router);
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly globalLoadingService = inject(GlobalLoadingService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
@@ -71,7 +75,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
private readonly qrPollingIntervalMs = 5_000;
|
||||
private readonly qrPollingMaxAttempts = 120;
|
||||
private readonly transferPollingIntervalMs = 3_000;
|
||||
private readonly transferPollingMaxAttempts = 209;
|
||||
private readonly transferPollingMaxAttempts = 20;
|
||||
|
||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
private qrPollingAttempts = 0;
|
||||
@@ -95,6 +99,27 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||
protected readonly isLoadingPurchase = signal(true);
|
||||
protected readonly checkoutStepIndex = signal(0);
|
||||
protected readonly checkoutRemainingTime = computed(() => {
|
||||
const purchase = this.createdPurchase();
|
||||
|
||||
if (
|
||||
!purchase ||
|
||||
(typeof purchase.expires_at !== 'string' && typeof purchase.expires_in_seconds !== 'number')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const remainingSeconds = this.checkoutCountdownService.remainingSeconds();
|
||||
|
||||
if (remainingSeconds === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(remainingSeconds / 60);
|
||||
const seconds = remainingSeconds % 60;
|
||||
|
||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
});
|
||||
protected readonly cartSubtotal = computed(() => {
|
||||
const purchase = this.createdPurchase();
|
||||
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||
@@ -135,6 +160,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly qrPaymentStatus = signal<QrPaymentStatus>('idle');
|
||||
protected readonly isCheckingQrPayment = signal(false);
|
||||
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(
|
||||
() =>
|
||||
this.tenantService
|
||||
@@ -228,6 +261,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
nombre_apellido: formValue.nombre,
|
||||
});
|
||||
this.createdPurchase.set(purchase);
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
this.stepper.next();
|
||||
|
||||
@@ -281,6 +315,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
if (!tenant || !purchaseId) {
|
||||
this.checkoutCountdownService.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -291,6 +326,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
await firstValueFrom(this.cartService.loadCart());
|
||||
this.createdPurchaseId.set(null);
|
||||
this.createdPurchase.set(null);
|
||||
this.checkoutCountdownService.clear();
|
||||
|
||||
this.navigationStarted = true;
|
||||
return true;
|
||||
@@ -299,11 +335,12 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
if (this.isStockReservationExpiredError(error)) {
|
||||
this.showRequestError(error, 'La reserva de stock venció.');
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
this.createdPurchaseId.set(null);
|
||||
this.createdPurchase.set(null);
|
||||
this.checkoutCountdownService.clear();
|
||||
this.navigationStarted = true;
|
||||
return true;
|
||||
}
|
||||
@@ -382,6 +419,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.transferDni.set(dni);
|
||||
this.stopTransferPolling();
|
||||
this.transferValidationStatus.set('idle');
|
||||
this.transferPrimaryCandidateReason.set(null);
|
||||
this.isGeneratingIntent.set(true);
|
||||
try {
|
||||
const response = await this.checkoutService
|
||||
@@ -438,6 +476,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.stopTransferPolling();
|
||||
this.hasSubmittedTransfer.set(true);
|
||||
this.transferValidationStatus.set('checking');
|
||||
this.transferPrimaryCandidateReason.set(null);
|
||||
this.transferPollingAttempts = 0;
|
||||
|
||||
const runId = this.transferPollingRunId;
|
||||
@@ -451,6 +490,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
this.captureTransferCandidateReason(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.navigateToPurchaseStatus(purchaseId);
|
||||
return;
|
||||
@@ -500,6 +542,9 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
this.captureTransferCandidateReason(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.navigateToPurchaseStatus(purchaseId);
|
||||
return;
|
||||
@@ -530,6 +575,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.scheduleTransferPoll(runId);
|
||||
}
|
||||
|
||||
private captureTransferCandidateReason(purchase: PurchaseStatusResponse): void {
|
||||
const reason = purchase.payment_verification?.primary?.reason;
|
||||
|
||||
if (reason) {
|
||||
this.transferPrimaryCandidateReason.set(reason);
|
||||
}
|
||||
}
|
||||
|
||||
private stopTransferPolling(): void {
|
||||
this.transferPollingRunId += 1;
|
||||
|
||||
@@ -586,6 +639,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.handleConfirmedPayment(purchaseId);
|
||||
return;
|
||||
@@ -659,6 +714,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.navigationStarted = true;
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
this.checkoutCountdownService.clear();
|
||||
|
||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||
}
|
||||
@@ -696,6 +752,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.createdPurchaseId.set(purchase.id);
|
||||
this.createdPurchase.set(purchase);
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
this.checkoutStepIndex.set(purchase.status === 'pending_payment' ? 1 : 0);
|
||||
|
||||
if (
|
||||
@@ -779,6 +836,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.navigationStarted = true;
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
this.checkoutCountdownService.clear();
|
||||
void this.router.navigate(['/checkout/status', purchaseId], {
|
||||
queryParams: { status: 'expired' },
|
||||
});
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
[validationStatus]="transferValidationStatus()"
|
||||
[paymentAmount]="qrPaymentAmount()"
|
||||
[whatsappUrl]="whatsappUrl()"
|
||||
[verificationErrorTitle]="transferVerificationErrorTitle()"
|
||||
(copyTransferValue)="requestCopy($event.field, $event.value)"
|
||||
(submitDni)="generateTransferIntent.emit($event)"
|
||||
(completePurchase)="complete.emit()"
|
||||
|
||||
@@ -33,6 +33,7 @@ export class CheckoutPaymentStepComponent {
|
||||
readonly qrPaymentAmount = input<number>(0);
|
||||
readonly whatsappUrl = input<string | null>(null);
|
||||
readonly transferValidationStatus = input<TransferValidationStatus>('idle');
|
||||
readonly transferVerificationErrorTitle = input<string | null>(null);
|
||||
|
||||
readonly paymentMethodChange = output<PaymentMethod>();
|
||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
<app-payment-verification-error
|
||||
[paymentAmount]="paymentAmount()"
|
||||
[whatsappUrl]="whatsappUrl()"
|
||||
[title]="verificationErrorTitle()"
|
||||
/>
|
||||
} @else {
|
||||
<div class="dni-form-container">
|
||||
|
||||
@@ -47,4 +47,23 @@ describe('CheckoutPaymentTransferComponent', () => {
|
||||
expect(whatsapp).toBeDefined();
|
||||
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a custom validation title for a near DNI candidate', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CheckoutPaymentTransferComponent],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||
fixture.componentRef.setInput('validationStatus', 'error');
|
||||
fixture.componentRef.setInput(
|
||||
'verificationErrorTitle',
|
||||
'El DNI no corresponde con el de la transferencia',
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain(
|
||||
'El DNI no corresponde con el de la transferencia',
|
||||
);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No pudimos verificar el pago de');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,6 +41,7 @@ export class CheckoutPaymentTransferComponent implements OnInit {
|
||||
readonly validationStatus = input<TransferValidationStatus>('idle');
|
||||
readonly paymentAmount = input<number>(0);
|
||||
readonly whatsappUrl = input<string | null>(null);
|
||||
readonly verificationErrorTitle = input<string | null>(null);
|
||||
|
||||
readonly copyTransferValue = output<{ field: TransferField; value: string }>();
|
||||
readonly submitDni = output<string>();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="payment-timeout__icon" aria-hidden="true">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</div>
|
||||
<h4 class="payment-timeout__title">No pudimos verificar el pago de {{ formattedAmount() }}.</h4>
|
||||
<h4 class="payment-timeout__title">{{ displayTitle() }}</h4>
|
||||
<p class="payment-timeout__message">Por favor contactate con nosotros para resolverlo.</p>
|
||||
@if (whatsappUrl()) {
|
||||
<app-button
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ButtonComponent } from '../../../../../../shared/components/button/butt
|
||||
export class PaymentVerificationErrorComponent {
|
||||
readonly paymentAmount = input<number>(0);
|
||||
readonly whatsappUrl = input<string | null>(null);
|
||||
readonly title = input<string | null>(null);
|
||||
|
||||
protected readonly formattedAmount = computed(() =>
|
||||
new Intl.NumberFormat('es-AR', {
|
||||
@@ -21,6 +22,9 @@ export class PaymentVerificationErrorComponent {
|
||||
maximumFractionDigits: 0,
|
||||
}).format(this.paymentAmount()),
|
||||
);
|
||||
protected readonly displayTitle = computed(
|
||||
() => this.title() ?? `No pudimos verificar el pago de ${this.formattedAmount()}.`,
|
||||
);
|
||||
|
||||
protected openWhatsApp(): void {
|
||||
const url = this.whatsappUrl();
|
||||
|
||||
@@ -17,7 +17,9 @@
|
||||
|
||||
<div class="status-content__section status-content__section--secondary">
|
||||
@if (ticketsRoute()) {
|
||||
<p class="status-content__message">A continuación, vas a poder ver los tickets que debés presentar en el evento.</p>
|
||||
<p class="status-content__message">
|
||||
A continuación, vas a poder ver los tickets que debés presentar en el evento.
|
||||
</p>
|
||||
|
||||
<app-button
|
||||
type="button"
|
||||
@@ -29,7 +31,9 @@
|
||||
<span>Mis tickets</span>
|
||||
</app-button>
|
||||
} @else if (whatsappUrl()) {
|
||||
<p class="status-content__message">Comunicate con nosotros para coordinar el envío.</p>
|
||||
<p class="status-content__message">
|
||||
Comunicate con nosotros para coordinar el envío.
|
||||
</p>
|
||||
|
||||
<app-button
|
||||
type="button"
|
||||
@@ -51,13 +55,21 @@
|
||||
<i class="fa-solid fa-clock"></i>
|
||||
</div>
|
||||
<h2 class="status-content__title">ESTAMOS VERIFICANDO TU PAGO</h2>
|
||||
<p class="status-content__subtitle">Tu compra ya fue registrada y estamos esperando la confirmación del pago.</p>
|
||||
<p class="status-content__subtitle">
|
||||
Tu compra ya fue registrada y estamos esperando la confirmación del pago.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<hr class="status-content__divider" />
|
||||
|
||||
<div class="status-content__section status-content__section--secondary">
|
||||
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
||||
@if (paymentIssueMessage()) {
|
||||
<p class="status-content__message">
|
||||
{{ paymentIssueMessage() }} Estamos revisando el pago.
|
||||
</p>
|
||||
} @else {
|
||||
<p class="status-content__message">Te avisaremos cuando el pago sea confirmado.</p>
|
||||
}
|
||||
</div>
|
||||
} @else if (status() === 'expired') {
|
||||
<div class="status-content__section status-content__section--primary">
|
||||
@@ -65,13 +77,17 @@
|
||||
<i class="fa-solid fa-clock"></i>
|
||||
</div>
|
||||
<h2 class="status-content__title">LA COMPRA VENCIÓ</h2>
|
||||
<p class="status-content__subtitle">El plazo de pago terminó y liberamos el stock reservado.</p>
|
||||
<p class="status-content__subtitle">
|
||||
El plazo de pago terminó y liberamos el stock reservado.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<hr class="status-content__divider" />
|
||||
|
||||
<div class="status-content__section status-content__section--secondary">
|
||||
<p class="status-content__message">Podés volver a la tienda e iniciar una nueva compra.</p>
|
||||
<p class="status-content__message">
|
||||
Podés volver a la tienda e iniciar una nueva compra.
|
||||
</p>
|
||||
</div>
|
||||
} @else if (status() === 'rejected') {
|
||||
<div class="status-content__section status-content__section--primary">
|
||||
@@ -79,7 +95,9 @@
|
||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||
</div>
|
||||
<h2 class="status-content__title">NO PUDIMOS CONFIRMAR EL PAGO</h2>
|
||||
<p class="status-content__subtitle">Revisá el medio de pago o comunicate con nosotros para continuar.</p>
|
||||
<p class="status-content__subtitle">
|
||||
Revisá el medio de pago o comunicate con nosotros para continuar.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<hr class="status-content__divider" />
|
||||
@@ -114,7 +132,9 @@
|
||||
<hr class="status-content__divider" />
|
||||
|
||||
<div class="status-content__section status-content__section--secondary">
|
||||
<p class="status-content__message">Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.</p>
|
||||
<p class="status-content__message">
|
||||
Volvé a ingresar más tarde. Si el problema sigue, comunicate con nosotros.
|
||||
</p>
|
||||
|
||||
@if (whatsappUrl()) {
|
||||
<div class="status-content__actions">
|
||||
|
||||
@@ -67,9 +67,13 @@ describe('PurchaseStatusPageComponent', () => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
async function render(hasGeneratedTickets: boolean, forcedStatus?: string) {
|
||||
async function render(
|
||||
hasGeneratedTickets: boolean,
|
||||
forcedStatus?: string,
|
||||
purchaseResponse = purchase(hasGeneratedTickets),
|
||||
) {
|
||||
const checkoutService = {
|
||||
getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
|
||||
getPurchase: vi.fn().mockResolvedValue(purchaseResponse),
|
||||
withCustomLoading() {
|
||||
return this;
|
||||
},
|
||||
@@ -91,9 +95,7 @@ describe('PurchaseStatusPageComponent', () => {
|
||||
useValue: {
|
||||
snapshot: {
|
||||
paramMap: convertToParamMap({ id: '42' }),
|
||||
queryParamMap: convertToParamMap(
|
||||
forcedStatus ? { status: forcedStatus } : {},
|
||||
),
|
||||
queryParamMap: convertToParamMap(forcedStatus ? { status: forcedStatus } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -159,6 +161,30 @@ describe('PurchaseStatusPageComponent', () => {
|
||||
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 () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import {
|
||||
CheckoutService,
|
||||
PurchasePaymentVerificationResponse,
|
||||
PurchaseStatusResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
@@ -48,6 +49,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly isLoading = signal(true);
|
||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||
protected readonly hasGeneratedTickets = signal(false);
|
||||
protected readonly paymentIssueMessage = signal<string | null>(null);
|
||||
protected readonly ticketsRoute = computed(() => {
|
||||
if (!this.hasGeneratedTickets()) {
|
||||
return null;
|
||||
@@ -105,6 +107,7 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
||||
const status = this.resolveStatus(purchase);
|
||||
this.status.set(status);
|
||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||
this.paymentIssueMessage.set(this.resolvePaymentIssueMessage(purchase.payment_verification));
|
||||
|
||||
if (status === 'approved') {
|
||||
this.cartService.clearCart();
|
||||
@@ -169,6 +172,43 @@ export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
private resolvePaymentIssueMessage(
|
||||
verification?: PurchasePaymentVerificationResponse,
|
||||
): string | null {
|
||||
const primary = verification?.primary;
|
||||
|
||||
if (!primary) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const primaryMessage = (() => {
|
||||
switch (primary.reason) {
|
||||
case 'ambiguous_exact_match':
|
||||
return 'Encontramos una transferencia que también coincide con otra compra.';
|
||||
case 'exact_dni_near_amount':
|
||||
return `El DNI coincide, pero el monto transferido tiene una diferencia de ${this.formatCurrency(primary.amount_difference)}.`;
|
||||
case 'exact_amount_near_dni':
|
||||
return primary.dni_distance === null
|
||||
? 'El monto coincide, pero el DNI del pagador es diferente.'
|
||||
: `El monto coincide, pero el DNI del pagador presenta ${primary.dni_distance} ${primary.dni_distance === 1 ? 'diferencia' : 'diferencias'} de escritura.`;
|
||||
}
|
||||
})();
|
||||
|
||||
if (verification.candidate_count > 1) {
|
||||
return `Encontramos ${verification.candidate_count} transferencias posibles. ${primaryMessage}`;
|
||||
}
|
||||
|
||||
return primaryMessage;
|
||||
}
|
||||
|
||||
private formatCurrency(amount: string): string {
|
||||
return new Intl.NumberFormat('es-AR', {
|
||||
style: 'currency',
|
||||
currency: 'ARS',
|
||||
maximumFractionDigits: 2,
|
||||
}).format(Number(amount));
|
||||
}
|
||||
|
||||
private isPurchaseExpiredError(error: unknown): boolean {
|
||||
if (typeof error !== 'object' || error === null || !('error' in error)) {
|
||||
return false;
|
||||
|
||||
@@ -212,7 +212,7 @@ export class SearchPageComponent {
|
||||
this.toastService.danger(message);
|
||||
|
||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
|
||||
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||
this.toastService.danger(error.error.message);
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
return;
|
||||
|
||||
@@ -330,7 +330,7 @@ export class CartComponent {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cartService.loadCart().subscribe({
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 30px 20px;
|
||||
overflow: hidden;
|
||||
overflow: visible;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 7px;
|
||||
|
||||
@@ -6,6 +6,15 @@
|
||||
|
||||
@import '../node_modules/bootstrap/scss/bootstrap';
|
||||
|
||||
html,
|
||||
body,
|
||||
app-root {
|
||||
width: 100%;
|
||||
min-height: 100%;
|
||||
margin: 0;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
:root,
|
||||
app-root {
|
||||
--border-color: #dddddd;
|
||||
|
||||
Reference in New Issue
Block a user