Compare commits
18 Commits
homo_exper
...
fix/cart-e
| Author | SHA1 | Date | |
|---|---|---|---|
| eb3a084d18 | |||
| e4f9d38e82 | |||
| b0e2efbdd1 | |||
| 1ad7bccf16 | |||
| a1d6585b54 | |||
| 38d03588b1 | |||
| 8e987d0ce6 | |||
| e171b9a233 | |||
| 643d43adea | |||
| d89d01b511 | |||
| eeb245209b | |||
| 9d3754c2d8 | |||
| 6f4aa3b1bd | |||
| 2b342ec235 | |||
| d06b146104 | |||
| f4e0a9e028 | |||
| 8c2b738806 | |||
| 1362d0c163 |
@@ -152,9 +152,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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()) {
|
||||
@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__category-menu">
|
||||
<button
|
||||
type="button"
|
||||
@@ -175,18 +175,7 @@
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
</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>
|
||||
|
||||
@@ -10,26 +10,6 @@
|
||||
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,13 +1,4 @@
|
||||
import {
|
||||
Component,
|
||||
computed,
|
||||
ElementRef,
|
||||
HostListener,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { Component, 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';
|
||||
@@ -49,7 +40,6 @@ 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>();
|
||||
@@ -63,18 +53,6 @@ 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,7 +13,6 @@
|
||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||
[displayCart]="displayCart()"
|
||||
[cartDisabled]="isCheckoutRoute()"
|
||||
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
||||
(cartClick)="onCartClick()"
|
||||
(ticketsClick)="onTicketsClick()"
|
||||
(loginClick)="onLoginClick()"
|
||||
|
||||
@@ -24,7 +24,6 @@ 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 = {
|
||||
@@ -151,7 +150,6 @@ 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>;
|
||||
|
||||
@@ -159,7 +157,6 @@ 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 = {
|
||||
@@ -218,12 +215,6 @@ describe('StoreLayoutComponent', () => {
|
||||
provide: CheckoutService,
|
||||
useValue: checkoutServiceStub,
|
||||
},
|
||||
{
|
||||
provide: CheckoutCountdownService,
|
||||
useValue: {
|
||||
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
});
|
||||
@@ -280,22 +271,6 @@ 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,7 +24,6 @@ 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',
|
||||
@@ -43,7 +42,6 @@ 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);
|
||||
@@ -51,7 +49,6 @@ 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);
|
||||
@@ -290,7 +287,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
this.toastService.danger(message);
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,20 +83,6 @@ 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,19 +34,14 @@ export class CartService extends BaseApiService {
|
||||
});
|
||||
}
|
||||
|
||||
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
||||
loadCart(): Observable<Cart> {
|
||||
return this.http
|
||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => response.data),
|
||||
tap((cart) => {
|
||||
this.cartState.set(cart);
|
||||
if (refreshCatalogAvailability) {
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
}
|
||||
}),
|
||||
tap((cart) => this.cartState.set(cart)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
CatalogItemDetail,
|
||||
CatalogVariantOptionsResponse,
|
||||
CategoryItemsResponse,
|
||||
Product,
|
||||
} from './catalog.interface';
|
||||
|
||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||
@@ -32,6 +33,12 @@ 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`);
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CheckoutCountdownService } from './checkout-countdown.service';
|
||||
|
||||
describe('CheckoutCountdownService', () => {
|
||||
let service: CheckoutCountdownService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
|
||||
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
|
||||
service = TestBed.inject(CheckoutCountdownService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
service.clear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('counts down from the checkout server timing without depending on the client clock', () => {
|
||||
service.synchronize({
|
||||
expires_at: '2026-08-27T15:10:00.000Z',
|
||||
expires_in_seconds: 600,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(service.remainingSeconds()).toBe(600);
|
||||
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
expect(service.remainingSeconds()).toBe(599);
|
||||
});
|
||||
|
||||
it('recalculates against the deadline after a delayed browser interval', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: 10,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
expect(service.remainingSeconds()).toBe(2);
|
||||
});
|
||||
|
||||
it('clears the countdown when checkout has no expiration', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: null,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(service.remainingSeconds()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
|
||||
service.synchronize({
|
||||
expires_at: null,
|
||||
expires_in_seconds: 10,
|
||||
server_time: '2026-08-27T15:00:00.000Z',
|
||||
});
|
||||
|
||||
service.synchronize({});
|
||||
|
||||
expect(service.remainingSeconds()).toBe(10);
|
||||
});
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import { Injectable, OnDestroy, signal } from '@angular/core';
|
||||
|
||||
export interface CheckoutTiming {
|
||||
expires_at: string | null;
|
||||
expires_in_seconds: number | null;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CheckoutCountdownService implements OnDestroy {
|
||||
private readonly remainingSecondsState = signal<number | null>(null);
|
||||
private deadlineMs: number | null = null;
|
||||
private intervalId: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
|
||||
|
||||
synchronize(timing: Partial<CheckoutTiming>): void {
|
||||
const remainingSeconds = this.resolveRemainingSeconds(timing);
|
||||
|
||||
if (remainingSeconds === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (remainingSeconds === null) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
this.stopInterval();
|
||||
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
|
||||
this.updateRemainingSeconds();
|
||||
|
||||
if (remainingSeconds > 0) {
|
||||
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.stopInterval();
|
||||
this.deadlineMs = null;
|
||||
this.remainingSecondsState.set(null);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.clear();
|
||||
}
|
||||
|
||||
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
|
||||
if (timing.expires_at === null && timing.expires_in_seconds === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const expiresAt =
|
||||
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
|
||||
const serverTime =
|
||||
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
|
||||
|
||||
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
|
||||
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
|
||||
}
|
||||
|
||||
if (
|
||||
typeof timing.expires_in_seconds === 'number' &&
|
||||
Number.isFinite(timing.expires_in_seconds)
|
||||
) {
|
||||
return Math.max(0, Math.ceil(timing.expires_in_seconds));
|
||||
}
|
||||
|
||||
if (Number.isFinite(expiresAt)) {
|
||||
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private updateRemainingSeconds(): void {
|
||||
if (this.deadlineMs === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
|
||||
this.remainingSecondsState.set(remainingSeconds);
|
||||
|
||||
if (remainingSeconds === 0) {
|
||||
this.stopInterval();
|
||||
}
|
||||
}
|
||||
|
||||
private stopInterval(): void {
|
||||
if (this.intervalId !== null) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/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 { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||
import { CheckoutService } from './checkout.service';
|
||||
|
||||
describe('CheckoutService', () => {
|
||||
@@ -39,59 +38,4 @@ 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,11 +1,10 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { 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;
|
||||
@@ -71,9 +70,6 @@ export type StartCheckoutPayload =
|
||||
|
||||
export interface PurchaseStatusResponse {
|
||||
status: string | null;
|
||||
expires_at: string | null;
|
||||
expires_in_seconds: number | null;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
||||
@@ -110,6 +106,7 @@ 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;
|
||||
@@ -127,34 +124,24 @@ 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> {
|
||||
try {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||
payload,
|
||||
),
|
||||
);
|
||||
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.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
} catch (error) {
|
||||
const responseBody = (error as { error?: unknown } | null)?.error;
|
||||
if (!isExpiredStockReservationResponse(responseBody)) {
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
}
|
||||
throw error;
|
||||
if (!purchase?.id) {
|
||||
throw new Error('Error al crear la compra.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async generatePaymentIntent(
|
||||
@@ -199,6 +186,25 @@ 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,
|
||||
@@ -215,7 +221,7 @@ export class CheckoutService extends BaseApiService {
|
||||
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> {
|
||||
@@ -231,7 +237,7 @@ export class CheckoutService extends BaseApiService {
|
||||
throw new Error('Error al cancelar la compra.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
return { status: purchase.status ?? null };
|
||||
}
|
||||
|
||||
async getPurchases(
|
||||
|
||||
@@ -180,7 +180,7 @@ export class CategoryItemsPageComponent {
|
||||
this.toastService.danger(message);
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -46,17 +46,6 @@
|
||||
</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,24 +28,6 @@
|
||||
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,7 +14,6 @@ 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', () => {
|
||||
@@ -130,35 +129,6 @@ 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' })
|
||||
|
||||
@@ -28,7 +28,6 @@ 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,
|
||||
@@ -65,7 +64,6 @@ 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);
|
||||
@@ -97,28 +95,6 @@ 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;
|
||||
@@ -252,7 +228,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
nombre_apellido: formValue.nombre,
|
||||
});
|
||||
this.createdPurchase.set(purchase);
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
this.stepper.next();
|
||||
|
||||
@@ -306,7 +281,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
if (!tenant || !purchaseId) {
|
||||
this.checkoutCountdownService.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -317,7 +291,6 @@ 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;
|
||||
@@ -326,12 +299,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
if (this.isStockReservationExpiredError(error)) {
|
||||
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),
|
||||
});
|
||||
this.createdPurchaseId.set(null);
|
||||
this.createdPurchase.set(null);
|
||||
this.checkoutCountdownService.clear();
|
||||
this.navigationStarted = true;
|
||||
return true;
|
||||
}
|
||||
@@ -479,8 +451,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.navigateToPurchaseStatus(purchaseId);
|
||||
return;
|
||||
@@ -530,8 +500,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.navigateToPurchaseStatus(purchaseId);
|
||||
return;
|
||||
@@ -618,8 +586,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.checkoutCountdownService.synchronize(purchase);
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.handleConfirmedPayment(purchaseId);
|
||||
return;
|
||||
@@ -693,7 +659,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.navigationStarted = true;
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
this.checkoutCountdownService.clear();
|
||||
|
||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||
}
|
||||
@@ -731,7 +696,6 @@ 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 (
|
||||
@@ -815,7 +779,6 @@ 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' },
|
||||
});
|
||||
|
||||
@@ -212,7 +212,7 @@ export class SearchPageComponent {
|
||||
this.toastService.danger(message);
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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(true).subscribe({
|
||||
this.cartService.loadCart().subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
return;
|
||||
|
||||
@@ -330,7 +330,7 @@ export class CartComponent {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cartService.loadCart(true).subscribe({
|
||||
this.cartService.loadCart().subscribe({
|
||||
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user