refactor(checkout): cancel purchase without reloading cart
This commit is contained in:
@@ -51,7 +51,7 @@
|
||||
[allowModify]="true"
|
||||
[showModifyWhenReadonly]="true"
|
||||
[modifyAsAction]="true"
|
||||
[editingDisabled]="isRestoringCart()"
|
||||
[editingDisabled]="isCancellingPurchase()"
|
||||
backgroundColor="transparent"
|
||||
(modify)="onModifyPurchase()"
|
||||
/>
|
||||
|
||||
@@ -3,11 +3,9 @@ import { signal } from '@angular/core';
|
||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
||||
import { of } from 'rxjs';
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||
@@ -26,12 +24,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
getPurchase: ReturnType<typeof vi.fn>;
|
||||
withCustomLoading: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let cartServiceStub: {
|
||||
cart: ReturnType<typeof signal>;
|
||||
isUpdating: ReturnType<typeof signal<boolean>>;
|
||||
loadCart: ReturnType<typeof vi.fn>;
|
||||
clearCart: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let routerStub: { navigate: ReturnType<typeof vi.fn> };
|
||||
let toastServiceStub: { danger: ReturnType<typeof vi.fn> };
|
||||
let globalLoadingServiceStub: {
|
||||
@@ -75,27 +67,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
withCustomLoading: vi.fn(),
|
||||
};
|
||||
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
|
||||
cartServiceStub = {
|
||||
cart: signal({
|
||||
id: 10,
|
||||
tenant_codigo: 'tenant-test',
|
||||
status: 'active',
|
||||
items: [],
|
||||
subtotal: '0.00',
|
||||
}),
|
||||
isUpdating: signal(false),
|
||||
loadCart: vi.fn().mockReturnValue(of({})),
|
||||
clearCart: vi.fn(),
|
||||
};
|
||||
cartServiceStub.clearCart.mockImplementation(() => {
|
||||
cartServiceStub.cart.set({
|
||||
id: null,
|
||||
tenant_codigo: 'tenant-test',
|
||||
status: 'active',
|
||||
items: [],
|
||||
subtotal: '0.00',
|
||||
});
|
||||
});
|
||||
routerStub = { navigate: vi.fn() };
|
||||
toastServiceStub = { danger: vi.fn() };
|
||||
globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() };
|
||||
@@ -117,7 +88,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
providers: [
|
||||
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
||||
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
|
||||
{ provide: CartService, useValue: cartServiceStub },
|
||||
{ provide: TenantService, useValue: { tenant: tenantState } },
|
||||
{ provide: AuthService, useValue: { user: authUserState } },
|
||||
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
|
||||
@@ -167,7 +137,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -239,7 +208,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||
expect(component.transferValidationStatus()).toBe('error');
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -252,7 +220,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
});
|
||||
|
||||
@@ -267,7 +234,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||
expect(component.transferValidationStatus()).toBe('error');
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -476,7 +442,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
});
|
||||
|
||||
it('shows the API error in a toast when restoring the cart fails', async () => {
|
||||
it('shows the API error in a toast when cancelling the purchase fails', async () => {
|
||||
const message = 'La compra venció. Iniciá una nueva compra.';
|
||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||
error: { code: 'purchase.expired', message },
|
||||
@@ -489,10 +455,10 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||
expect(component.isRestoringCart()).toBe(false);
|
||||
expect(component.isCancellingPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it('restores the previous cart and opens it when Modificar is clicked', async () => {
|
||||
it('cancels the current purchase and opens the active cart when Modificar is clicked', async () => {
|
||||
let finishNavigation!: (navigated: boolean) => void;
|
||||
routerStub.navigate.mockReturnValue(
|
||||
new Promise<boolean>((resolve) => {
|
||||
@@ -530,7 +496,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
|
||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||
expect(component.createdPurchaseId()).toBeNull();
|
||||
expect(component.createdPurchase()).toBeNull();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
|
||||
@@ -544,7 +509,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
|
||||
await component.canDeactivate();
|
||||
|
||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('updates customer data on the existing purchase before payment', async () => {
|
||||
@@ -581,20 +545,18 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(component.stepper.next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('restores the cart when navigating away from checkout', async () => {
|
||||
it('cancels the current purchase when navigating away from checkout', async () => {
|
||||
const { component } = createComponent();
|
||||
|
||||
await expect(component.canDeactivate()).resolves.toBe(true);
|
||||
|
||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(component.createdPurchaseId()).toBeNull();
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('prevents leaving checkout when the cart cannot be restored', async () => {
|
||||
it('prevents leaving checkout when the purchase cannot be cancelled', async () => {
|
||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||
error: { message: 'No se pudo cancelar la compra.' },
|
||||
});
|
||||
@@ -602,7 +564,6 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
|
||||
await expect(component.canDeactivate()).resolves.toBe(false);
|
||||
|
||||
expect(cartServiceStub.loadCart).not.toHaveBeenCalled();
|
||||
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo cancelar la compra.');
|
||||
expect(component.createdPurchaseId()).toBe(25);
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { FormBuilder, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { firstValueFrom, startWith } from 'rxjs';
|
||||
import { startWith } from 'rxjs';
|
||||
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import {
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
PurchaseDetailResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||
@@ -65,7 +64,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly globalLoadingService = inject(GlobalLoadingService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly qrPollingIntervalMs = 5_000;
|
||||
@@ -81,7 +79,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
private transferPollingRunId = 0;
|
||||
private paymentMethodRequestId = 0;
|
||||
private navigationStarted = false;
|
||||
private restoreCartPromise: Promise<boolean> | null = null;
|
||||
private cancelPurchasePromise: Promise<boolean> | null = null;
|
||||
|
||||
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
||||
|
||||
@@ -123,7 +121,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly transferDni = signal<string>('');
|
||||
|
||||
protected readonly isUpdatingPurchase = signal(false);
|
||||
protected readonly isRestoringCart = signal(false);
|
||||
protected readonly isCancellingPurchase = signal(false);
|
||||
protected readonly createdPurchaseId = signal<number | null>(null);
|
||||
protected readonly isGeneratingIntent = signal(false);
|
||||
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
|
||||
@@ -189,14 +187,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
protected async onModifyPurchase(): Promise<void> {
|
||||
if (this.isRestoringCart()) {
|
||||
if (this.isCancellingPurchase()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.globalLoadingService.start();
|
||||
try {
|
||||
const restored = await this.restoreCheckoutCart();
|
||||
if (!restored) return;
|
||||
const cancelled = await this.cancelCurrentPurchase();
|
||||
if (!cancelled) return;
|
||||
|
||||
await this.router.navigate(['/'], {
|
||||
queryParams: { openCart: true },
|
||||
@@ -245,8 +243,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
|
||||
if (this.restoreCartPromise) {
|
||||
return this.restoreCartPromise;
|
||||
if (this.cancelPurchasePromise) {
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
if (this.navigationStarted) {
|
||||
@@ -255,53 +253,46 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.globalLoadingService.start();
|
||||
try {
|
||||
return await this.restoreCheckoutCart();
|
||||
return await this.cancelCurrentPurchase();
|
||||
} finally {
|
||||
this.globalLoadingService.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private restoreCheckoutCart(): Promise<boolean> {
|
||||
if (this.restoreCartPromise) {
|
||||
return this.restoreCartPromise;
|
||||
private cancelCurrentPurchase(): Promise<boolean> {
|
||||
if (this.cancelPurchasePromise) {
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
this.restoreCartPromise = this.performCartRestore().finally(() => {
|
||||
this.restoreCartPromise = null;
|
||||
this.cancelPurchasePromise = this.performPurchaseCancellation().finally(() => {
|
||||
this.cancelPurchasePromise = null;
|
||||
});
|
||||
|
||||
return this.restoreCartPromise;
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
private async performCartRestore(): Promise<boolean> {
|
||||
private async performPurchaseCancellation(): Promise<boolean> {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
if (!tenant || !purchaseId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
this.isRestoringCart.set(true);
|
||||
this.isCancellingPurchase.set(true);
|
||||
|
||||
try {
|
||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
||||
this.createdPurchaseId.set(null);
|
||||
this.createdPurchase.set(null);
|
||||
|
||||
try {
|
||||
await firstValueFrom(this.cartService.loadCart());
|
||||
} catch (error) {
|
||||
console.error('Failed to load the restored cart:', error);
|
||||
this.showRequestError(error, 'La compra se canceló, pero no se pudo cargar el carrito.');
|
||||
}
|
||||
|
||||
this.navigationStarted = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to restore the checkout cart:', error);
|
||||
this.showRequestError(error, 'No se pudo recuperar el carrito.');
|
||||
console.error('Failed to cancel the current purchase:', error);
|
||||
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
||||
return false;
|
||||
} finally {
|
||||
this.isRestoringCart.set(false);
|
||||
this.isCancellingPurchase.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user