refactor(checkout): cancel purchase without reloading cart

This commit is contained in:
2026-08-21 13:42:59 -03:00
parent 69c836a578
commit 02ff829c06
3 changed files with 26 additions and 74 deletions

View File

@@ -51,7 +51,7 @@
[allowModify]="true" [allowModify]="true"
[showModifyWhenReadonly]="true" [showModifyWhenReadonly]="true"
[modifyAsAction]="true" [modifyAsAction]="true"
[editingDisabled]="isRestoringCart()" [editingDisabled]="isCancellingPurchase()"
backgroundColor="transparent" backgroundColor="transparent"
(modify)="onModifyPurchase()" (modify)="onModifyPurchase()"
/> />

View File

@@ -3,11 +3,9 @@ import { signal } from '@angular/core';
import { getTestBed, TestBed } from '@angular/core/testing'; import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router'; import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
import { of } from 'rxjs';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { CheckoutService } from '../../../../core/services/checkout.service'; import { CheckoutService } from '../../../../core/services/checkout.service';
import { CatalogService } from '../../../../core/services/catalog/catalog.service'; import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service'; import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
@@ -26,12 +24,6 @@ describe('CheckoutPageComponent payment validation', () => {
getPurchase: ReturnType<typeof vi.fn>; getPurchase: ReturnType<typeof vi.fn>;
withCustomLoading: 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 routerStub: { navigate: ReturnType<typeof vi.fn> };
let toastServiceStub: { danger: ReturnType<typeof vi.fn> }; let toastServiceStub: { danger: ReturnType<typeof vi.fn> };
let globalLoadingServiceStub: { let globalLoadingServiceStub: {
@@ -75,27 +67,6 @@ describe('CheckoutPageComponent payment validation', () => {
withCustomLoading: vi.fn(), withCustomLoading: vi.fn(),
}; };
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub); 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() }; routerStub = { navigate: vi.fn() };
toastServiceStub = { danger: vi.fn() }; toastServiceStub = { danger: vi.fn() };
globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() }; globalLoadingServiceStub = { start: vi.fn(), stop: vi.fn() };
@@ -117,7 +88,6 @@ describe('CheckoutPageComponent payment validation', () => {
providers: [ providers: [
{ provide: CheckoutService, useValue: checkoutServiceStub }, { provide: CheckoutService, useValue: checkoutServiceStub },
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } }, { provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
{ provide: CartService, useValue: cartServiceStub },
{ provide: TenantService, useValue: { tenant: tenantState } }, { provide: TenantService, useValue: { tenant: tenantState } },
{ provide: AuthService, useValue: { user: authUserState } }, { provide: AuthService, useValue: { user: authUserState } },
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub }, { provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
@@ -167,7 +137,6 @@ describe('CheckoutPageComponent payment validation', () => {
await vi.advanceTimersByTimeAsync(5_000); await vi.advanceTimersByTimeAsync(5_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(2);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledTimes(1);
}); });
@@ -239,7 +208,6 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25); expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
@@ -252,7 +220,6 @@ describe('CheckoutPageComponent payment validation', () => {
await vi.advanceTimersByTimeAsync(3_000); await vi.advanceTimersByTimeAsync(3_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
@@ -267,7 +234,6 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4); expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
expect(component.transferValidationStatus()).toBe('error'); expect(component.transferValidationStatus()).toBe('error');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
}); });
@@ -476,7 +442,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
}); });
it('shows the API error in a toast when 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.'; const message = 'La compra venció. Iniciá una nueva compra.';
checkoutServiceStub.cancelPurchase.mockRejectedValue({ checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { code: 'purchase.expired', message }, error: { code: 'purchase.expired', message },
@@ -489,10 +455,10 @@ describe('CheckoutPageComponent payment validation', () => {
expect(routerStub.navigate).not.toHaveBeenCalled(); expect(routerStub.navigate).not.toHaveBeenCalled();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).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; let finishNavigation!: (navigated: boolean) => void;
routerStub.navigate.mockReturnValue( routerStub.navigate.mockReturnValue(
new Promise<boolean>((resolve) => { new Promise<boolean>((resolve) => {
@@ -530,7 +496,6 @@ describe('CheckoutPageComponent payment validation', () => {
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled(); expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(component.createdPurchaseId()).toBeNull(); expect(component.createdPurchaseId()).toBeNull();
expect(component.createdPurchase()).toBeNull(); expect(component.createdPurchase()).toBeNull();
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], { expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
@@ -544,7 +509,6 @@ describe('CheckoutPageComponent payment validation', () => {
await component.canDeactivate(); await component.canDeactivate();
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
}); });
it('updates customer data on the existing purchase before payment', async () => { it('updates customer data on the existing purchase before payment', async () => {
@@ -581,20 +545,18 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.stepper.next).toHaveBeenCalledOnce(); 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(); const { component } = createComponent();
await expect(component.canDeactivate()).resolves.toBe(true); await expect(component.canDeactivate()).resolves.toBe(true);
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25); expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(component.createdPurchaseId()).toBeNull(); expect(component.createdPurchaseId()).toBeNull();
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce(); expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
expect(globalLoadingServiceStub.stop).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({ checkoutServiceStub.cancelPurchase.mockRejectedValue({
error: { message: 'No se pudo cancelar la compra.' }, error: { message: 'No se pudo cancelar la compra.' },
}); });
@@ -602,7 +564,6 @@ describe('CheckoutPageComponent payment validation', () => {
await expect(component.canDeactivate()).resolves.toBe(false); await expect(component.canDeactivate()).resolves.toBe(false);
expect(cartServiceStub.loadCart).not.toHaveBeenCalled();
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo cancelar la compra.'); expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo cancelar la compra.');
expect(component.createdPurchaseId()).toBe(25); expect(component.createdPurchaseId()).toBe(25);
}); });

View File

@@ -11,7 +11,7 @@ import {
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { firstValueFrom, startWith } from 'rxjs'; import { startWith } from 'rxjs';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { import {
@@ -20,7 +20,6 @@ import {
PurchaseDetailResponse, PurchaseDetailResponse,
} from '../../../../core/services/checkout.service'; } from '../../../../core/services/checkout.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service'; import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component'; 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 tenantService = inject(TenantService);
private readonly checkoutService = inject(CheckoutService); private readonly checkoutService = inject(CheckoutService);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
private readonly cartService = inject(CartService);
private readonly globalLoadingService = inject(GlobalLoadingService); private readonly globalLoadingService = inject(GlobalLoadingService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly qrPollingIntervalMs = 5_000; private readonly qrPollingIntervalMs = 5_000;
@@ -81,7 +79,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
private transferPollingRunId = 0; private transferPollingRunId = 0;
private paymentMethodRequestId = 0; private paymentMethodRequestId = 0;
private navigationStarted = false; private navigationStarted = false;
private restoreCartPromise: Promise<boolean> | null = null; private cancelPurchasePromise: Promise<boolean> | null = null;
@ViewChild(StepperComponent) stepper!: StepperComponent; @ViewChild(StepperComponent) stepper!: StepperComponent;
@@ -123,7 +121,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
protected readonly transferDni = signal<string>(''); protected readonly transferDni = signal<string>('');
protected readonly isUpdatingPurchase = signal(false); protected readonly isUpdatingPurchase = signal(false);
protected readonly isRestoringCart = signal(false); protected readonly isCancellingPurchase = signal(false);
protected readonly createdPurchaseId = signal<number | null>(null); protected readonly createdPurchaseId = signal<number | null>(null);
protected readonly isGeneratingIntent = signal(false); protected readonly isGeneratingIntent = signal(false);
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent()); protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
@@ -189,14 +187,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
} }
protected async onModifyPurchase(): Promise<void> { protected async onModifyPurchase(): Promise<void> {
if (this.isRestoringCart()) { if (this.isCancellingPurchase()) {
return; return;
} }
this.globalLoadingService.start(); this.globalLoadingService.start();
try { try {
const restored = await this.restoreCheckoutCart(); const cancelled = await this.cancelCurrentPurchase();
if (!restored) return; if (!cancelled) return;
await this.router.navigate(['/'], { await this.router.navigate(['/'], {
queryParams: { openCart: true }, queryParams: { openCart: true },
@@ -245,8 +243,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.stopQrPolling(); this.stopQrPolling();
this.stopTransferPolling(); this.stopTransferPolling();
if (this.restoreCartPromise) { if (this.cancelPurchasePromise) {
return this.restoreCartPromise; return this.cancelPurchasePromise;
} }
if (this.navigationStarted) { if (this.navigationStarted) {
@@ -255,53 +253,46 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
this.globalLoadingService.start(); this.globalLoadingService.start();
try { try {
return await this.restoreCheckoutCart(); return await this.cancelCurrentPurchase();
} finally { } finally {
this.globalLoadingService.stop(); this.globalLoadingService.stop();
} }
} }
private restoreCheckoutCart(): Promise<boolean> { private cancelCurrentPurchase(): Promise<boolean> {
if (this.restoreCartPromise) { if (this.cancelPurchasePromise) {
return this.restoreCartPromise; return this.cancelPurchasePromise;
} }
this.restoreCartPromise = this.performCartRestore().finally(() => { this.cancelPurchasePromise = this.performPurchaseCancellation().finally(() => {
this.restoreCartPromise = null; 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 tenant = this.tenantService.tenant();
const purchaseId = this.createdPurchaseId(); const purchaseId = this.createdPurchaseId();
if (!tenant || !purchaseId) { if (!tenant || !purchaseId) {
return true; return true;
} }
this.isRestoringCart.set(true); this.isCancellingPurchase.set(true);
try { try {
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId); await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
this.createdPurchaseId.set(null); this.createdPurchaseId.set(null);
this.createdPurchase.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; this.navigationStarted = true;
return true; return true;
} catch (error) { } catch (error) {
console.error('Failed to restore the checkout cart:', error); console.error('Failed to cancel the current purchase:', error);
this.showRequestError(error, 'No se pudo recuperar el carrito.'); this.showRequestError(error, 'No se pudo cancelar la compra.');
return false; return false;
} finally { } finally {
this.isRestoringCart.set(false); this.isCancellingPurchase.set(false);
} }
} }