Compare commits
8 Commits
56e011bc7a
...
fix/expira
| Author | SHA1 | Date | |
|---|---|---|---|
| 4251ca8a8a | |||
| cfa1091116 | |||
| d0b1607ff4 | |||
| 92546a28c0 | |||
| ce26fb5d1a | |||
| 38a57adf55 | |||
| e1d9590905 | |||
| 00a01e1a8e |
@@ -22,14 +22,18 @@
|
|||||||
|
|
||||||
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
||||||
<div class="d-grid gap-2 store-layout__contact-details">
|
<div class="d-grid gap-2 store-layout__contact-details">
|
||||||
|
@if (address) {
|
||||||
<div class="d-flex align-items-center gap-2">
|
<div class="d-flex align-items-center gap-2">
|
||||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||||
<span>Av. San Lorenzo 1542, Rosario</span>
|
<span>{{ address }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
@if (phone) {
|
||||||
<div class="d-flex align-items-center gap-2">
|
<div class="d-flex align-items-center gap-2">
|
||||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||||
<span>54 9 (0341) 6658247</span>
|
<span>{{ phone }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
||||||
|
|||||||
@@ -27,5 +27,7 @@ export class StoreFooterComponent {
|
|||||||
@Input() logoUrl: string | null = null;
|
@Input() logoUrl: string | null = null;
|
||||||
@Input() backgroundImageUrl: string | null = null;
|
@Input() backgroundImageUrl: string | null = null;
|
||||||
@Input() storeName: string | null = null;
|
@Input() storeName: string | null = null;
|
||||||
|
@Input() address: string | null = null;
|
||||||
|
@Input() phone: string | null = null;
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,8 @@
|
|||||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||||
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||||
[storeName]="tenant()?.nombre ?? null"
|
[storeName]="tenant()?.nombre ?? null"
|
||||||
|
[address]="tenant()?.address ?? null"
|
||||||
|
[phone]="tenant()?.phone ?? null"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
convertToParamMap,
|
||||||
|
ParamMap,
|
||||||
|
provideRouter,
|
||||||
|
Router,
|
||||||
|
} from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { BehaviorSubject, of } from 'rxjs';
|
||||||
|
|
||||||
import { Tenant } from '../../services/tenant.interface';
|
import { Tenant } from '../../services/tenant.interface';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
@@ -22,6 +28,8 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
address: 'Calle Test 123, Rosario',
|
||||||
|
phone: '+54 341 555 1234',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -140,11 +148,13 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||||
@@ -154,6 +164,10 @@ describe('StoreLayoutComponent', () => {
|
|||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -213,6 +227,19 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the cart when requested through the openCart query parameter', () => {
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
|
||||||
|
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('hides the configured header elements when the tenant disables them', () => {
|
it('hides the configured header elements when the tenant disables them', () => {
|
||||||
tenantState.set({
|
tenantState.set({
|
||||||
...tenant,
|
...tenant,
|
||||||
@@ -274,6 +301,12 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.address,
|
||||||
|
);
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.phone,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates to search results when the search button is clicked', () => {
|
it('navigates to search results when the search button is clicked', () => {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||||
import { Router, RouterOutlet } from '@angular/router';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||||
@@ -32,6 +33,8 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
@@ -146,6 +149,12 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||||
|
if (params.get('openCart') === 'true') {
|
||||||
|
this.isCartOpen.set(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.cartService.loadCart().subscribe({
|
this.cartService.loadCart().subscribe({
|
||||||
error: (err) => console.error('Error loading cart', err),
|
error: (err) => console.error('Error loading cart', err),
|
||||||
});
|
});
|
||||||
@@ -178,8 +187,8 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
protected async onLogoutClick(): Promise<void> {
|
protected async onLogoutClick(): Promise<void> {
|
||||||
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
||||||
|
|
||||||
// Checkout must be left while the authenticated session is still valid so
|
// Leave checkout before closing the authenticated session so its component
|
||||||
// its CanDeactivate guard can cancel the pending purchase.
|
// can stop payment polling cleanly. The checkout itself remains pending.
|
||||||
if (isLeavingCheckout) {
|
if (isLeavingCheckout) {
|
||||||
const navigationSucceeded = await this.router.navigate(['/']);
|
const navigationSucceeded = await this.router.navigate(['/']);
|
||||||
|
|
||||||
|
|||||||
@@ -155,6 +155,7 @@ export type CatalogFeaturedItems =
|
|||||||
|
|
||||||
export interface CatalogFeaturedGroup {
|
export interface CatalogFeaturedGroup {
|
||||||
id: number;
|
id: number;
|
||||||
|
code: string;
|
||||||
title: string;
|
title: string;
|
||||||
layout: CatalogProductLayout;
|
layout: CatalogProductLayout;
|
||||||
group_layout: CatalogGroupLayout;
|
group_layout: CatalogGroupLayout;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { CartItemVariant } from './cart/cart.interface';
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -73,6 +74,7 @@ export interface PurchaseDetailItemResponse {
|
|||||||
line_total: string;
|
line_total: string;
|
||||||
source_catalog_item_id: number | null;
|
source_catalog_item_id: number | null;
|
||||||
source_variant_id: number | null;
|
source_variant_id: number | null;
|
||||||
|
variants?: CartItemVariant[];
|
||||||
item_details: {
|
item_details: {
|
||||||
nombre: string;
|
nombre: string;
|
||||||
descripcion: string | null;
|
descripcion: string | null;
|
||||||
@@ -95,7 +97,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
telefono: string | null;
|
telefono: string | null;
|
||||||
nombre_apellido: string | null;
|
nombre_apellido: string | null;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
items_source: 'purchase';
|
items_source: 'purchase' | 'cart';
|
||||||
items: PurchaseDetailItemResponse[];
|
items: PurchaseDetailItemResponse[];
|
||||||
tickets_count?: number;
|
tickets_count?: number;
|
||||||
has_generated_tickets?: boolean;
|
has_generated_tickets?: boolean;
|
||||||
@@ -174,7 +176,20 @@ export class CheckoutService extends BaseApiService {
|
|||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
itemId: number,
|
itemId: number,
|
||||||
quantity: number,
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
@@ -190,6 +205,51 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateItemVariant(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
variantId: number,
|
||||||
|
quantity: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
if (itemsSource === 'cart' && cartId !== null) {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`,
|
||||||
|
{ cantidad: quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await firstValueFrom(
|
||||||
|
this.http.patch(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||||
|
{ quantity, variant_id: variantId },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeItem(
|
||||||
|
tenantCode: string,
|
||||||
|
purchaseId: number,
|
||||||
|
itemId: number,
|
||||||
|
cartId: number | null = null,
|
||||||
|
itemsSource: 'purchase' | 'cart' = 'purchase',
|
||||||
|
): Promise<PurchaseDetailResponse> {
|
||||||
|
const url =
|
||||||
|
itemsSource === 'cart' && cartId !== null
|
||||||
|
? `${environment.url}tenants/${tenantCode}/checkout-carts/${cartId}/items/${itemId}`
|
||||||
|
: `${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`;
|
||||||
|
|
||||||
|
await firstValueFrom(this.http.delete(url));
|
||||||
|
|
||||||
|
return this.getPurchase(tenantCode, purchaseId);
|
||||||
|
}
|
||||||
|
|
||||||
async prepareItemEditing(
|
async prepareItemEditing(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
|
|||||||
@@ -113,6 +113,8 @@ export interface Tenant {
|
|||||||
dominio: string;
|
dominio: string;
|
||||||
base_path?: string;
|
base_path?: string;
|
||||||
site_title?: string | null;
|
site_title?: string | null;
|
||||||
|
address?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
favicon?: string | null;
|
favicon?: string | null;
|
||||||
primary_color: string;
|
primary_color: string;
|
||||||
secondary_color: string;
|
secondary_color: string;
|
||||||
@@ -138,6 +140,7 @@ export interface Tenant {
|
|||||||
display_seach_bar?: boolean;
|
display_seach_bar?: boolean;
|
||||||
display_cart?: boolean;
|
display_cart?: boolean;
|
||||||
cart_editing_policy?: CartEditingPolicy;
|
cart_editing_policy?: CartEditingPolicy;
|
||||||
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
display_cart_item_images?: boolean;
|
display_cart_item_images?: boolean;
|
||||||
social_media?: SocialMedia[];
|
social_media?: SocialMedia[];
|
||||||
menues?: Menu[];
|
menues?: Menu[];
|
||||||
|
|||||||
@@ -59,18 +59,22 @@
|
|||||||
[discount]="cartDiscount()"
|
[discount]="cartDiscount()"
|
||||||
[total]="cartTotal()"
|
[total]="cartTotal()"
|
||||||
[readonly]="!canModifyCart()"
|
[readonly]="!canModifyCart()"
|
||||||
[allowModify]="canModifyCart()"
|
[allowModify]="true"
|
||||||
|
[showModifyWhenReadonly]="true"
|
||||||
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||||
[requireEditingMode]="
|
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||||
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
|
[requireEditingMode]="true"
|
||||||
"
|
[allowDelete]="canDeleteCartItems()"
|
||||||
[allowDelete]="false"
|
|
||||||
[persistQuantityChanges]="false"
|
[persistQuantityChanges]="false"
|
||||||
|
[persistVariantChanges]="false"
|
||||||
|
[persistDeleteChanges]="false"
|
||||||
[editing]="isEditingItems()"
|
[editing]="isEditingItems()"
|
||||||
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
||||||
backgroundColor="transparent"
|
backgroundColor="transparent"
|
||||||
(editingChange)="onEditingItemsChange($event)"
|
(editingChange)="onEditingItemsChange($event)"
|
||||||
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
||||||
|
(itemVariantChange)="onPurchaseItemVariantChange($event)"
|
||||||
|
(itemRemove)="onPurchaseItemRemove($event)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { signal } from '@angular/core';
|
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';
|
||||||
@@ -10,6 +11,7 @@ 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 { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||||
import { CheckoutPageComponent } from './checkout-page.component';
|
import { CheckoutPageComponent } from './checkout-page.component';
|
||||||
|
|
||||||
@@ -18,9 +20,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
startCheckout: ReturnType<typeof vi.fn>;
|
startCheckout: ReturnType<typeof vi.fn>;
|
||||||
updateCustomerData: ReturnType<typeof vi.fn>;
|
updateCustomerData: ReturnType<typeof vi.fn>;
|
||||||
updateItemQuantity: ReturnType<typeof vi.fn>;
|
updateItemQuantity: ReturnType<typeof vi.fn>;
|
||||||
|
updateItemVariant: ReturnType<typeof vi.fn>;
|
||||||
|
removeItem: ReturnType<typeof vi.fn>;
|
||||||
prepareItemEditing: ReturnType<typeof vi.fn>;
|
prepareItemEditing: ReturnType<typeof vi.fn>;
|
||||||
cancelPurchase: ReturnType<typeof vi.fn>;
|
cancelPurchase: ReturnType<typeof vi.fn>;
|
||||||
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
||||||
|
submitPurchaseForReview: ReturnType<typeof vi.fn>;
|
||||||
getPurchase: ReturnType<typeof vi.fn>;
|
getPurchase: ReturnType<typeof vi.fn>;
|
||||||
withCustomLoading: ReturnType<typeof vi.fn>;
|
withCustomLoading: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
@@ -31,12 +36,13 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
clearCart: 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 routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||||
let authUserState: ReturnType<typeof signal>;
|
let authUserState: ReturnType<typeof signal>;
|
||||||
let tenantState: ReturnType<
|
let tenantState: ReturnType<
|
||||||
typeof signal<{
|
typeof signal<{
|
||||||
codigo: string;
|
codigo: string;
|
||||||
cart_editing_policy?: CartEditingPolicy;
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
}>
|
}>
|
||||||
>;
|
>;
|
||||||
|
|
||||||
@@ -60,11 +66,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
}),
|
}),
|
||||||
updateCustomerData: vi.fn(),
|
updateCustomerData: vi.fn(),
|
||||||
updateItemQuantity: vi.fn(),
|
updateItemQuantity: vi.fn(),
|
||||||
|
updateItemVariant: vi.fn(),
|
||||||
|
removeItem: vi.fn(),
|
||||||
prepareItemEditing: vi.fn(),
|
prepareItemEditing: vi.fn(),
|
||||||
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
||||||
generatePaymentIntent: vi.fn().mockResolvedValue({
|
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||||
qr_data: { qr_code: 'qr-value' },
|
qr_data: { qr_code: 'qr-value' },
|
||||||
}),
|
}),
|
||||||
|
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||||
withCustomLoading: vi.fn(),
|
withCustomLoading: vi.fn(),
|
||||||
};
|
};
|
||||||
@@ -91,11 +100,12 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
routerStub = { navigate: vi.fn() };
|
routerStub = { navigate: vi.fn() };
|
||||||
|
toastServiceStub = { danger: vi.fn() };
|
||||||
routeQueryParamMap = convertToParamMap({});
|
routeQueryParamMap = convertToParamMap({});
|
||||||
authUserState = signal(null);
|
authUserState = signal(null);
|
||||||
tenantState = signal({
|
tenantState = signal({
|
||||||
codigo: 'tenant-test',
|
codigo: 'tenant-test',
|
||||||
cart_editing_policy: {
|
checkout_editing_policy: {
|
||||||
code: 'full',
|
code: 'full',
|
||||||
allow_modify: true,
|
allow_modify: true,
|
||||||
allow_delete: true,
|
allow_delete: true,
|
||||||
@@ -112,6 +122,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
{ provide: CartService, useValue: cartServiceStub },
|
{ 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: ToastService, useValue: toastServiceStub },
|
||||||
{
|
{
|
||||||
provide: ActivatedRoute,
|
provide: ActivatedRoute,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -209,19 +220,28 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('checks the purchase detail once when the transfer was made', async () => {
|
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
expect(component.transferValidationStatus()).toBe('checking');
|
||||||
|
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(3_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenLastCalledWith('tenant-test', 25);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(30_000);
|
|
||||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates after a transfer is confirmed as paid', async () => {
|
it('navigates after a transfer is confirmed as paid', async () => {
|
||||||
@@ -230,25 +250,59 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
|
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(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows a retryable state when transfer validation fails', async () => {
|
it('keeps polling after transfer validation requests fail', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
|
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
|
||||||
const { component } = createComponent();
|
const { component } = createComponent();
|
||||||
component.selectedPaymentMethod.set('transfer');
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
await component.onComplete();
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||||
expect(component.transferValidationStatus()).toBe('error');
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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'));
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.selectedPaymentMethod.set('transfer');
|
||||||
|
|
||||||
|
await component.onComplete();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
|
||||||
|
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
expect(component.transferValidationStatus()).toBe('error');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels transfer polling when the payment method changes or the component is destroyed', async () => {
|
||||||
|
const first = createComponent();
|
||||||
|
first.component.selectedPaymentMethod.set('transfer');
|
||||||
|
first.component.onComplete();
|
||||||
|
checkoutServiceStub.generatePaymentIntent.mockResolvedValueOnce({});
|
||||||
|
await first.component.selectPaymentMethod('qr');
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const second = createComponent();
|
||||||
|
second.component.selectedPaymentMethod.set('transfer');
|
||||||
|
second.component.onComplete();
|
||||||
|
second.fixture.destroy();
|
||||||
|
await vi.advanceTimersByTimeAsync(12_000);
|
||||||
|
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('loads purchase items but prefills customer data from the user', async () => {
|
it('loads purchase items but prefills customer data from the user', async () => {
|
||||||
const purchase = {
|
const purchase = {
|
||||||
id: 25,
|
id: 25,
|
||||||
@@ -448,7 +502,14 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
quantity: 3,
|
quantity: 3,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3);
|
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith(
|
||||||
|
'tenant-test',
|
||||||
|
25,
|
||||||
|
91,
|
||||||
|
3,
|
||||||
|
null,
|
||||||
|
'purchase',
|
||||||
|
);
|
||||||
expect(component.createdPurchase()).toBe(updatedPurchase);
|
expect(component.createdPurchase()).toBe(updatedPurchase);
|
||||||
expect(component.isUpdatingItem()).toBe(false);
|
expect(component.isUpdatingItem()).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -481,10 +542,10 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.isEditingItems()).toBe(false);
|
expect(component.isEditingItems()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not allow item editing when the tenant disables cart editing', async () => {
|
it('shows Modificar and returns to the home cart when checkout editing is disabled', async () => {
|
||||||
tenantState.set({
|
tenantState.set({
|
||||||
codigo: 'tenant-test',
|
codigo: 'tenant-test',
|
||||||
cart_editing_policy: {
|
checkout_editing_policy: {
|
||||||
code: 'disabled',
|
code: 'disabled',
|
||||||
allow_modify: false,
|
allow_modify: false,
|
||||||
allow_delete: false,
|
allow_delete: false,
|
||||||
@@ -492,7 +553,37 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
allow_update_variant: false,
|
allow_update_variant: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const { component } = createComponent();
|
const { fixture, component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 91,
|
||||||
|
quantity: 2,
|
||||||
|
unit_price: '100.00',
|
||||||
|
line_total: '200.00',
|
||||||
|
source_catalog_item_id: 8,
|
||||||
|
source_variant_id: null,
|
||||||
|
item_details: {
|
||||||
|
nombre: 'Remera',
|
||||||
|
descripcion: null,
|
||||||
|
slug: 'remera',
|
||||||
|
imagen: null,
|
||||||
|
attributes: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
subtotal: '200.00',
|
||||||
|
total: '200.00',
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const modifyButton = (fixture.nativeElement as HTMLElement).querySelector('.cart-edit-btn');
|
||||||
|
expect(modifyButton?.textContent?.trim()).toBe('Modificar');
|
||||||
|
expect(
|
||||||
|
(fixture.nativeElement as HTMLElement).querySelector('app-quantity-selector'),
|
||||||
|
).toBeNull();
|
||||||
|
|
||||||
await component.onEditingItemsChange(true);
|
await component.onEditingItemsChange(true);
|
||||||
|
|
||||||
@@ -500,6 +591,9 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.canModifyCart()).toBe(false);
|
expect(component.canModifyCart()).toBe(false);
|
||||||
expect(component.isEditingItems()).toBe(false);
|
expect(component.isEditingItems()).toBe(false);
|
||||||
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
|
expect(checkoutServiceStub.prepareItemEditing).not.toHaveBeenCalled();
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updates customer data on the existing purchase before payment', async () => {
|
it('updates customer data on the existing purchase before payment', async () => {
|
||||||
@@ -536,14 +630,65 @@ describe('CheckoutPageComponent payment validation', () => {
|
|||||||
expect(component.stepper.next).toHaveBeenCalledOnce();
|
expect(component.stepper.next).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('cancels the pending purchase before allowing navigation away', async () => {
|
it('keeps the checkout purchase intact when navigating away', 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).not.toHaveBeenCalled();
|
||||||
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
expect(cartServiceStub.loadCart).toHaveBeenCalled();
|
||||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||||
expect(component.createdPurchaseId()).toBeNull();
|
expect(component.createdPurchaseId()).toBe(25);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the API message and redirects home when a checkout operation finds an expired purchase', async () => {
|
||||||
|
checkoutServiceStub.generatePaymentIntent.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
code: 'purchase.expired',
|
||||||
|
message: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { component } = createComponent();
|
||||||
|
|
||||||
|
await component.selectPaymentMethod('qr');
|
||||||
|
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
|
expect(component.isGeneratingIntent()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a generic customer-data error as expired when the local deadline passed', () => {
|
||||||
|
const { component } = createComponent();
|
||||||
|
component.createdPurchase.set({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
expires_at: new Date(Date.now() - 1_000).toISOString(),
|
||||||
|
items: [],
|
||||||
|
subtotal: '100.00',
|
||||||
|
total: '100.00',
|
||||||
|
});
|
||||||
|
|
||||||
|
const handled = component.handleCheckoutError(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: {
|
||||||
|
errors: {
|
||||||
|
purchase: ['La compra ya no se puede modificar.'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
'No se pudieron actualizar los datos de la compra.',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(handled).toBe(true);
|
||||||
|
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||||
|
'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
expect(routerStub.navigate).toHaveBeenCalledWith(['/']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
signal,
|
signal,
|
||||||
ViewChild,
|
ViewChild,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
|
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 { firstValueFrom, startWith } from 'rxjs';
|
||||||
@@ -20,6 +21,7 @@ import {
|
|||||||
} 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 { CartService } from '../../../../core/services/cart/cart.service';
|
||||||
|
import { ToastService } from '../../../../core/services/toast.service';
|
||||||
import { BankAccount } from '../../../../core/services/tenant.interface';
|
import { BankAccount } from '../../../../core/services/tenant.interface';
|
||||||
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||||
@@ -36,6 +38,12 @@ import {
|
|||||||
TransferValidationStatus,
|
TransferValidationStatus,
|
||||||
} from './checkout-page.models';
|
} from './checkout-page.models';
|
||||||
|
|
||||||
|
interface ApiErrorResponse {
|
||||||
|
code?: string;
|
||||||
|
message?: string;
|
||||||
|
errors?: Record<string, string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-checkout-page',
|
selector: 'app-checkout-page',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
@@ -59,11 +67,17 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly qrPollingIntervalMs = 5_000;
|
private readonly qrPollingIntervalMs = 5_000;
|
||||||
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly qrPollingMaxAttempts = 9;
|
private readonly qrPollingMaxAttempts = 9;
|
||||||
|
private readonly transferPollingIntervalMs = 3_000;
|
||||||
|
private readonly transferPollingMaxAttempts = 4;
|
||||||
|
|
||||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
private qrPollingAttempts = 0;
|
private qrPollingAttempts = 0;
|
||||||
private qrPollingRunId = 0;
|
private qrPollingRunId = 0;
|
||||||
|
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private transferPollingAttempts = 0;
|
||||||
|
private transferPollingRunId = 0;
|
||||||
private paymentMethodRequestId = 0;
|
private paymentMethodRequestId = 0;
|
||||||
private navigationStarted = false;
|
private navigationStarted = false;
|
||||||
|
|
||||||
@@ -80,10 +94,16 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
protected readonly isLoadingPurchase = signal(true);
|
protected readonly isLoadingPurchase = signal(true);
|
||||||
protected readonly checkoutStepIndex = signal(0);
|
protected readonly checkoutStepIndex = signal(0);
|
||||||
protected readonly canUpdateCartQuantity = computed(
|
protected readonly canUpdateCartQuantity = computed(
|
||||||
() => this.tenantService.tenant()?.cart_editing_policy?.allow_update_quantity ?? false,
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_quantity ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartVariant = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_update_variant ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canDeleteCartItems = computed(
|
||||||
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_delete ?? false,
|
||||||
);
|
);
|
||||||
protected readonly canModifyCart = computed(
|
protected readonly canModifyCart = computed(
|
||||||
() => this.tenantService.tenant()?.cart_editing_policy?.allow_modify ?? false,
|
() => this.tenantService.tenant()?.checkout_editing_policy?.allow_modify ?? false,
|
||||||
);
|
);
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
@@ -161,6 +181,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
|
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
|
||||||
@@ -176,6 +197,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
value: attribute.value === null ? '' : String(attribute.value),
|
value: attribute.value === null ? '' : String(attribute.value),
|
||||||
})),
|
})),
|
||||||
quantity: item.quantity,
|
quantity: item.quantity,
|
||||||
|
variantId: item.source_variant_id,
|
||||||
|
variants: item.variants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +208,28 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (editing && !this.canModifyCart()) {
|
if (editing && !this.canModifyCart()) {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchaseId = this.createdPurchaseId();
|
||||||
|
|
||||||
|
if (!tenant || !purchaseId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isPreparingItemEdit.set(true);
|
||||||
|
try {
|
||||||
|
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
||||||
|
this.createdPurchaseId.set(null);
|
||||||
|
this.createdPurchase.set(null);
|
||||||
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
|
await this.router.navigate(['/'], {
|
||||||
|
queryParams: { openCart: true },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo restaurar el carrito para editarlo.');
|
||||||
|
} finally {
|
||||||
|
this.isPreparingItemEdit.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,6 +245,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.isEditingItems.set(true);
|
this.isEditingItems.set(true);
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrData.set(null);
|
this.qrData.set(null);
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferAccount.set(null);
|
this.transferAccount.set(null);
|
||||||
@@ -218,7 +264,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId);
|
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to prepare purchase item editing:', error);
|
this.handleCheckoutError(error, 'No se pudo preparar la compra para editarla.');
|
||||||
this.isEditingItems.set(false);
|
this.isEditingItems.set(false);
|
||||||
} finally {
|
} finally {
|
||||||
this.isPreparingItemEdit.set(false);
|
this.isPreparingItemEdit.set(false);
|
||||||
@@ -251,10 +297,85 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
purchaseId,
|
purchaseId,
|
||||||
itemId,
|
itemId,
|
||||||
event.quantity,
|
event.quantity,
|
||||||
|
this.createdPurchase()?.cart_id ?? null,
|
||||||
|
this.createdPurchase()?.items_source ?? 'purchase',
|
||||||
);
|
);
|
||||||
this.createdPurchase.set(purchase);
|
this.createdPurchase.set(purchase);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to update purchase item quantity:', error);
|
this.handleCheckoutError(error, 'No se pudo actualizar la cantidad del producto.');
|
||||||
|
} finally {
|
||||||
|
this.isUpdatingItem.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemVariantChange(event: {
|
||||||
|
item: CartItemMock;
|
||||||
|
variantId: number;
|
||||||
|
}): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canUpdateCartVariant() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.updateItemVariant(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
event.variantId,
|
||||||
|
event.item.quantity,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo actualizar la variante del producto.');
|
||||||
|
} finally {
|
||||||
|
this.isUpdatingItem.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPurchaseItemRemove(event: { item: CartItemMock }): Promise<void> {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
const itemId = event.item.cartItemId;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!this.canDeleteCartItems() ||
|
||||||
|
!tenant ||
|
||||||
|
!purchase ||
|
||||||
|
!itemId ||
|
||||||
|
this.isUpdatingItem() ||
|
||||||
|
!this.isEditingItems()
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUpdatingItem.set(true);
|
||||||
|
try {
|
||||||
|
this.createdPurchase.set(
|
||||||
|
await this.checkoutService.removeItem(
|
||||||
|
tenant.codigo,
|
||||||
|
purchase.id,
|
||||||
|
itemId,
|
||||||
|
purchase.cart_id,
|
||||||
|
purchase.items_source,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.handleCheckoutError(error, 'No se pudo eliminar el producto de la compra.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isUpdatingItem.set(false);
|
this.isUpdatingItem.set(false);
|
||||||
}
|
}
|
||||||
@@ -284,8 +405,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
// Auto trigger intent for default option
|
// Auto trigger intent for default option
|
||||||
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create purchase:', error);
|
this.handleCheckoutError(error, 'No se pudieron actualizar los datos de la compra.');
|
||||||
// Here we could show an alert or toast
|
|
||||||
} finally {
|
} finally {
|
||||||
this.isUpdatingPurchase.set(false);
|
this.isUpdatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
@@ -299,34 +419,21 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
public async canDeactivate(): Promise<boolean> {
|
public async canDeactivate(): Promise<boolean> {
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
if (this.navigationStarted) {
|
if (this.navigationStarted) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const purchaseId = this.createdPurchaseId();
|
// The checkout cart remains attached to its purchase. Once the user adds a
|
||||||
const tenant = this.tenantService.tenant();
|
// new item, the cart API creates a separate active cart automatically.
|
||||||
|
|
||||||
if (!purchaseId || !tenant) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
|
||||||
this.createdPurchaseId.set(null);
|
|
||||||
this.createdPurchase.set(null);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await firstValueFrom(this.cartService.loadCart());
|
await firstValueFrom(this.cartService.loadCart());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to restore cart after cancelling checkout:', error);
|
console.error('Failed to load the active cart after leaving checkout:', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to cancel purchase:', error);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||||
@@ -335,6 +442,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
this.qrPaymentStatus.set('idle');
|
this.qrPaymentStatus.set('idle');
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.selectedPaymentMethod.set(method);
|
this.selectedPaymentMethod.set(method);
|
||||||
@@ -373,7 +481,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
this.startQrPolling();
|
this.startQrPolling();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to generate payment intent:', error);
|
this.handleCheckoutError(error, 'No se pudo generar la intenci\u00f3n de pago.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isGeneratingIntent.set(false);
|
this.isGeneratingIntent.set(false);
|
||||||
}
|
}
|
||||||
@@ -392,6 +500,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.transferDni.set(dni);
|
this.transferDni.set(dni);
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('idle');
|
this.transferValidationStatus.set('idle');
|
||||||
this.isGeneratingIntent.set(true);
|
this.isGeneratingIntent.set(true);
|
||||||
try {
|
try {
|
||||||
@@ -409,7 +518,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to generate transfer payment intent:', error);
|
this.handleCheckoutError(error, 'No se pudo generar la intenci\u00f3n de transferencia.');
|
||||||
} finally {
|
} finally {
|
||||||
this.isGeneratingIntent.set(false);
|
this.isGeneratingIntent.set(false);
|
||||||
}
|
}
|
||||||
@@ -446,22 +555,97 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('checking');
|
this.transferValidationStatus.set('checking');
|
||||||
|
this.transferPollingAttempts = 0;
|
||||||
|
|
||||||
|
const runId = this.transferPollingRunId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const purchase = await this.checkoutService
|
const purchase = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.getPurchase(tenant.codigo, purchaseId);
|
.submitPurchaseForReview(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (purchase.status === 'paid') {
|
if (purchase.status === 'paid') {
|
||||||
this.navigateToPurchaseStatus(purchaseId);
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.scheduleTransferPoll(runId);
|
||||||
|
} catch (error) {
|
||||||
|
const expired = this.handleCheckoutError(
|
||||||
|
error,
|
||||||
|
'No se pudo enviar la compra a revisi\u00f3n.',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!expired && runId === this.transferPollingRunId) {
|
||||||
this.transferValidationStatus.set('error');
|
this.transferValidationStatus.set('error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleTransferPoll(runId: number): void {
|
||||||
|
this.transferPollingTimeoutId = setTimeout(() => {
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
|
void this.checkTransferPayment(runId);
|
||||||
|
}, this.transferPollingIntervalMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkTransferPayment(runId: number): Promise<void> {
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const purchaseId = this.createdPurchaseId();
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
|
||||||
|
if (!purchaseId || !tenant || this.selectedPaymentMethod() !== 'transfer') {
|
||||||
|
this.stopTransferPolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.transferPollingAttempts += 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const purchase = await this.checkoutService
|
||||||
|
.withCustomLoading()
|
||||||
|
.getPurchase(tenant.codigo, purchaseId);
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'paid') {
|
||||||
|
this.navigateToPurchaseStatus(purchaseId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to validate transfer payment:', error);
|
console.error('Failed to validate transfer payment:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runId !== this.transferPollingRunId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
|
||||||
|
this.stopTransferPolling();
|
||||||
this.transferValidationStatus.set('error');
|
this.transferValidationStatus.set('error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.scheduleTransferPoll(runId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopTransferPolling(): void {
|
||||||
|
this.transferPollingRunId += 1;
|
||||||
|
|
||||||
|
if (this.transferPollingTimeoutId !== null) {
|
||||||
|
clearTimeout(this.transferPollingTimeoutId);
|
||||||
|
this.transferPollingTimeoutId = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -575,6 +759,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
this.navigationStarted = true;
|
this.navigationStarted = true;
|
||||||
this.stopQrPolling();
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
|
||||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||||
}
|
}
|
||||||
@@ -629,4 +814,54 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
|||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private handleCheckoutError(error: unknown, fallbackMessage: string): boolean {
|
||||||
|
if (!(error instanceof HttpErrorResponse)) {
|
||||||
|
this.toastService.danger(fallbackMessage);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = error.error as ApiErrorResponse | null;
|
||||||
|
|
||||||
|
if (response?.code === 'purchase.expired' || this.hasExpiredPurchase()) {
|
||||||
|
this.navigationStarted = true;
|
||||||
|
this.stopQrPolling();
|
||||||
|
this.stopTransferPolling();
|
||||||
|
this.toastService.danger(
|
||||||
|
response?.code === 'purchase.expired' && response.message
|
||||||
|
? response.message
|
||||||
|
: 'La compra venci\u00f3. Inici\u00e1 una nueva compra.',
|
||||||
|
);
|
||||||
|
void this.router.navigate(['/']);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const validationMessage = response?.errors
|
||||||
|
? Object.values(response.errors).flat().find(Boolean)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
this.toastService.danger(validationMessage ?? response?.message ?? fallbackMessage);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasExpiredPurchase(): boolean {
|
||||||
|
const purchase = this.createdPurchase();
|
||||||
|
|
||||||
|
if (!purchase) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (purchase.status === 'expired') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!purchase.expires_at) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Date.parse(purchase.expires_at) <= Date.now();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
</p>
|
</p>
|
||||||
} @else {
|
} @else {
|
||||||
@for (group of catalog(); track group.id) {
|
@for (group of catalog(); track group.id) {
|
||||||
<app-store-section [title]="group.title">
|
<app-store-section [attr.id]="group.code" [title]="group.title">
|
||||||
<app-product-list
|
<app-product-list
|
||||||
[layout]="group.layout"
|
[layout]="group.layout"
|
||||||
[groupLayout]="group.group_layout"
|
[groupLayout]="group.group_layout"
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ app-store-section + app-store-section {
|
|||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app-store-section[id] {
|
||||||
|
scroll-margin-top: 8rem;
|
||||||
|
}
|
||||||
|
|
||||||
:host > .store-home__additional-info:not(:first-child) {
|
:host > .store-home__additional-info:not(:first-child) {
|
||||||
margin-top: clamp(3rem, 6vw, 5rem);
|
margin-top: clamp(3rem, 6vw, 5rem);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ function createCatalog(
|
|||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
id: 7,
|
id: 7,
|
||||||
|
code: 'destacados',
|
||||||
title: 'Destacados',
|
title: 'Destacados',
|
||||||
layout: 'column_with_image',
|
layout: 'column_with_image',
|
||||||
group_layout: 'paginated',
|
group_layout: 'paginated',
|
||||||
@@ -149,6 +150,7 @@ describe('StoreHomePageComponent', () => {
|
|||||||
const element = fixture.nativeElement as HTMLElement;
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
expect(catalogServiceStub.getCatalog).not.toHaveBeenCalled();
|
||||||
|
expect(element.querySelector('app-store-section')?.id).toBe('destacados');
|
||||||
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
expect(element.querySelector('.store-section__title')?.textContent?.trim()).toBe('Destacados');
|
||||||
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
expect(element.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
||||||
expect(element.textContent).toContain('Auriculares Bluetooth');
|
expect(element.textContent).toContain('Auriculares Bluetooth');
|
||||||
|
|||||||
@@ -6,7 +6,12 @@
|
|||||||
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||||
|
|
||||||
<div class="d-flex align-items-center cart-header-actions">
|
<div class="d-flex align-items-center cart-header-actions">
|
||||||
@if (!readonly() && allowModify() && requireEditingMode() && items().length > 0) {
|
@if (
|
||||||
|
allowModify() &&
|
||||||
|
(!readonly() || showModifyWhenReadonly()) &&
|
||||||
|
requireEditingMode() &&
|
||||||
|
items().length > 0
|
||||||
|
) {
|
||||||
<button
|
<button
|
||||||
class="btn btn-link p-0 border-0 cart-edit-btn"
|
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -55,10 +55,13 @@ export class CartComponent {
|
|||||||
readonly readonly = input<boolean>(false);
|
readonly readonly = input<boolean>(false);
|
||||||
readonly allowUpdateQuantity = input<boolean>(true);
|
readonly allowUpdateQuantity = input<boolean>(true);
|
||||||
readonly allowModify = input<boolean>(true);
|
readonly allowModify = input<boolean>(true);
|
||||||
|
readonly showModifyWhenReadonly = input<boolean>(false);
|
||||||
readonly requireEditingMode = input<boolean>(false);
|
readonly requireEditingMode = input<boolean>(false);
|
||||||
readonly allowUpdateVariant = input<boolean>(true);
|
readonly allowUpdateVariant = input<boolean>(true);
|
||||||
readonly allowDelete = input<boolean>(true);
|
readonly allowDelete = input<boolean>(true);
|
||||||
readonly persistQuantityChanges = input<boolean>(true);
|
readonly persistQuantityChanges = input<boolean>(true);
|
||||||
|
readonly persistVariantChanges = input<boolean>(true);
|
||||||
|
readonly persistDeleteChanges = input<boolean>(true);
|
||||||
readonly editingDisabled = input<boolean>(false);
|
readonly editingDisabled = input<boolean>(false);
|
||||||
readonly editing = model<boolean>(false);
|
readonly editing = model<boolean>(false);
|
||||||
|
|
||||||
@@ -68,6 +71,12 @@ export class CartComponent {
|
|||||||
index: number;
|
index: number;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}>();
|
}>();
|
||||||
|
readonly itemVariantChange = output<{
|
||||||
|
item: CartItemMock;
|
||||||
|
index: number;
|
||||||
|
variantId: number;
|
||||||
|
}>();
|
||||||
|
readonly itemRemove = output<{ item: CartItemMock; index: number }>();
|
||||||
|
|
||||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||||
protected readonly variantOverrides = signal<Record<number, number>>({});
|
protected readonly variantOverrides = signal<Record<number, number>>({});
|
||||||
@@ -179,6 +188,12 @@ export class CartComponent {
|
|||||||
|
|
||||||
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
if (!item || !cartItemId || variantId === this.getItemVariant(item)) return;
|
||||||
|
|
||||||
|
this.itemVariantChange.emit({ item, index, variantId });
|
||||||
|
|
||||||
|
if (!this.persistVariantChanges()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
this.variantOverrides.update((overrides) => ({ ...overrides, [cartItemId]: variantId }));
|
||||||
this.cartService
|
this.cartService
|
||||||
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
||||||
@@ -221,8 +236,15 @@ export class CartComponent {
|
|||||||
})
|
})
|
||||||
.subscribe((confirmed) => {
|
.subscribe((confirmed) => {
|
||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
|
const item = this.items()[index];
|
||||||
|
if (item) {
|
||||||
|
this.itemRemove.emit({ item, index });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.persistDeleteChanges()) {
|
||||||
this.removeItem(target.cartItemId);
|
this.removeItem(target.cartItemId);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user