Compare commits
55 Commits
feature/ti
...
feature/al
| Author | SHA1 | Date | |
|---|---|---|---|
| 72c80465e8 | |||
| 5273459b64 | |||
| 3ec469a539 | |||
| f02f4456b7 | |||
| eda8d32f4e | |||
| 5ca1f03e20 | |||
| 8861e42fff | |||
| 7fbdd3844f | |||
| f2c1542e46 | |||
| def86405dc | |||
| 870de3ca6e | |||
| d8d489e846 | |||
| 4183d6386d | |||
| 8089298383 | |||
| d51db00247 | |||
| 88c3a08a23 | |||
| 21e89805d0 | |||
| 195ac73aed | |||
| c24a8b946d | |||
| 70060f65ec | |||
| 02ff829c06 | |||
| 69c836a578 | |||
| 87cc430f05 | |||
| 3e9e35c681 | |||
| 0bd6dc3b22 | |||
| f056c32f49 | |||
| 11df4dbe72 | |||
| 9b69a1d387 | |||
| 4251ca8a8a | |||
| b14f34d3e8 | |||
| d636b2b82b | |||
| cfa1091116 | |||
| d0b1607ff4 | |||
| 92546a28c0 | |||
| ce26fb5d1a | |||
| 38a57adf55 | |||
| e1d9590905 | |||
| 00a01e1a8e | |||
| 56e011bc7a | |||
| 5c6a03b10d | |||
| cc446433f6 | |||
| 2d0664a7c7 | |||
| 2192eea09f | |||
| 8659708e1a | |||
| dce54ceb67 | |||
| cab33d4842 | |||
| f318f614af | |||
| 581696ffab | |||
| 53cee7ecdd | |||
| 757f362918 | |||
| a8e73af806 | |||
| 61789d9238 | |||
| dd2082f40e | |||
| 755d6a9903 | |||
| c486131905 |
14
angular.json
14
angular.json
@@ -47,6 +47,9 @@
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"optimization": true,
|
||||
"extractLicenses": true,
|
||||
"sourceMap": false,
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
@@ -59,7 +62,13 @@
|
||||
"maximumError": "8kB"
|
||||
}
|
||||
],
|
||||
"outputHashing": "all"
|
||||
"outputHashing": "all",
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.production.ts"
|
||||
}
|
||||
]
|
||||
},
|
||||
"development": {
|
||||
"optimization": true,
|
||||
@@ -78,6 +87,9 @@
|
||||
]
|
||||
},
|
||||
"homo": {
|
||||
"optimization": true,
|
||||
"extractLicenses": true,
|
||||
"sourceMap": false,
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
provideAppInitializer,
|
||||
provideBrowserGlobalErrorListeners,
|
||||
} from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideRouter, UrlSerializer } from '@angular/router';
|
||||
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
@@ -12,6 +12,7 @@ import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
||||
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||
import { TenantUrlSerializer } from './core/services/tenant-url.serializer';
|
||||
|
||||
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||
return (
|
||||
@@ -26,6 +27,7 @@ export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||
provideClientHydration(
|
||||
withHttpTransferCacheOptions({
|
||||
includeRequestsWithAuthHeaders: true,
|
||||
|
||||
@@ -14,5 +14,12 @@ export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
loadChildren: () => import('./features/store/store.routes').then((m) => m.routes)
|
||||
},
|
||||
{
|
||||
path: '**',
|
||||
loadComponent: () =>
|
||||
import('./shared/pages/route-not-found-page.component').then(
|
||||
(m) => m.RouteNotFoundPageComponent,
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
@@ -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="d-grid gap-2 store-layout__contact-details">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||
<span>Av. San Lorenzo 1542, Rosario</span>
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||
<span>54 9 (0341) 6658247</span>
|
||||
</div>
|
||||
@if (address) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||
<span>{{ address }}</span>
|
||||
</div>
|
||||
}
|
||||
@if (phone) {
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||
<span>{{ phone }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<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() backgroundImageUrl: string | null = null;
|
||||
@Input() storeName: string | null = null;
|
||||
@Input() address: string | null = null;
|
||||
@Input() phone: string | null = null;
|
||||
readonly logoutClick = output<void>();
|
||||
}
|
||||
|
||||
@@ -79,10 +79,13 @@
|
||||
|
||||
@if (displayCart()) {
|
||||
<app-cart-icon
|
||||
[quantity]="cartQuantity()"
|
||||
ariaLabel="Carrito de compras"
|
||||
title="Carrito"
|
||||
(click)="cartClick.emit()"
|
||||
[quantity]="cartDisabled() ? null : cartQuantity()"
|
||||
[disabled]="cartDisabled()"
|
||||
[ariaLabel]="
|
||||
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
||||
"
|
||||
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
|
||||
(click)="onCartClick()"
|
||||
/>
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ export class StoreHeaderComponent {
|
||||
readonly displayCategories = input(true);
|
||||
readonly displaySeachBar = input(true);
|
||||
readonly displayCart = input(true);
|
||||
readonly cartDisabled = input(false);
|
||||
readonly cartClick = output<void>();
|
||||
readonly ticketsClick = output<void>();
|
||||
readonly loginClick = output<void>();
|
||||
@@ -53,6 +54,14 @@ export class StoreHeaderComponent {
|
||||
protected readonly showSearchError = signal(false);
|
||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
||||
|
||||
protected onCartClick(): void {
|
||||
if (this.cartDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cartClick.emit();
|
||||
}
|
||||
|
||||
@HostListener('document:click', ['$event'])
|
||||
protected onDocumentClick(event: MouseEvent): void {
|
||||
if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
[displayCategories]="tenant()?.display_categories ?? true"
|
||||
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||
[displayCart]="displayCart()"
|
||||
(cartClick)="isCartOpen.set(!isCartOpen())"
|
||||
[cartDisabled]="isCheckoutRoute()"
|
||||
(cartClick)="onCartClick()"
|
||||
(ticketsClick)="onTicketsClick()"
|
||||
(loginClick)="onLoginClick()"
|
||||
(logoutClick)="onLogoutClick()"
|
||||
@@ -20,7 +21,7 @@
|
||||
(categorySelect)="onCategorySelect($event)"
|
||||
/>
|
||||
|
||||
@if (displayCart() && isCartOpen()) {
|
||||
@if (displayCart() && !isCheckoutRoute() && isCartOpen()) {
|
||||
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
|
||||
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
||||
<app-cart
|
||||
@@ -29,6 +30,11 @@
|
||||
[subtotal]="cartSubtotal()"
|
||||
[discount]="cartDiscount()"
|
||||
[total]="cartTotal()"
|
||||
[readonly]="!canModifyCart()"
|
||||
[allowModify]="canModifyCart()"
|
||||
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||
[allowDelete]="canDeleteCartItems()"
|
||||
[backgroundColor]="'#ffffff'"
|
||||
(closed)="isCartOpen.set(false)"
|
||||
>
|
||||
@@ -62,6 +68,8 @@
|
||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||
[storeName]="tenant()?.nombre ?? null"
|
||||
[address]="tenant()?.address ?? null"
|
||||
[phone]="tenant()?.phone ?? null"
|
||||
(logoutClick)="onLogoutClick()"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
|
||||
.store-layout__cart-dropdown {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
top: 100px;
|
||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||
width: 100%;
|
||||
@@ -34,6 +36,10 @@
|
||||
overflow: hidden;
|
||||
animation: store-layout-slide-down 0.2s ease-out;
|
||||
|
||||
> app-cart {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 1400px) {
|
||||
right: 1.5rem;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,16 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
convertToParamMap,
|
||||
ParamMap,
|
||||
provideRouter,
|
||||
Router,
|
||||
UrlSerializer,
|
||||
} from '@angular/router';
|
||||
|
||||
import { of } from 'rxjs';
|
||||
import { BehaviorSubject, of } from 'rxjs';
|
||||
|
||||
import { Tenant } from '../../services/tenant.interface';
|
||||
import { TenantService } from '../../services/tenant.service';
|
||||
@@ -16,12 +23,15 @@ import { AuthUser } from '../../services/auth/auth.interfaces';
|
||||
import { StoreLayoutComponent } from './store-layout.component';
|
||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||
import { CheckoutService } from '../../services/checkout.service';
|
||||
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
||||
|
||||
const tenant: Tenant = {
|
||||
id: 1,
|
||||
codigo: 'test',
|
||||
nombre: 'Test Tenant',
|
||||
dominio: 'localhost',
|
||||
address: 'Calle Test 123, Rosario',
|
||||
phone: '+54 341 555 1234',
|
||||
primary_color: '#6376F3',
|
||||
secondary_color: '#A0A0A0',
|
||||
danger_color: '#FF8888',
|
||||
@@ -32,6 +42,13 @@ const tenant: Tenant = {
|
||||
footer_logo: 'https://example.com/footer.png',
|
||||
header_bg_image: 'https://example.com/header-background.png',
|
||||
footer_bg_image: 'https://example.com/footer-background.png',
|
||||
cart_editing_policy: {
|
||||
code: 'full',
|
||||
allow_modify: true,
|
||||
allow_delete: true,
|
||||
allow_update_quantity: true,
|
||||
allow_update_variant: true,
|
||||
},
|
||||
categories: [],
|
||||
menues: [
|
||||
{
|
||||
@@ -133,11 +150,13 @@ describe('StoreLayoutComponent', () => {
|
||||
let cartState = signal<Cart | null>(null);
|
||||
let authUserState = signal<AuthUser | null>(null);
|
||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||
|
||||
beforeEach(async () => {
|
||||
tenantState = signal<Tenant | null>(tenant);
|
||||
cartState = signal<Cart | null>(null);
|
||||
authUserState = signal<AuthUser | null>(null);
|
||||
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||
const isAuthenticatedState = signal(false);
|
||||
checkoutServiceStub = {
|
||||
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||
@@ -147,6 +166,11 @@ describe('StoreLayoutComponent', () => {
|
||||
imports: [StoreLayoutComponent],
|
||||
providers: [
|
||||
provideRouter([]),
|
||||
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||
},
|
||||
{
|
||||
provide: TenantService,
|
||||
useValue: {
|
||||
@@ -206,6 +230,46 @@ describe('StoreLayoutComponent', () => {
|
||||
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('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
||||
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
||||
const router = TestBed.inject(Router);
|
||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout?purchase=25');
|
||||
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const cartButton = element.querySelector<HTMLButtonElement>('app-cart-icon button');
|
||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||
|
||||
expect(cartButton?.disabled).toBe(true);
|
||||
expect(cartButton?.getAttribute('aria-label')).toBe(
|
||||
'Carrito no disponible durante el checkout',
|
||||
);
|
||||
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
|
||||
|
||||
header.componentInstance.cartClick.emit();
|
||||
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||
expect(element.querySelector('app-cart')).toBeNull();
|
||||
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||
});
|
||||
|
||||
it('hides the configured header elements when the tenant disables them', () => {
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
@@ -267,6 +331,12 @@ describe('StoreLayoutComponent', () => {
|
||||
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
||||
expect(compiled.querySelector('.fa-facebook')).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', () => {
|
||||
@@ -645,4 +715,102 @@ describe('StoreLayoutComponent', () => {
|
||||
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
|
||||
expect(buyButton).toBeDefined();
|
||||
});
|
||||
|
||||
it('hides quantity selectors when the tenant disables cart editing', () => {
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
cart_editing_policy: {
|
||||
code: 'disabled',
|
||||
allow_modify: false,
|
||||
allow_delete: false,
|
||||
allow_update_quantity: false,
|
||||
allow_update_variant: false,
|
||||
},
|
||||
});
|
||||
cartState.set({
|
||||
id: 1,
|
||||
tenant_codigo: tenant.codigo,
|
||||
status: 'active',
|
||||
subtotal: '100.00',
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
cantidad: 1,
|
||||
precio_unitario: '100.00',
|
||||
catalog_item_id: 1,
|
||||
variant_id: null,
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
variant: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
|
||||
expect(cartItem.componentInstance.readonly()).toBe(true);
|
||||
expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows variant selectors only for the full cart editing policy', () => {
|
||||
const variantCart: Cart = {
|
||||
id: 1,
|
||||
tenant_codigo: tenant.codigo,
|
||||
status: 'active',
|
||||
subtotal: '100.00',
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
cantidad: 1,
|
||||
precio_unitario: '100.00',
|
||||
catalog_item_id: 1,
|
||||
variant_id: 10,
|
||||
nombre: 'Producto',
|
||||
imagen: null,
|
||||
variant: { id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||
variants: [
|
||||
{ id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||
{ id: 11, precio: '100.00', stock_tecnico: 5, values: { talle: 'L' } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
cart_editing_policy: {
|
||||
code: 'quantity_and_remove',
|
||||
allow_modify: true,
|
||||
allow_delete: true,
|
||||
allow_update_quantity: true,
|
||||
allow_update_variant: false,
|
||||
},
|
||||
});
|
||||
cartState.set(variantCart);
|
||||
|
||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||
fixture.detectChanges();
|
||||
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.querySelector('app-variant-selector')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('app-quantity-selector')).not.toBeNull();
|
||||
|
||||
tenantState.set({
|
||||
...tenant,
|
||||
cart_editing_policy: {
|
||||
code: 'full',
|
||||
allow_modify: true,
|
||||
allow_delete: true,
|
||||
allow_update_quantity: true,
|
||||
allow_update_variant: true,
|
||||
},
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.querySelector('app-variant-selector')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
||||
import { Router, RouterOutlet } from '@angular/router';
|
||||
import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
NavigationEnd,
|
||||
PRIMARY_OUTLET,
|
||||
Router,
|
||||
RouterOutlet,
|
||||
} from '@angular/router';
|
||||
import { filter } from 'rxjs';
|
||||
import { TenantService } from '../../services/tenant.service';
|
||||
import { CartService } from '../../services/cart/cart.service';
|
||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||
@@ -32,10 +40,26 @@ export class StoreLayoutComponent implements OnInit {
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
protected readonly isCartOpen = signal(false);
|
||||
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||
protected readonly isCreatingPurchase = signal(false);
|
||||
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||
protected readonly canModifyCart = computed(
|
||||
() => this.cartEditingPolicy()?.allow_modify ?? false,
|
||||
);
|
||||
protected readonly canDeleteCartItems = computed(
|
||||
() => this.cartEditingPolicy()?.allow_delete ?? false,
|
||||
);
|
||||
protected readonly canUpdateCartQuantity = computed(
|
||||
() => this.cartEditingPolicy()?.allow_update_quantity ?? false,
|
||||
);
|
||||
protected readonly canUpdateCartVariant = computed(
|
||||
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
|
||||
);
|
||||
|
||||
protected readonly cartSubtotal = computed(() => {
|
||||
const cart = this.cartService.cart();
|
||||
@@ -89,6 +113,7 @@ export class StoreLayoutComponent implements OnInit {
|
||||
attributes,
|
||||
quantity: item.cantidad,
|
||||
variantId: item.variant_id,
|
||||
variants: item.variants,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,15 +157,49 @@ export class StoreLayoutComponent implements OnInit {
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.router.events
|
||||
.pipe(
|
||||
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe((event) => {
|
||||
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
|
||||
this.isCheckoutRoute.set(isCheckoutRoute);
|
||||
|
||||
if (isCheckoutRoute) {
|
||||
this.isCartOpen.set(false);
|
||||
}
|
||||
});
|
||||
|
||||
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||
if (params.get('openCart') === 'true' && !this.isCheckoutRoute()) {
|
||||
this.isCartOpen.set(true);
|
||||
}
|
||||
});
|
||||
|
||||
this.cartService.loadCart().subscribe({
|
||||
error: (err) => console.error('Error loading cart', err),
|
||||
});
|
||||
}
|
||||
|
||||
private isCheckoutUrl(url: string): boolean {
|
||||
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
||||
|
||||
return primarySegments[0]?.path === 'checkout';
|
||||
}
|
||||
|
||||
protected onLoginClick(): void {
|
||||
void this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
protected onCartClick(): void {
|
||||
if (this.isCheckoutRoute()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isCartOpen.update((isOpen) => !isOpen);
|
||||
}
|
||||
|
||||
protected onSearch(term: string): void {
|
||||
void this.router.navigate(['/buscar'], {
|
||||
queryParams: { q: term, page: 1 },
|
||||
@@ -164,8 +223,8 @@ export class StoreLayoutComponent implements OnInit {
|
||||
protected async onLogoutClick(): Promise<void> {
|
||||
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
||||
|
||||
// Checkout must be left while the authenticated session is still valid so
|
||||
// its CanDeactivate guard can cancel the pending purchase.
|
||||
// Leave checkout before closing the authenticated session so its component
|
||||
// can stop payment polling cleanly. The checkout itself remains pending.
|
||||
if (isLeavingCheckout) {
|
||||
const navigationSucceeded = await this.router.navigate(['/']);
|
||||
|
||||
@@ -213,7 +272,6 @@ export class StoreLayoutComponent implements OnInit {
|
||||
cart_id: cart.id,
|
||||
});
|
||||
|
||||
this.cartService.clearCart();
|
||||
this.isCartOpen.set(false);
|
||||
await this.router.navigate(['/checkout'], {
|
||||
queryParams: { purchase: purchase.id },
|
||||
|
||||
@@ -119,8 +119,12 @@ export class AuthService extends BaseApiService {
|
||||
|
||||
const apiUrl = new URL(environment.url);
|
||||
const authorizationUrl = new URL('/auth/google/redirect', apiUrl.origin);
|
||||
const basePath = tenant.base_path && tenant.base_path !== '/' ? tenant.base_path : '';
|
||||
authorizationUrl.searchParams.set('tenant', tenant.codigo);
|
||||
authorizationUrl.searchParams.set('return_url', this.document.location.origin);
|
||||
authorizationUrl.searchParams.set(
|
||||
'return_url',
|
||||
`${this.document.location.origin}${basePath}`,
|
||||
);
|
||||
|
||||
this.document.location.assign(authorizationUrl.toString());
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface CartItem {
|
||||
nombre: string | null;
|
||||
imagen: string | null;
|
||||
variant: CartItemVariant | null;
|
||||
variants?: CartItemVariant[];
|
||||
}
|
||||
|
||||
export interface Cart {
|
||||
|
||||
@@ -7,11 +7,13 @@ import { CartService } from './cart.service';
|
||||
import { TenantService } from '../tenant.service';
|
||||
import { Cart } from './cart.interface';
|
||||
import { LOADING_MODE } from '../global-loading/loading-mode';
|
||||
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
|
||||
|
||||
describe('CartService', () => {
|
||||
let service: CartService;
|
||||
let httpMock: HttpTestingController;
|
||||
let tenantServiceMock: any;
|
||||
let catalogAvailabilityService: CatalogAvailabilityService;
|
||||
|
||||
const mockCart: Cart = {
|
||||
id: 123,
|
||||
@@ -53,6 +55,7 @@ describe('CartService', () => {
|
||||
});
|
||||
|
||||
service = TestBed.inject(CartService);
|
||||
catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
@@ -101,6 +104,9 @@ describe('CartService', () => {
|
||||
});
|
||||
|
||||
it('should add item and update signal', () => {
|
||||
const availabilityChanged = vi.fn();
|
||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||
|
||||
service.addItem(5, 10, 2).subscribe((res) => {
|
||||
expect(res.data).toEqual(mockCart);
|
||||
expect(service.cart()).toEqual(mockCart);
|
||||
@@ -115,9 +121,13 @@ describe('CartService', () => {
|
||||
});
|
||||
expect(req.request.withCredentials).toBe(true);
|
||||
req.flush({ data: mockCart });
|
||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should update item quantity and update signal', () => {
|
||||
const availabilityChanged = vi.fn();
|
||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||
|
||||
const updatedCart = { ...mockCart, subtotal: '30.00' };
|
||||
updatedCart.items[0].cantidad = 3;
|
||||
|
||||
@@ -131,9 +141,13 @@ describe('CartService', () => {
|
||||
expect(req.request.body).toEqual({ cantidad: 3 });
|
||||
expect(req.request.withCredentials).toBe(true);
|
||||
req.flush({ data: updatedCart });
|
||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should remove item and update signal', () => {
|
||||
const availabilityChanged = vi.fn();
|
||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||
|
||||
const emptyCart: Cart = {
|
||||
id: 123,
|
||||
tenant_codigo: 'acme',
|
||||
@@ -151,5 +165,18 @@ describe('CartService', () => {
|
||||
expect(req.request.method).toBe('DELETE');
|
||||
expect(req.request.withCredentials).toBe(true);
|
||||
req.flush({ data: emptyCart });
|
||||
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not notify an availability change when a cart mutation fails', () => {
|
||||
const availabilityChanged = vi.fn();
|
||||
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||
|
||||
service.removeItem(10).subscribe({ error: vi.fn() });
|
||||
|
||||
const req = httpMock.expectOne('http://api.test/tenants/acme/cart/items/10');
|
||||
req.flush({ message: 'Error' }, { status: 500, statusText: 'Server Error' });
|
||||
|
||||
expect(availabilityChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { catchError, map, Observable, tap } from 'rxjs';
|
||||
|
||||
import { ApiResponse } from '../api-response.interface';
|
||||
import { BaseApiService } from '../base-api.service';
|
||||
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
|
||||
import { TenantService } from '../tenant.service';
|
||||
import { Cart } from './cart.interface';
|
||||
|
||||
@@ -10,6 +11,7 @@ import { Cart } from './cart.interface';
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CartService extends BaseApiService {
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
private readonly tenantService = inject(TenantService);
|
||||
|
||||
private readonly cartState = signal<Cart | null>(null);
|
||||
@@ -60,6 +62,7 @@ export class CartService extends BaseApiService {
|
||||
.pipe(
|
||||
tap((response) => {
|
||||
this.cartState.set(response.data);
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
this.isUpdatingState.set(false);
|
||||
}),
|
||||
catchError((error) => {
|
||||
@@ -93,6 +96,7 @@ export class CartService extends BaseApiService {
|
||||
.pipe(
|
||||
tap((response) => {
|
||||
this.cartState.set(response.data);
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
this.isUpdatingState.set(false);
|
||||
}),
|
||||
catchError((error) => {
|
||||
@@ -111,6 +115,7 @@ export class CartService extends BaseApiService {
|
||||
.pipe(
|
||||
tap((response) => {
|
||||
this.cartState.set(response.data);
|
||||
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||
this.isUpdatingState.set(false);
|
||||
}),
|
||||
catchError((error) => {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable, Subject } from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CatalogAvailabilityService {
|
||||
private readonly availabilityChangedSubject = new Subject<void>();
|
||||
|
||||
readonly availabilityChanged$: Observable<void> = this.availabilityChangedSubject.asObservable();
|
||||
|
||||
notifyAvailabilityChanged(): void {
|
||||
this.availabilityChangedSubject.next();
|
||||
}
|
||||
}
|
||||
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
59
src/app/core/services/catalog/catalog-availability.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { CatalogAvailability } from './catalog.interface';
|
||||
import {
|
||||
allowsCatalogAction,
|
||||
combineCatalogAvailability,
|
||||
createCatalogAvailability,
|
||||
maximumCatalogQuantity,
|
||||
} from './catalog-availability';
|
||||
|
||||
describe('catalog availability', () => {
|
||||
it('represents hidden items without irrelevant actions or quantities', () => {
|
||||
const availability = createCatalogAvailability(0);
|
||||
|
||||
expect(availability).toEqual({
|
||||
state: 'hidden',
|
||||
reasons: [
|
||||
{
|
||||
code: 'out_of_stock',
|
||||
message: 'Este producto no tiene stock disponible.',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(allowsCatalogAction(availability, 'buy_now')).toBe(false);
|
||||
expect(maximumCatalogQuantity(availability)).toBe(0);
|
||||
});
|
||||
|
||||
it('intersects product and variant actions and quantities', () => {
|
||||
const product: CatalogAvailability = {
|
||||
state: 'visible',
|
||||
maximum_quantity: 3,
|
||||
allowed_actions: ['select_variant', 'change_quantity'],
|
||||
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
|
||||
};
|
||||
const variant: CatalogAvailability = {
|
||||
state: 'visible',
|
||||
maximum_quantity: 2,
|
||||
allowed_actions: ['change_quantity', 'add_to_cart'],
|
||||
reasons: [],
|
||||
};
|
||||
|
||||
expect(combineCatalogAvailability(product, variant)).toEqual({
|
||||
state: 'visible',
|
||||
maximum_quantity: 2,
|
||||
allowed_actions: ['change_quantity'],
|
||||
reasons: [{ code: 'limited', message: 'Corregí la selección.' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('lets a hidden decision win composition', () => {
|
||||
const availability = combineCatalogAvailability(
|
||||
createCatalogAvailability(5),
|
||||
createCatalogAvailability(0),
|
||||
);
|
||||
|
||||
expect(availability.state).toBe('hidden');
|
||||
expect(allowsCatalogAction(availability, 'add_to_cart')).toBe(false);
|
||||
});
|
||||
});
|
||||
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
80
src/app/core/services/catalog/catalog-availability.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { CatalogAction, CatalogAvailability } from './catalog.interface';
|
||||
|
||||
const ALL_CATALOG_ACTIONS: CatalogAction[] = [
|
||||
'select_variant',
|
||||
'change_quantity',
|
||||
'add_to_cart',
|
||||
'buy_now',
|
||||
];
|
||||
|
||||
export const AVAILABLE_CATALOG_AVAILABILITY: CatalogAvailability = {
|
||||
state: 'visible',
|
||||
maximum_quantity: null,
|
||||
allowed_actions: ALL_CATALOG_ACTIONS,
|
||||
reasons: [],
|
||||
};
|
||||
|
||||
export function createCatalogAvailability(maximumQuantity: number | null): CatalogAvailability {
|
||||
const unavailable = maximumQuantity === 0;
|
||||
|
||||
if (unavailable) {
|
||||
return {
|
||||
state: 'hidden',
|
||||
reasons: [
|
||||
{
|
||||
code: 'out_of_stock',
|
||||
message: 'Este producto no tiene stock disponible.',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
state: 'visible',
|
||||
maximum_quantity: maximumQuantity,
|
||||
allowed_actions: [...ALL_CATALOG_ACTIONS],
|
||||
reasons: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function primaryAvailabilityMessage(availability: CatalogAvailability): string | null {
|
||||
return availability.reasons[0]?.message ?? null;
|
||||
}
|
||||
|
||||
export function allowsCatalogAction(
|
||||
availability: CatalogAvailability,
|
||||
action: CatalogAction,
|
||||
): boolean {
|
||||
return availability.state === 'visible' && availability.allowed_actions.includes(action);
|
||||
}
|
||||
|
||||
export function maximumCatalogQuantity(availability: CatalogAvailability): number | null {
|
||||
return availability.state === 'visible' ? availability.maximum_quantity : 0;
|
||||
}
|
||||
|
||||
export function combineCatalogAvailability(
|
||||
product: CatalogAvailability,
|
||||
variant?: CatalogAvailability | null,
|
||||
): CatalogAvailability {
|
||||
if (!variant) return product;
|
||||
|
||||
const reasons = [...product.reasons, ...variant.reasons];
|
||||
if (product.state === 'hidden' || variant.state === 'hidden') {
|
||||
return { state: 'hidden', reasons };
|
||||
}
|
||||
|
||||
return {
|
||||
state: 'visible',
|
||||
maximum_quantity: minimumNullable(product.maximum_quantity, variant.maximum_quantity),
|
||||
allowed_actions: product.allowed_actions.filter((action) =>
|
||||
variant.allowed_actions.includes(action),
|
||||
),
|
||||
reasons,
|
||||
};
|
||||
}
|
||||
|
||||
function minimumNullable(left: number | null, right: number | null): number | null {
|
||||
if (left === null) return right;
|
||||
if (right === null) return left;
|
||||
return Math.min(left, right);
|
||||
}
|
||||
@@ -49,6 +49,25 @@ export interface ProductAttribute {
|
||||
|
||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
||||
|
||||
export interface CatalogRestriction {
|
||||
code: 'out_of_stock' | 'user_quota_reached' | string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type CatalogAction = 'select_variant' | 'change_quantity' | 'add_to_cart' | 'buy_now';
|
||||
|
||||
export type CatalogAvailability =
|
||||
| {
|
||||
state: 'hidden';
|
||||
reasons: CatalogRestriction[];
|
||||
}
|
||||
| {
|
||||
state: 'visible';
|
||||
maximum_quantity: number | null;
|
||||
allowed_actions: CatalogAction[];
|
||||
reasons: CatalogRestriction[];
|
||||
};
|
||||
|
||||
export interface CatalogVariantOption {
|
||||
value: string;
|
||||
label: string;
|
||||
@@ -66,7 +85,7 @@ export interface CatalogItemVariant {
|
||||
event_date_id?: number | null;
|
||||
event_date_ids?: number[];
|
||||
event_dates?: string[];
|
||||
stock_tecnico: number | null;
|
||||
availability: CatalogAvailability;
|
||||
minimum_use_date?: string | null;
|
||||
maximum_use_date?: string | null;
|
||||
effective_minimum_use_date?: string | null;
|
||||
@@ -98,7 +117,7 @@ export interface CatalogItemDetail {
|
||||
attributes: ProductAttribute[];
|
||||
variants: CatalogItemVariant[];
|
||||
selected_variant?: SelectedCatalogItemVariant;
|
||||
stock_tecnico?: number | null;
|
||||
availability: CatalogAvailability;
|
||||
images?: string[];
|
||||
}
|
||||
|
||||
@@ -113,7 +132,7 @@ export interface CatalogFeaturedItemVariant {
|
||||
id: number;
|
||||
descripcion?: string | null;
|
||||
precio?: string;
|
||||
stock_tecnico: number | null;
|
||||
availability: CatalogAvailability;
|
||||
values: Record<string, CatalogVariantValue>;
|
||||
}
|
||||
|
||||
@@ -145,7 +164,7 @@ export interface CatalogFeaturedItem {
|
||||
descripcion?: string | null;
|
||||
precio: number | string;
|
||||
image?: string | null;
|
||||
stock_tecnico?: number | null;
|
||||
availability: CatalogAvailability;
|
||||
variants?: CatalogFeaturedItemVariant[];
|
||||
}
|
||||
|
||||
@@ -155,6 +174,7 @@ export type CatalogFeaturedItems =
|
||||
|
||||
export interface CatalogFeaturedGroup {
|
||||
id: number;
|
||||
code: string;
|
||||
title: string;
|
||||
layout: CatalogProductLayout;
|
||||
group_layout: CatalogGroupLayout;
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Injectable } from '@angular/core';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
||||
import { BaseApiService } from './base-api.service';
|
||||
|
||||
export interface UpdatePurchaseCustomerPayload {
|
||||
@@ -130,7 +132,7 @@ export class CheckoutService extends BaseApiService {
|
||||
async generatePaymentIntent(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
method: 'qr' | 'transfer' | 'telepagos',
|
||||
method: 'qr' | 'transfer',
|
||||
payerDni?: string,
|
||||
): Promise<any> {
|
||||
const payload: any = { method };
|
||||
@@ -169,46 +171,6 @@ export class CheckoutService extends BaseApiService {
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async updateItemQuantity(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
itemId: number,
|
||||
quantity: number,
|
||||
): Promise<PurchaseDetailResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
||||
{ quantity },
|
||||
),
|
||||
);
|
||||
|
||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||
if (!purchase) {
|
||||
throw new Error('Error al actualizar la cantidad del producto.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async prepareItemEditing(
|
||||
tenantCode: string,
|
||||
purchaseId: number,
|
||||
): Promise<PurchaseDetailResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/edit-items`,
|
||||
{},
|
||||
),
|
||||
);
|
||||
|
||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||
if (!purchase) {
|
||||
throw new Error('Error al preparar la compra para editarla.');
|
||||
}
|
||||
|
||||
return purchase;
|
||||
}
|
||||
|
||||
async completePurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||
@@ -266,12 +228,20 @@ export class CheckoutService extends BaseApiService {
|
||||
async getPurchases(
|
||||
tenantCode: string,
|
||||
status?: string,
|
||||
): Promise<{ data: PurchaseSummaryResponse[] }> {
|
||||
let url = `${environment.url}tenants/${tenantCode}/compras`;
|
||||
if (status) {
|
||||
url += `?status=${status}`;
|
||||
}
|
||||
const response = await firstValueFrom(this.http.get<{ data: PurchaseSummaryResponse[] }>(url));
|
||||
pagination: ApiPaginationQueryParams = {},
|
||||
): Promise<ApiPaginatedResponse<PurchaseSummaryResponse[]>> {
|
||||
const params: Record<string, string | number> = {};
|
||||
|
||||
if (status) params['status'] = status;
|
||||
if (pagination.page) params['page'] = pagination.page;
|
||||
if (pagination.per_page) params['per_page'] = pagination.per_page;
|
||||
|
||||
const response = await firstValueFrom(
|
||||
this.http.get<ApiPaginatedResponse<PurchaseSummaryResponse[]>>(
|
||||
`${environment.url}tenants/${tenantCode}/compras`,
|
||||
{ params },
|
||||
),
|
||||
);
|
||||
if (!response) {
|
||||
throw new Error('Error al obtener las compras.');
|
||||
}
|
||||
|
||||
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import '@angular/compiler';
|
||||
import { DefaultUrlSerializer } from '@angular/router';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { Tenant } from './tenant.interface';
|
||||
import { TenantService } from './tenant.service';
|
||||
import { TenantUrlSerializer } from './tenant-url.serializer';
|
||||
|
||||
describe('TenantUrlSerializer', () => {
|
||||
const defaultSerializer = new DefaultUrlSerializer();
|
||||
|
||||
function createSerializer(basePath: string): TenantUrlSerializer {
|
||||
const tenantService = {
|
||||
getTenant: () => ({ base_path: basePath }) as Tenant,
|
||||
} as TenantService;
|
||||
|
||||
return new TenantUrlSerializer(tenantService);
|
||||
}
|
||||
|
||||
it('keeps root tenants unchanged', () => {
|
||||
const serializer = createSerializer('/');
|
||||
const tree = serializer.parse('/producto/123?ref=home');
|
||||
|
||||
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||
expect(serializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||
});
|
||||
|
||||
it('removes the tenant base path when parsing and restores it when serializing', () => {
|
||||
const serializer = createSerializer('/desfile');
|
||||
const tree = serializer.parse('/desfile/producto/123?ref=home#detalle');
|
||||
|
||||
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home#detalle');
|
||||
expect(serializer.serialize(tree)).toBe('/desfile/producto/123?ref=home#detalle');
|
||||
});
|
||||
|
||||
it('maps the tenant base path to the application root', () => {
|
||||
const serializer = createSerializer('/desfile/');
|
||||
const tree = serializer.parse('/desfile');
|
||||
|
||||
expect(defaultSerializer.serialize(tree)).toBe('/');
|
||||
expect(serializer.serialize(tree)).toBe('/desfile');
|
||||
});
|
||||
|
||||
it('does not strip partial path segment matches', () => {
|
||||
const serializer = createSerializer('/desfile');
|
||||
const tree = serializer.parse('/desfile-shop/producto/123');
|
||||
|
||||
expect(defaultSerializer.serialize(tree)).toBe('/desfile-shop/producto/123');
|
||||
});
|
||||
});
|
||||
66
src/app/core/services/tenant-url.serializer.ts
Normal file
66
src/app/core/services/tenant-url.serializer.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { DefaultUrlSerializer, UrlSerializer, UrlTree } from '@angular/router';
|
||||
|
||||
import { TenantService } from './tenant.service';
|
||||
|
||||
@Injectable()
|
||||
export class TenantUrlSerializer extends UrlSerializer {
|
||||
private readonly defaultSerializer = new DefaultUrlSerializer();
|
||||
|
||||
constructor(private readonly tenantService: TenantService) {
|
||||
super();
|
||||
}
|
||||
|
||||
override parse(url: string): UrlTree {
|
||||
return this.defaultSerializer.parse(this.removeBasePath(url));
|
||||
}
|
||||
|
||||
override serialize(tree: UrlTree): string {
|
||||
const url = this.defaultSerializer.serialize(tree);
|
||||
const basePath = this.basePath();
|
||||
|
||||
if (basePath === '/') {
|
||||
return url;
|
||||
}
|
||||
|
||||
return url === '/' ? basePath : `${basePath}${url}`;
|
||||
}
|
||||
|
||||
private removeBasePath(url: string): string {
|
||||
const basePath = this.basePath();
|
||||
|
||||
if (basePath === '/' || !this.startsWithCompletePathSegment(url, basePath)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const remainder = url.slice(basePath.length);
|
||||
|
||||
if (remainder === '') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return remainder.startsWith('?') || remainder.startsWith('#')
|
||||
? `/${remainder}`
|
||||
: remainder;
|
||||
}
|
||||
|
||||
private basePath(): string {
|
||||
const configuredPath = this.tenantService.getTenant()?.base_path?.trim() ?? '/';
|
||||
|
||||
if (configuredPath === '' || configuredPath === '/') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return `/${configuredPath.replace(/^\/+|\/+$/g, '')}`;
|
||||
}
|
||||
|
||||
private startsWithCompletePathSegment(url: string, basePath: string): boolean {
|
||||
if (!url.startsWith(basePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const boundary = url.charAt(basePath.length);
|
||||
|
||||
return boundary === '' || boundary === '/' || boundary === '?' || boundary === '#';
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
import { ApiResponse } from './api-response.interface';
|
||||
|
||||
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
|
||||
|
||||
export interface CartEditingPolicy {
|
||||
code: CartEditingPolicyCode;
|
||||
allow_modify: boolean;
|
||||
allow_delete: boolean;
|
||||
allow_update_quantity: boolean;
|
||||
allow_update_variant: boolean;
|
||||
}
|
||||
|
||||
export interface BankAccount {
|
||||
id: number;
|
||||
tenant_code: string;
|
||||
@@ -101,7 +111,10 @@ export interface Tenant {
|
||||
codigo: string;
|
||||
nombre: string;
|
||||
dominio: string;
|
||||
base_path?: string;
|
||||
site_title?: string | null;
|
||||
address?: string | null;
|
||||
phone?: string | null;
|
||||
favicon?: string | null;
|
||||
primary_color: string;
|
||||
secondary_color: string;
|
||||
@@ -126,6 +139,9 @@ export interface Tenant {
|
||||
display_categories?: boolean;
|
||||
display_seach_bar?: boolean;
|
||||
display_cart?: boolean;
|
||||
cart_editing_policy?: CartEditingPolicy;
|
||||
checkout_editing_policy?: CartEditingPolicy;
|
||||
display_cart_item_images?: boolean;
|
||||
social_media?: SocialMedia[];
|
||||
menues?: Menu[];
|
||||
categories: Category[];
|
||||
|
||||
@@ -13,6 +13,7 @@ import { StoreSectionComponent } from '../../../../shared/components/store-secti
|
||||
import { ModalService } from '../../../../core/services/modal.service';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||
import { CarouselComponent } from '../../../../shared/components/carousel/carousel.component';
|
||||
@@ -232,7 +233,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1001,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
@@ -243,7 +244,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1002,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
@@ -254,7 +255,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1003,
|
||||
precio: 250000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('c', 'Sector C'),
|
||||
@@ -265,7 +266,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1004,
|
||||
precio: 200000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
@@ -276,7 +277,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1005,
|
||||
precio: 200000,
|
||||
stock_tecnico: 0,
|
||||
availability: createCatalogAvailability(0),
|
||||
values: {
|
||||
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||
sector: ticketOption('a', 'Sector A'),
|
||||
@@ -287,7 +288,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1006,
|
||||
precio: 100000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('b', 'Sector B'),
|
||||
@@ -298,7 +299,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1007,
|
||||
precio: 100000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('b', 'Sector B'),
|
||||
@@ -309,7 +310,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1008,
|
||||
precio: 90000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
@@ -320,7 +321,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1009,
|
||||
precio: 65000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
@@ -331,7 +332,7 @@ export class ReutilizablesTestPageComponent {
|
||||
{
|
||||
id: 1010,
|
||||
precio: 40000,
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: ticketOption('general', 'General'),
|
||||
sector: ticketOption('d', 'Sector D'),
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
.menu-content-section__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
gap: var(--menu-content-prefix-gap, 0.75rem);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
[attr.aria-label]="option.label"
|
||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||
[title]="option.label"
|
||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||
(click)="selectAttributeOption(attribute, option)"
|
||||
>
|
||||
<span class="visually-hidden">{{ option.label }}</span>
|
||||
@@ -33,7 +33,7 @@
|
||||
!availableOptions()[attribute.codigo][option.id]
|
||||
"
|
||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||
[disabled]="disabled() || !availableOptions()[attribute.codigo][option.id]"
|
||||
(click)="selectAttributeOption(attribute, option)"
|
||||
>
|
||||
{{ option.label }}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
|
||||
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
||||
|
||||
describe('ProductAttributeSelectorComponent', () => {
|
||||
@@ -31,7 +32,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 1,
|
||||
stock_tecnico: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
values: { size: 'S' },
|
||||
},
|
||||
]);
|
||||
@@ -51,12 +52,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{
|
||||
id: 1,
|
||||
stock_tecnico: 0,
|
||||
availability: createCatalogAvailability(0),
|
||||
values: { size: 'S' },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
stock_tecnico: 2,
|
||||
availability: createCatalogAvailability(2),
|
||||
values: { size: 'M' },
|
||||
},
|
||||
]);
|
||||
@@ -92,9 +93,9 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
]);
|
||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, stock_tecnico: null, values: { event_date: '1' } },
|
||||
{ id: 2, stock_tecnico: null, values: { event_date: '2' } },
|
||||
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } },
|
||||
{ id: 1, availability: createCatalogAvailability(null), values: { event_date: '1' } },
|
||||
{ id: 2, availability: createCatalogAvailability(null), values: { event_date: '2' } },
|
||||
{ id: 3, availability: createCatalogAvailability(null), values: { event_date: ['1', '2'] } },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -135,8 +136,16 @@ describe('ProductAttributeSelectorComponent', () => {
|
||||
]);
|
||||
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, stock_tecnico: null, values: { size: 'S', internal_type: 'adult' } },
|
||||
{ id: 2, stock_tecnico: null, values: { size: 'M', internal_type: 'child' } },
|
||||
{
|
||||
id: 1,
|
||||
availability: createCatalogAvailability(null),
|
||||
values: { size: 'S', internal_type: 'adult' },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
availability: createCatalogAvailability(null),
|
||||
values: { size: 'M', internal_type: 'child' },
|
||||
},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ProductAttribute,
|
||||
ProductAttributeOption,
|
||||
} from '../../../../core/services/catalog/catalog.interface';
|
||||
import { allowsCatalogAction } from '../../../../core/services/catalog/catalog-availability';
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-attribute-selector',
|
||||
@@ -29,6 +30,7 @@ export class ProductAttributeSelectorComponent {
|
||||
public variants = input<CatalogItemVariant[]>([]);
|
||||
public selectedVariant = input<CatalogItemVariant | null>(null);
|
||||
public inventoryPolicy = input.required<InventoryPolicy>();
|
||||
public disabled = input(false);
|
||||
|
||||
public variantChange = output<CatalogItemVariant | null>();
|
||||
|
||||
@@ -51,22 +53,15 @@ export class ProductAttributeSelectorComponent {
|
||||
const optionNormalized = this.normalizeText(option.value || option.label);
|
||||
const selectedForAttribute = selections[attribute.codigo] ?? [];
|
||||
|
||||
if (
|
||||
!attribute.allow_multi_select &&
|
||||
selectedForAttribute.length >= 1 &&
|
||||
!selectedForAttribute.includes(option.id)
|
||||
) {
|
||||
availability[attribute.codigo][option.id] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
const isAvailable = variants.some((variant) => {
|
||||
if (!this.isVariantAvailable(variant)) return false;
|
||||
|
||||
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||
const desiredOptionIds = selectedForAttribute.includes(option.id)
|
||||
? selectedForAttribute
|
||||
: [...selectedForAttribute, option.id];
|
||||
const desiredOptionIds = attribute.allow_multi_select
|
||||
? selectedForAttribute.includes(option.id)
|
||||
? selectedForAttribute
|
||||
: [...selectedForAttribute, option.id]
|
||||
: [option.id];
|
||||
const desiredValues = desiredOptionIds
|
||||
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
||||
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||
@@ -137,6 +132,8 @@ export class ProductAttributeSelectorComponent {
|
||||
attribute: ProductAttribute,
|
||||
option: ProductAttributeOption,
|
||||
): void {
|
||||
if (this.disabled()) return;
|
||||
|
||||
this.selectedAttributeOptions.update((current) => {
|
||||
const selected = current[attribute.codigo] ?? [];
|
||||
const isMultiple = attribute.allow_multi_select ?? false;
|
||||
@@ -186,7 +183,15 @@ export class ProductAttributeSelectorComponent {
|
||||
return [];
|
||||
}
|
||||
|
||||
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||
const defaultValues =
|
||||
attribute.type === 'event_date'
|
||||
? (
|
||||
variant.event_date_ids ??
|
||||
(variant.event_date_id === null || variant.event_date_id === undefined
|
||||
? []
|
||||
: [variant.event_date_id])
|
||||
).map(String)
|
||||
: this.getVariantAttributeValues(attribute, variant.values);
|
||||
if (defaultValues.length === 0) {
|
||||
return [];
|
||||
}
|
||||
@@ -215,6 +220,17 @@ export class ProductAttributeSelectorComponent {
|
||||
}
|
||||
}
|
||||
|
||||
if (attribute.type === 'event_date') {
|
||||
const variant = this.variants().find((candidate) => candidate.values === variantAttributes);
|
||||
const eventDateIds =
|
||||
variant?.event_date_ids ??
|
||||
(variant?.event_date_id === null || variant?.event_date_id === undefined
|
||||
? []
|
||||
: [variant.event_date_id]);
|
||||
|
||||
return eventDateIds.map(String);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -227,7 +243,7 @@ export class ProductAttributeSelectorComponent {
|
||||
}
|
||||
|
||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||
return this.inventoryPolicy() === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
||||
return allowsCatalogAction(variant.availability, 'select_variant');
|
||||
}
|
||||
|
||||
private findFirstHexValue(value: unknown): string | null {
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
<div class="purchase-item" [routerLink]="[purchase.id]" style="cursor: pointer;">
|
||||
<div class="purchase-info">
|
||||
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
||||
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
||||
</div>
|
||||
<div class="purchase-action">
|
||||
<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow-icon">
|
||||
<path d="M1 1L7 7L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="purchase-item" [routerLink]="[purchase.id]">
|
||||
<div class="purchase-info">
|
||||
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
||||
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
||||
</div>
|
||||
|
||||
@if (purchase.statusMessage) {
|
||||
<span class="purchase-status">{{ purchase.statusMessage }}</span>
|
||||
}
|
||||
|
||||
<div class="purchase-action">
|
||||
<svg
|
||||
width="8"
|
||||
height="14"
|
||||
viewBox="0 0 8 14"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="arrow-icon"
|
||||
>
|
||||
<path
|
||||
d="M1 1L7 7L1 13"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,33 +2,57 @@
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
padding-left:0;
|
||||
transition: box-shadow 0.2s, border-radius 0.2s;
|
||||
gap: 16px;
|
||||
padding: 16px;
|
||||
padding-left: 0;
|
||||
transition:
|
||||
box-shadow 0.2s,
|
||||
border-radius 0.2s;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.purchase-item:hover {
|
||||
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.purchase-item:hover .arrow-icon {
|
||||
color: #5b75ff; /* Blue on hover */
|
||||
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||
}
|
||||
|
||||
.purchase-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.purchase-id {
|
||||
font-weight: bold;
|
||||
color: #666666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.purchase-date {
|
||||
font-weight: 325;
|
||||
color: #666666;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.purchase-status {
|
||||
margin-left: auto;
|
||||
margin-right: 20px;
|
||||
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.purchase-action {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.arrow-icon {
|
||||
width: 8px;
|
||||
height: 14px;
|
||||
|
||||
@@ -9,6 +9,5 @@ import { RouterLink } from '@angular/router';
|
||||
styleUrl: './purchase-list-item.scss',
|
||||
})
|
||||
export class PurchaseListItem {
|
||||
@Input() purchase!: { id: number; date: string };
|
||||
@Input() purchase!: { id: number; date: string; statusMessage?: string | null };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
<div class="purchase-list-container">
|
||||
<ng-container *ngIf="isLoading(); else contentTpl">
|
||||
<!-- Skeleton -->
|
||||
<div class="skeleton-item" *ngFor="let i of [1, 2, 3, 4]">
|
||||
<div class="skeleton-info">
|
||||
<div class="skeleton-id"></div>
|
||||
<div class="skeleton-date"></div>
|
||||
</div>
|
||||
<div class="skeleton-action"></div>
|
||||
<div class="purchase-list-container">
|
||||
@if (isLoading()) {
|
||||
@for (i of [1, 2, 3, 4]; track i) {
|
||||
<div class="skeleton-item">
|
||||
<div class="skeleton-info">
|
||||
<div class="skeleton-id"></div>
|
||||
<div class="skeleton-date"></div>
|
||||
</div>
|
||||
</ng-container>
|
||||
<div class="skeleton-action"></div>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
@if (purchases().length > 0) {
|
||||
@for (purchase of purchases(); track purchase.id; let last = $last) {
|
||||
<app-purchase-list-item [purchase]="purchase"></app-purchase-list-item>
|
||||
@if (!last) {
|
||||
<div class="purchase-divider"></div>
|
||||
}
|
||||
}
|
||||
} @else {
|
||||
<div class="empty-state">Aún no hay compras realizadas</div>
|
||||
}
|
||||
|
||||
<ng-template #contentTpl>
|
||||
<ng-container *ngIf="purchases().length > 0; else emptyTpl">
|
||||
<ng-container *ngFor="let purchase of purchases(); let last = last">
|
||||
<app-purchase-list-item
|
||||
[purchase]="purchase">
|
||||
</app-purchase-list-item>
|
||||
<div class="purchase-divider" *ngIf="!last"></div>
|
||||
</ng-container>
|
||||
</ng-container>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #emptyTpl>
|
||||
<div class="empty-state">
|
||||
Aún no hay compras realizadas
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
@if (pagination(); as paginationData) {
|
||||
@if (paginationData.last_page > 1) {
|
||||
<app-paginator
|
||||
class="purchase-list__paginator"
|
||||
[page]="paginationData.current_page"
|
||||
[totalPages]="paginationData.last_page"
|
||||
[disabled]="isLoading()"
|
||||
(pageChange)="onPageChange($event)"
|
||||
></app-paginator>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.purchase-list__paginator {
|
||||
align-self: center;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.purchase-divider {
|
||||
height: 1px;
|
||||
background-color: #DDDDDD;
|
||||
background-color: #dddddd;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -39,7 +44,7 @@
|
||||
.skeleton-id {
|
||||
width: 100px;
|
||||
height: 1rem;
|
||||
background-color: #EEEEEE;
|
||||
background-color: #eeeeee;
|
||||
border-radius: 4px;
|
||||
animation: pulse 1.5s infinite ease-in-out;
|
||||
}
|
||||
@@ -47,7 +52,7 @@
|
||||
.skeleton-date {
|
||||
width: 150px;
|
||||
height: 0.8rem;
|
||||
background-color: #EEEEEE;
|
||||
background-color: #eeeeee;
|
||||
border-radius: 4px;
|
||||
animation: pulse 1.5s infinite ease-in-out;
|
||||
}
|
||||
@@ -55,19 +60,19 @@
|
||||
.skeleton-action {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background-color: #EEEEEE;
|
||||
background-color: #eeeeee;
|
||||
border-radius: 50%;
|
||||
animation: pulse 1.5s infinite ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
background-color: #EEEEEE;
|
||||
background-color: #eeeeee;
|
||||
}
|
||||
50% {
|
||||
background-color: #E0E0E0;
|
||||
background-color: #e0e0e0;
|
||||
}
|
||||
100% {
|
||||
background-color: #EEEEEE;
|
||||
background-color: #eeeeee;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
|
||||
import { CheckoutService, PurchaseSummaryResponse } from '../../../../../../core/services/checkout.service';
|
||||
import {
|
||||
CheckoutService,
|
||||
PurchaseSummaryResponse,
|
||||
} from '../../../../../../core/services/checkout.service';
|
||||
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||
import { ApiPaginationMeta } from '../../../../../../core/services/api-paginated-response.interface';
|
||||
import { PaginatorComponent } from '../../../../../../shared/components/paginator/paginator.component';
|
||||
|
||||
type PurchaseListViewModel = {
|
||||
id: number;
|
||||
date: string;
|
||||
statusMessage: string | null;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-purchase-list',
|
||||
standalone: true,
|
||||
imports: [CommonModule, PurchaseListItem],
|
||||
imports: [PurchaseListItem, PaginatorComponent],
|
||||
templateUrl: './purchase-list.html',
|
||||
styleUrl: './purchase-list.scss',
|
||||
})
|
||||
@@ -22,21 +27,28 @@ export class PurchaseList implements OnInit {
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly tenantService = inject(TenantService);
|
||||
|
||||
purchases = signal<PurchaseListViewModel[]>([]);
|
||||
isLoading = signal<boolean>(true);
|
||||
protected readonly purchases = signal<PurchaseListViewModel[]>([]);
|
||||
protected readonly pagination = signal<ApiPaginationMeta | null>(null);
|
||||
protected readonly isLoading = signal(true);
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
await this.loadPurchases();
|
||||
}
|
||||
|
||||
protected async onPageChange(page: number): Promise<void> {
|
||||
await this.loadPurchases(page);
|
||||
}
|
||||
|
||||
private async loadPurchases(page = 1): Promise<void> {
|
||||
this.isLoading.set(true);
|
||||
|
||||
try {
|
||||
const tenantCode = this.tenantService.tenant()?.codigo || '';
|
||||
|
||||
const response = await this.checkoutService
|
||||
.withCustomLoading()
|
||||
.getPurchases(tenantCode, 'paid');
|
||||
const mappedPurchases = response.data.map((purchase: PurchaseSummaryResponse) => ({
|
||||
id: purchase.id,
|
||||
date: this.formatDate(purchase.created_at),
|
||||
}));
|
||||
this.purchases.set(mappedPurchases);
|
||||
.getPurchases(this.tenantCode(), 'paid,in_review', { page });
|
||||
|
||||
this.purchases.set(this.mapPurchases(response.data));
|
||||
this.pagination.set(response.meta);
|
||||
} catch (error) {
|
||||
this.toastService.danger('Hubo un error al cargar las compras');
|
||||
} finally {
|
||||
@@ -44,6 +56,18 @@ export class PurchaseList implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
private tenantCode(): string {
|
||||
return this.tenantService.tenant()?.codigo || '';
|
||||
}
|
||||
|
||||
private mapPurchases(purchases: PurchaseSummaryResponse[]): PurchaseListViewModel[] {
|
||||
return purchases.map((purchase) => ({
|
||||
id: purchase.id,
|
||||
date: this.formatDate(purchase.created_at),
|
||||
statusMessage: purchase.status === 'in_review' ? 'Esperando confirmación' : null,
|
||||
}));
|
||||
}
|
||||
|
||||
private formatDate(value: string | null): string {
|
||||
if (!value) {
|
||||
return '-';
|
||||
|
||||
@@ -15,6 +15,27 @@
|
||||
@if (isLoading()) {
|
||||
<p class="purchase-loading">Cargando detalle de compra...</p>
|
||||
} @else if (purchase(); as purchase) {
|
||||
@if (purchase.isInReview) {
|
||||
<section class="purchase-review" aria-labelledby="purchase-review-title">
|
||||
<h3 id="purchase-review-title" class="purchase-review__title">ESPERANDO CONFIRMACIÓN</h3>
|
||||
<p class="purchase-review__message">
|
||||
Tu compra aún no ha sido confirmada.<br />
|
||||
Si no te contactaste con nosotros, podés hacerlo a través del siguiente WhatsApp
|
||||
</p>
|
||||
|
||||
@if (whatsappUrl()) {
|
||||
<app-button
|
||||
type="button"
|
||||
variant="primary"
|
||||
hostClass="purchase-review__button"
|
||||
(click)="openWhatsApp()"
|
||||
>
|
||||
WhatsApp
|
||||
</app-button>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
<div
|
||||
class="d-flex justify-content-between align-items-center mb-4 pb-3"
|
||||
style="border-bottom: 1px solid #dddddd"
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
}
|
||||
|
||||
.account-page {
|
||||
--menu-content-prefix-gap: 0;
|
||||
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
@@ -50,6 +52,32 @@
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.purchase-review {
|
||||
padding-bottom: 2rem;
|
||||
margin-bottom: 2rem;
|
||||
border-bottom: 1px solid #dddddd;
|
||||
}
|
||||
|
||||
.purchase-review__title {
|
||||
margin: 0 0 0.5rem;
|
||||
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.purchase-review__message {
|
||||
margin: 0 0 1.5rem;
|
||||
color: #777777;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.purchase-review__button {
|
||||
width: 185px;
|
||||
}
|
||||
|
||||
.purchase-loading,
|
||||
.purchase-empty {
|
||||
color: #666666;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { Component, OnInit, computed, inject, signal } from '@angular/core';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
|
||||
import {
|
||||
@@ -8,6 +7,7 @@ import {
|
||||
} from '../../../../../../core/services/checkout.service';
|
||||
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||
import { ButtonComponent } from '../../../../../../shared/components/button/button.component';
|
||||
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
|
||||
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
|
||||
|
||||
@@ -16,12 +16,13 @@ type PurchaseDetailViewModel = {
|
||||
date: string;
|
||||
total: string;
|
||||
items: PurchaseItemViewModel[];
|
||||
isInReview: boolean;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-purchase-detail-page',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterLink, PurchaseItem, MenuContentSectionComponent],
|
||||
imports: [RouterLink, PurchaseItem, MenuContentSectionComponent, ButtonComponent],
|
||||
templateUrl: './purchase-detail-page.html',
|
||||
styleUrl: './purchase-detail-page.scss',
|
||||
})
|
||||
@@ -34,6 +35,12 @@ export class PurchaseDetailPage implements OnInit {
|
||||
|
||||
readonly isLoading = signal(true);
|
||||
readonly purchase = signal<PurchaseDetailViewModel | null>(null);
|
||||
protected readonly whatsappUrl = computed(
|
||||
() =>
|
||||
this.tenantService
|
||||
.tenant()
|
||||
?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? null,
|
||||
);
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
const purchaseId = this.route.snapshot.paramMap.get('id');
|
||||
@@ -54,6 +61,7 @@ export class PurchaseDetailPage implements OnInit {
|
||||
date: this.formatDate(response.created_at),
|
||||
total: response.total,
|
||||
items: this.mapItems(response),
|
||||
isInReview: response.status === 'in_review',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch purchase detail:', error);
|
||||
@@ -64,6 +72,14 @@ export class PurchaseDetailPage implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
protected openWhatsApp(): void {
|
||||
const url = this.whatsappUrl();
|
||||
|
||||
if (url) {
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
}
|
||||
|
||||
private formatDate(value: string | null): string {
|
||||
if (!value) {
|
||||
return '-';
|
||||
|
||||
@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
@@ -107,6 +108,16 @@ describe('CategoryItemsPageComponent', () => {
|
||||
expect(Array.isArray(productList.items())).toBe(false);
|
||||
});
|
||||
|
||||
it('reloads the current category page when catalog availability changes', () => {
|
||||
const fixture = TestBed.createComponent(CategoryItemsPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||
|
||||
expect(getCategoryItems).toHaveBeenCalledTimes(2);
|
||||
expect(getCategoryItems).toHaveBeenLastCalledWith(7, { page: 1 });
|
||||
});
|
||||
|
||||
it('does not request the API when the category id is invalid', () => {
|
||||
TestBed.overrideProvider(ActivatedRoute, {
|
||||
useValue: {
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
finalize,
|
||||
map,
|
||||
of,
|
||||
startWith,
|
||||
switchMap,
|
||||
tap,
|
||||
} from 'rxjs';
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
CategoryItemsResponse,
|
||||
} from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import {
|
||||
@@ -50,6 +52,7 @@ interface CategoryRouteState {
|
||||
})
|
||||
export class CategoryItemsPageComponent {
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
private readonly catalogService = inject(CatalogService);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -65,22 +68,29 @@ export class CategoryItemsPageComponent {
|
||||
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
|
||||
|
||||
constructor() {
|
||||
combineLatest([this.route.paramMap, this.route.queryParamMap])
|
||||
.pipe(
|
||||
map(
|
||||
([params, queryParams]): CategoryRouteState => ({
|
||||
categoryId: this.parsePositiveInteger(params.get('id')),
|
||||
page: this.parsePositiveInteger(queryParams.get('page'), 1),
|
||||
}),
|
||||
),
|
||||
distinctUntilChanged(
|
||||
(previous, current) =>
|
||||
previous.categoryId === current.categoryId && previous.page === current.page,
|
||||
),
|
||||
tap(() => {
|
||||
this.results.set(null);
|
||||
this.error.set(null);
|
||||
const routeState$ = combineLatest([this.route.paramMap, this.route.queryParamMap]).pipe(
|
||||
map(
|
||||
([params, queryParams]): CategoryRouteState => ({
|
||||
categoryId: this.parsePositiveInteger(params.get('id')),
|
||||
page: this.parsePositiveInteger(queryParams.get('page'), 1),
|
||||
}),
|
||||
),
|
||||
distinctUntilChanged(
|
||||
(previous, current) =>
|
||||
previous.categoryId === current.categoryId && previous.page === current.page,
|
||||
),
|
||||
tap(() => {
|
||||
this.results.set(null);
|
||||
this.error.set(null);
|
||||
}),
|
||||
);
|
||||
|
||||
combineLatest([
|
||||
routeState$,
|
||||
this.catalogAvailabilityService.availabilityChanged$.pipe(startWith(undefined)),
|
||||
])
|
||||
.pipe(
|
||||
map(([routeState]) => routeState),
|
||||
switchMap(({ categoryId, page }) => {
|
||||
if (categoryId === 0) {
|
||||
this.error.set('La categoría solicitada no es válida.');
|
||||
|
||||
@@ -5,13 +5,12 @@
|
||||
</div>
|
||||
} @else {
|
||||
<div class="checkout-page">
|
||||
<div
|
||||
class="checkout-page__stepper-col"
|
||||
[class.checkout-page__stepper-col--editing]="isEditingItems()"
|
||||
[attr.aria-hidden]="isEditingItems()"
|
||||
[attr.inert]="isEditingItems() ? '' : null"
|
||||
>
|
||||
<app-stepper #stepper [initialStepIndex]="checkoutStepIndex()">
|
||||
<div class="checkout-page__stepper-col">
|
||||
<app-stepper
|
||||
#stepper
|
||||
[initialStepIndex]="checkoutStepIndex()"
|
||||
[disabled]="hasSubmittedTransfer()"
|
||||
>
|
||||
<app-step label="Datos" [isValid]="isStep1Valid()">
|
||||
<app-checkout-data-step
|
||||
[form]="form"
|
||||
@@ -24,6 +23,7 @@
|
||||
<app-checkout-payment-step
|
||||
[paymentMethods]="paymentMethods"
|
||||
[selectedPaymentMethod]="selectedPaymentMethod()"
|
||||
[paymentMethodDisabled]="hasSubmittedTransfer()"
|
||||
[copiedTransferField]="copiedTransferField()"
|
||||
[transferAccount]="transferAccount()"
|
||||
[transferDni]="transferDni()"
|
||||
@@ -45,12 +45,6 @@
|
||||
</app-stepper>
|
||||
</div>
|
||||
|
||||
@if (isEditingItems()) {
|
||||
<div class="checkout-page__editing-notice" role="status">
|
||||
<p>Terminá de modificar las cantidades para continuar con el pago.</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="checkout-page__cart-col">
|
||||
<app-cart
|
||||
title="COMPRA"
|
||||
@@ -58,16 +52,13 @@
|
||||
[subtotal]="cartSubtotal()"
|
||||
[discount]="cartDiscount()"
|
||||
[total]="cartTotal()"
|
||||
[allowEditing]="
|
||||
createdPurchase()?.status === 'created' || createdPurchase()?.status === 'pending_payment'
|
||||
"
|
||||
[allowRemove]="false"
|
||||
[persistQuantityChanges]="false"
|
||||
[editing]="isEditingItems()"
|
||||
[editingDisabled]="isUpdatingItem() || isPreparingItemEdit()"
|
||||
[readonly]="true"
|
||||
[allowModify]="true"
|
||||
[showModifyWhenReadonly]="true"
|
||||
[modifyAsAction]="true"
|
||||
[editingDisabled]="isPurchaseModificationDisabled()"
|
||||
backgroundColor="transparent"
|
||||
(editingChange)="onEditingItemsChange($event)"
|
||||
(itemQuantityChange)="onPurchaseItemQuantityChange($event)"
|
||||
(modify)="onModifyPurchase()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
order: 1;
|
||||
}
|
||||
|
||||
.checkout-page__stepper-col,
|
||||
.checkout-page__editing-notice {
|
||||
.checkout-page__stepper-col {
|
||||
order: 2;
|
||||
}
|
||||
}
|
||||
@@ -21,27 +20,6 @@
|
||||
min-width: 0;
|
||||
border-radius: 4px;
|
||||
min-height: 420px;
|
||||
|
||||
&--editing {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
&__editing-notice {
|
||||
display: grid;
|
||||
min-height: 420px;
|
||||
place-items: center;
|
||||
padding: 2rem;
|
||||
border-radius: 4px;
|
||||
background: #f5f5f5;
|
||||
color: #666666;
|
||||
text-align: center;
|
||||
|
||||
p {
|
||||
max-width: 360px;
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
&__cart-col {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { signal } from '@angular/core';
|
||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
@@ -6,33 +7,40 @@ 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';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { CartEditingPolicy } from '../../../../core/services/tenant.interface';
|
||||
import { CheckoutPageComponent } from './checkout-page.component';
|
||||
|
||||
describe('CheckoutPageComponent payment validation', () => {
|
||||
let checkoutServiceStub: {
|
||||
startCheckout: ReturnType<typeof vi.fn>;
|
||||
updateCustomerData: ReturnType<typeof vi.fn>;
|
||||
updateItemQuantity: ReturnType<typeof vi.fn>;
|
||||
prepareItemEditing: ReturnType<typeof vi.fn>;
|
||||
cancelPurchase: ReturnType<typeof vi.fn>;
|
||||
generatePaymentIntent: ReturnType<typeof vi.fn>;
|
||||
getPurchase: ReturnType<typeof vi.fn>;
|
||||
submitPurchaseForReview: ReturnType<typeof vi.fn>;
|
||||
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: {
|
||||
start: ReturnType<typeof vi.fn>;
|
||||
stop: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let cartServiceStub: { loadCart: ReturnType<typeof vi.fn> };
|
||||
let routeQueryParamMap: ReturnType<typeof convertToParamMap>;
|
||||
let authUserState: ReturnType<typeof signal>;
|
||||
let tenantState: ReturnType<
|
||||
typeof signal<{
|
||||
codigo: string;
|
||||
checkout_editing_policy?: CartEditingPolicy;
|
||||
}>
|
||||
>;
|
||||
|
||||
beforeAll(() => {
|
||||
try {
|
||||
@@ -53,50 +61,44 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
total: '0.00',
|
||||
}),
|
||||
updateCustomerData: vi.fn(),
|
||||
updateItemQuantity: vi.fn(),
|
||||
prepareItemEditing: vi.fn(),
|
||||
cancelPurchase: vi.fn().mockResolvedValue({ status: 'cancelled' }),
|
||||
generatePaymentIntent: vi.fn().mockResolvedValue({
|
||||
qr_data: { qr_code: 'qr-value' },
|
||||
}),
|
||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'in_review' }),
|
||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||
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() };
|
||||
cartServiceStub = {
|
||||
loadCart: vi.fn().mockReturnValue(of({ id: 30, items: [], subtotal: '0.00' })),
|
||||
};
|
||||
routeQueryParamMap = convertToParamMap({});
|
||||
authUserState = signal(null);
|
||||
tenantState = signal({
|
||||
codigo: 'tenant-test',
|
||||
checkout_editing_policy: {
|
||||
code: 'full',
|
||||
allow_modify: true,
|
||||
allow_delete: true,
|
||||
allow_update_quantity: true,
|
||||
allow_update_variant: true,
|
||||
},
|
||||
});
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CheckoutPageComponent],
|
||||
providers: [
|
||||
{ provide: CheckoutService, useValue: checkoutServiceStub },
|
||||
{ provide: CatalogService, useValue: { getCatalogItem: vi.fn() } },
|
||||
{ provide: CartService, useValue: cartServiceStub },
|
||||
{ provide: TenantService, useValue: { tenant: signal({ codigo: 'tenant-test' }) } },
|
||||
{ provide: TenantService, useValue: { tenant: tenantState } },
|
||||
{ provide: AuthService, useValue: { user: authUserState } },
|
||||
{ provide: GlobalLoadingService, useValue: globalLoadingServiceStub },
|
||||
{ provide: ToastService, useValue: toastServiceStub },
|
||||
{ provide: CartService, useValue: cartServiceStub },
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: {
|
||||
@@ -142,7 +144,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);
|
||||
});
|
||||
@@ -194,46 +195,95 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('checks a transfer once and redirects to purchase status while pending', async () => {
|
||||
it('polls a transfer every three seconds up to four attempts', async () => {
|
||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'pending_payment' });
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
expect(component.transferValidationStatus()).toBe('pending');
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
expect(component.transferValidationStatus()).toBe('checking');
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
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(routerStub.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prevents modifying the purchase after Ya transferí is clicked', async () => {
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(component.hasSubmittedTransfer()).toBe(true);
|
||||
expect(component.isPurchaseModificationDisabled()).toBe(true);
|
||||
|
||||
await component.selectPaymentMethod('qr');
|
||||
await component.onModifyPurchase();
|
||||
|
||||
expect(component.selectedPaymentMethod()).toBe('transfer');
|
||||
expect(checkoutServiceStub.generatePaymentIntent).not.toHaveBeenCalled();
|
||||
expect(checkoutServiceStub.cancelPurchase).not.toHaveBeenCalled();
|
||||
expect(globalLoadingServiceStub.start).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('navigates after a transfer is confirmed as paid', async () => {
|
||||
checkoutServiceStub.submitPurchaseForReview.mockResolvedValue({ status: 'paid' });
|
||||
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' });
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
|
||||
expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledWith('tenant-test', 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);
|
||||
checkoutServiceStub.getPurchase.mockRejectedValue(new Error('network error'));
|
||||
const { component } = createComponent();
|
||||
component.selectedPaymentMethod.set('transfer');
|
||||
|
||||
await component.onComplete();
|
||||
await vi.advanceTimersByTimeAsync(12_000);
|
||||
|
||||
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(4);
|
||||
expect(component.transferValidationStatus()).toBe('error');
|
||||
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');
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels transfer polling when the component is destroyed', async () => {
|
||||
const checkout = createComponent();
|
||||
checkout.component.selectedPaymentMethod.set('transfer');
|
||||
await checkout.component.onComplete();
|
||||
checkout.fixture.destroy();
|
||||
await vi.advanceTimersByTimeAsync(12_000);
|
||||
expect(checkoutServiceStub.getPurchase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('loads purchase items but prefills customer data from the user', async () => {
|
||||
@@ -366,11 +416,7 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
|
||||
expect(component.checkoutStepIndex()).toBe(1);
|
||||
expect(component.selectedPaymentMethod()).toBe('qr');
|
||||
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledWith(
|
||||
'tenant-test',
|
||||
25,
|
||||
'qr',
|
||||
);
|
||||
expect(checkoutServiceStub.generatePaymentIntent).toHaveBeenCalledWith('tenant-test', 25, 'qr');
|
||||
expect(component.qrData()).toBe('qr-value');
|
||||
expect(component.qrPaymentStatus()).toBe('waiting');
|
||||
});
|
||||
@@ -414,62 +460,73 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
|
||||
});
|
||||
|
||||
it('updates a purchase item while editing and refreshes checkout totals', async () => {
|
||||
const updatedPurchase = {
|
||||
id: 25,
|
||||
items: [],
|
||||
subtotal: '300.00',
|
||||
total: '300.00',
|
||||
};
|
||||
checkoutServiceStub.updateItemQuantity.mockResolvedValue(updatedPurchase);
|
||||
const { component } = createComponent();
|
||||
component.isEditingItems.set(true);
|
||||
|
||||
await component.onPurchaseItemQuantityChange({
|
||||
item: {
|
||||
cartItemId: 91,
|
||||
imageUrl: null,
|
||||
product: 'Remera',
|
||||
originalPrice: null,
|
||||
discountedPrice: 100,
|
||||
discountPercentage: null,
|
||||
attributes: [],
|
||||
quantity: 2,
|
||||
},
|
||||
quantity: 3,
|
||||
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 },
|
||||
});
|
||||
const { component } = createComponent();
|
||||
|
||||
expect(checkoutServiceStub.updateItemQuantity).toHaveBeenCalledWith('tenant-test', 25, 91, 3);
|
||||
expect(component.createdPurchase()).toBe(updatedPurchase);
|
||||
expect(component.isUpdatingItem()).toBe(false);
|
||||
await component.onModifyPurchase();
|
||||
|
||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(message);
|
||||
expect(routerStub.navigate).not.toHaveBeenCalled();
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||
expect(component.isCancellingPurchase()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the payment step selected while editing and regenerates payment afterward', async () => {
|
||||
const editablePurchase = {
|
||||
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) => {
|
||||
finishNavigation = resolve;
|
||||
}),
|
||||
);
|
||||
const { component } = createComponent();
|
||||
component.createdPurchase.set({
|
||||
id: 25,
|
||||
status: 'created',
|
||||
items: [],
|
||||
subtotal: '100.00',
|
||||
total: '100.00',
|
||||
};
|
||||
checkoutServiceStub.prepareItemEditing.mockResolvedValue(editablePurchase);
|
||||
const { component } = createComponent();
|
||||
component.stepper = { currentStepIndex: signal(1) };
|
||||
const selectPaymentMethod = vi
|
||||
.spyOn(component, 'selectPaymentMethod')
|
||||
.mockResolvedValue(undefined);
|
||||
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',
|
||||
});
|
||||
const modification = component.onModifyPurchase();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
await component.onEditingItemsChange(true);
|
||||
expect(checkoutServiceStub.cancelPurchase).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).not.toHaveBeenCalled();
|
||||
expect(component.createdPurchaseId()).toBeNull();
|
||||
expect(component.createdPurchase()).toBeNull();
|
||||
expect(routerStub.navigate).toHaveBeenCalledWith(['/'], {
|
||||
queryParams: { openCart: true },
|
||||
});
|
||||
|
||||
expect(checkoutServiceStub.prepareItemEditing).toHaveBeenCalledWith('tenant-test', 25);
|
||||
expect(component.isEditingItems()).toBe(true);
|
||||
expect(component.createdPurchase()).toBe(editablePurchase);
|
||||
finishNavigation(true);
|
||||
await modification;
|
||||
|
||||
await component.onEditingItemsChange(false);
|
||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||
|
||||
expect(component.stepper.currentStepIndex()).toBe(1);
|
||||
expect(selectPaymentMethod).toHaveBeenCalledWith('qr');
|
||||
expect(component.isEditingItems()).toBe(false);
|
||||
await component.canDeactivate();
|
||||
});
|
||||
|
||||
it('updates customer data on the existing purchase before payment', async () => {
|
||||
@@ -506,14 +563,78 @@ describe('CheckoutPageComponent payment validation', () => {
|
||||
expect(component.stepper.next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('cancels the pending purchase before allowing navigation away', 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).toHaveBeenCalled();
|
||||
expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
|
||||
expect(cartServiceStub.loadCart).toHaveBeenCalledOnce();
|
||||
expect(component.createdPurchaseId()).toBeNull();
|
||||
expect(globalLoadingServiceStub.start).toHaveBeenCalledOnce();
|
||||
expect(globalLoadingServiceStub.stop).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('prevents leaving checkout when the purchase cannot be cancelled', async () => {
|
||||
checkoutServiceStub.cancelPurchase.mockRejectedValue({
|
||||
error: { message: 'No se pudo cancelar la compra.' },
|
||||
});
|
||||
const { component } = createComponent();
|
||||
|
||||
await expect(component.canDeactivate()).resolves.toBe(false);
|
||||
|
||||
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo cancelar la compra.');
|
||||
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,
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { FormBuilder, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { firstValueFrom, startWith } from 'rxjs';
|
||||
@@ -19,8 +20,9 @@ import {
|
||||
PurchaseDetailResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { GlobalLoadingService } from '../../../../core/services/global-loading/global-loading.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { BankAccount } from '../../../../core/services/tenant.interface';
|
||||
import { CartComponent, CartItemMock } from '../../../../shared/components/cart/cart.component';
|
||||
import { StepComponent } from '../../../../shared/components/stepper/step.component';
|
||||
import { StepperComponent } from '../../../../shared/components/stepper/stepper.component';
|
||||
@@ -36,6 +38,12 @@ import {
|
||||
TransferValidationStatus,
|
||||
} from './checkout-page.models';
|
||||
|
||||
interface ApiErrorResponse {
|
||||
code?: string;
|
||||
message?: string;
|
||||
errors?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-checkout-page',
|
||||
standalone: true,
|
||||
@@ -57,15 +65,23 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly authService = inject(AuthService);
|
||||
private readonly globalLoadingService = inject(GlobalLoadingService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly qrPollingIntervalMs = 5_000;
|
||||
private readonly qrPollingMaxAttempts = 9;
|
||||
private readonly qrPollingMaxAttempts = 120;
|
||||
private readonly transferPollingIntervalMs = 3_000;
|
||||
private readonly transferPollingMaxAttempts = 209;
|
||||
|
||||
private qrPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
private qrPollingAttempts = 0;
|
||||
private qrPollingRunId = 0;
|
||||
private transferPollingTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
private transferPollingAttempts = 0;
|
||||
private transferPollingRunId = 0;
|
||||
private paymentMethodRequestId = 0;
|
||||
private navigationStarted = false;
|
||||
private cancelPurchasePromise: Promise<boolean> | null = null;
|
||||
|
||||
@ViewChild(StepperComponent) stepper!: StepperComponent;
|
||||
|
||||
@@ -79,7 +95,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly createdPurchase = signal<PurchaseDetailResponse | null>(null);
|
||||
protected readonly isLoadingPurchase = signal(true);
|
||||
protected readonly checkoutStepIndex = signal(0);
|
||||
|
||||
protected readonly cartSubtotal = computed(() => {
|
||||
const purchase = this.createdPurchase();
|
||||
return purchase ? parseFloat(purchase.subtotal) : 0;
|
||||
@@ -101,7 +116,6 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly paymentMethods: ReadonlyArray<PaymentMethodOption> = [
|
||||
{ id: 'qr', label: 'QR' },
|
||||
{ id: 'transfer', label: 'Transferencia' },
|
||||
{ id: 'telepagos', label: 'TelePagos' },
|
||||
];
|
||||
protected readonly selectedPaymentMethod = signal<PaymentMethod>('qr');
|
||||
protected readonly copiedTransferField = signal<TransferField | null>(null);
|
||||
@@ -109,9 +123,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
protected readonly transferDni = signal<string>('');
|
||||
|
||||
protected readonly isUpdatingPurchase = signal(false);
|
||||
protected readonly isEditingItems = signal(false);
|
||||
protected readonly isUpdatingItem = signal(false);
|
||||
protected readonly isPreparingItemEdit = signal(false);
|
||||
protected readonly isCancellingPurchase = signal(false);
|
||||
protected readonly hasSubmittedTransfer = signal(false);
|
||||
protected readonly isPurchaseModificationDisabled = computed(
|
||||
() => this.isCancellingPurchase() || this.hasSubmittedTransfer(),
|
||||
);
|
||||
protected readonly createdPurchaseId = signal<number | null>(null);
|
||||
protected readonly isGeneratingIntent = signal(false);
|
||||
protected readonly isPaymentLoading = computed(() => this.isGeneratingIntent());
|
||||
@@ -156,6 +172,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
}
|
||||
|
||||
private mapPurchaseItemToMock(item: PurchaseDetailItemResponse): CartItemMock {
|
||||
@@ -171,81 +188,30 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
value: attribute.value === null ? '' : String(attribute.value),
|
||||
})),
|
||||
quantity: item.quantity,
|
||||
variantId: item.source_variant_id,
|
||||
};
|
||||
}
|
||||
|
||||
protected async onEditingItemsChange(editing: boolean): Promise<void> {
|
||||
if (this.isUpdatingItem() || this.isPreparingItemEdit()) {
|
||||
protected async onModifyPurchase(): Promise<void> {
|
||||
if (this.isPurchaseModificationDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!editing) {
|
||||
this.isEditingItems.set(false);
|
||||
|
||||
if (this.stepper?.currentStepIndex() === 1) {
|
||||
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.isEditingItems.set(true);
|
||||
this.stopQrPolling();
|
||||
this.qrData.set(null);
|
||||
this.qrPaymentStatus.set('idle');
|
||||
this.transferAccount.set(null);
|
||||
this.transferValidationStatus.set('idle');
|
||||
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
|
||||
if (!tenant || !purchaseId) {
|
||||
this.isEditingItems.set(false);
|
||||
return;
|
||||
}
|
||||
|
||||
this.isPreparingItemEdit.set(true);
|
||||
this.globalLoadingService.start();
|
||||
try {
|
||||
const purchase = await this.checkoutService.prepareItemEditing(tenant.codigo, purchaseId);
|
||||
this.createdPurchase.set(purchase);
|
||||
} catch (error) {
|
||||
console.error('Failed to prepare purchase item editing:', error);
|
||||
this.isEditingItems.set(false);
|
||||
const cancelled = await this.cancelCurrentPurchase();
|
||||
if (!cancelled) return;
|
||||
|
||||
await this.router.navigate(['/'], {
|
||||
queryParams: { openCart: true },
|
||||
});
|
||||
} finally {
|
||||
this.isPreparingItemEdit.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async onPurchaseItemQuantityChange(event: {
|
||||
item: CartItemMock;
|
||||
quantity: number;
|
||||
}): Promise<void> {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
const itemId = event.item.cartItemId;
|
||||
|
||||
if (!tenant || !purchaseId || !itemId || this.isUpdatingItem() || !this.isEditingItems()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isUpdatingItem.set(true);
|
||||
try {
|
||||
const purchase = await this.checkoutService.updateItemQuantity(
|
||||
tenant.codigo,
|
||||
purchaseId,
|
||||
itemId,
|
||||
event.quantity,
|
||||
);
|
||||
this.createdPurchase.set(purchase);
|
||||
} catch (error) {
|
||||
console.error('Failed to update purchase item quantity:', error);
|
||||
} finally {
|
||||
this.isUpdatingItem.set(false);
|
||||
this.globalLoadingService.stop();
|
||||
}
|
||||
}
|
||||
|
||||
protected async onStep1Continue(): Promise<void> {
|
||||
if (this.form.invalid || this.isUpdatingPurchase() || this.isEditingItems()) return;
|
||||
if (this.form.invalid || this.isUpdatingPurchase()) return;
|
||||
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
@@ -269,56 +235,81 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
void this.selectPaymentMethod(this.selectedPaymentMethod());
|
||||
} catch (error) {
|
||||
console.error('Failed to create purchase:', error);
|
||||
// Here we could show an alert or toast
|
||||
this.showRequestError(error, 'No se pudieron actualizar los datos de la compra.');
|
||||
} finally {
|
||||
this.isUpdatingPurchase.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async onCancel(): Promise<void> {
|
||||
if (await this.canDeactivate()) {
|
||||
void this.router.navigate(['/']);
|
||||
}
|
||||
void this.router.navigate(['/']);
|
||||
}
|
||||
|
||||
public async canDeactivate(): Promise<boolean> {
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
|
||||
if (this.cancelPurchasePromise) {
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
if (this.navigationStarted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
const tenant = this.tenantService.tenant();
|
||||
this.globalLoadingService.start();
|
||||
try {
|
||||
return await this.cancelCurrentPurchase();
|
||||
} finally {
|
||||
this.globalLoadingService.stop();
|
||||
}
|
||||
}
|
||||
|
||||
if (!purchaseId || !tenant) {
|
||||
private cancelCurrentPurchase(): Promise<boolean> {
|
||||
if (this.cancelPurchasePromise) {
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
this.cancelPurchasePromise = this.performPurchaseCancellation().finally(() => {
|
||||
this.cancelPurchasePromise = null;
|
||||
});
|
||||
|
||||
return this.cancelPurchasePromise;
|
||||
}
|
||||
|
||||
private async performPurchaseCancellation(): Promise<boolean> {
|
||||
const tenant = this.tenantService.tenant();
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
if (!tenant || !purchaseId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
this.isCancellingPurchase.set(true);
|
||||
|
||||
try {
|
||||
await this.checkoutService.cancelPurchase(tenant.codigo, purchaseId);
|
||||
await firstValueFrom(this.cartService.loadCart());
|
||||
this.createdPurchaseId.set(null);
|
||||
this.createdPurchase.set(null);
|
||||
|
||||
try {
|
||||
await firstValueFrom(this.cartService.loadCart());
|
||||
} catch (error) {
|
||||
console.error('Failed to restore cart after cancelling checkout:', error);
|
||||
}
|
||||
|
||||
this.navigationStarted = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to cancel purchase:', error);
|
||||
console.error('Failed to cancel the current purchase:', error);
|
||||
this.showRequestError(error, 'No se pudo cancelar la compra.');
|
||||
return false;
|
||||
} finally {
|
||||
this.isCancellingPurchase.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async selectPaymentMethod(method: PaymentMethod): Promise<void> {
|
||||
if (this.navigationStarted || this.isEditingItems()) {
|
||||
if (this.navigationStarted || this.hasSubmittedTransfer()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
this.qrPaymentStatus.set('idle');
|
||||
this.transferValidationStatus.set('idle');
|
||||
this.selectedPaymentMethod.set(method);
|
||||
@@ -331,7 +322,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
const purchaseId = this.createdPurchaseId();
|
||||
const tenant = this.tenantService.tenant();
|
||||
|
||||
if (!purchaseId || !tenant || method === 'telepagos') {
|
||||
if (!purchaseId || !tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -358,13 +349,14 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to generate payment intent:', error);
|
||||
this.showRequestError(error, 'No se pudo generar el pago.');
|
||||
} finally {
|
||||
this.isGeneratingIntent.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected async generateTransferIntent(dni: string): Promise<void> {
|
||||
if (this.isEditingItems()) {
|
||||
if (this.hasSubmittedTransfer()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -376,6 +368,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
this.transferDni.set(dni);
|
||||
this.stopTransferPolling();
|
||||
this.transferValidationStatus.set('idle');
|
||||
this.isGeneratingIntent.set(true);
|
||||
try {
|
||||
@@ -394,6 +387,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to generate transfer payment intent:', error);
|
||||
this.showRequestError(error, 'No se pudo generar el pago por transferencia.');
|
||||
} finally {
|
||||
this.isGeneratingIntent.set(false);
|
||||
}
|
||||
@@ -424,32 +418,103 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
!purchaseId ||
|
||||
!tenant ||
|
||||
this.navigationStarted ||
|
||||
this.isEditingItems() ||
|
||||
this.transferValidationStatus() === 'checking'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.stopTransferPolling();
|
||||
this.hasSubmittedTransfer.set(true);
|
||||
this.transferValidationStatus.set('checking');
|
||||
this.transferPollingAttempts = 0;
|
||||
|
||||
const runId = this.transferPollingRunId;
|
||||
|
||||
try {
|
||||
const purchase = await this.checkoutService
|
||||
.withCustomLoading()
|
||||
.submitPurchaseForReview(tenant.codigo, purchaseId);
|
||||
|
||||
if (purchase.status === 'paid' || purchase.status === 'pending_payment') {
|
||||
if (purchase.status === 'pending_payment') {
|
||||
this.transferValidationStatus.set('pending');
|
||||
}
|
||||
if (runId !== this.transferPollingRunId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (purchase.status === 'paid') {
|
||||
this.navigateToPurchaseStatus(purchaseId);
|
||||
return;
|
||||
}
|
||||
|
||||
this.transferValidationStatus.set('error');
|
||||
this.scheduleTransferPoll(runId);
|
||||
} catch (error) {
|
||||
console.error('Failed to submit purchase for review:', error);
|
||||
const expired = this.handleCheckoutError(
|
||||
error,
|
||||
'No se pudo enviar el pago para su validación.',
|
||||
);
|
||||
|
||||
if (!expired && runId === this.transferPollingRunId) {
|
||||
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) {
|
||||
console.error('Failed to validate transfer payment:', error);
|
||||
}
|
||||
|
||||
if (runId !== this.transferPollingRunId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.transferPollingAttempts >= this.transferPollingMaxAttempts) {
|
||||
this.stopTransferPolling();
|
||||
this.transferValidationStatus.set('error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.scheduleTransferPoll(runId);
|
||||
}
|
||||
|
||||
private stopTransferPolling(): void {
|
||||
this.transferPollingRunId += 1;
|
||||
|
||||
if (this.transferPollingTimeoutId !== null) {
|
||||
clearTimeout(this.transferPollingTimeoutId);
|
||||
this.transferPollingTimeoutId = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -563,6 +628,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.navigationStarted = true;
|
||||
this.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
|
||||
void this.router.navigate(['/checkout/status', purchaseId]);
|
||||
}
|
||||
@@ -574,6 +640,8 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.createdPurchaseId.set(purchaseId);
|
||||
|
||||
try {
|
||||
const purchase = await this.checkoutService
|
||||
.withCustomLoading()
|
||||
@@ -581,6 +649,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
if (
|
||||
(purchase.status === 'pending_payment' && purchase.expires_at === null) ||
|
||||
purchase.status === 'in_review' ||
|
||||
purchase.status === 'paid' ||
|
||||
purchase.status === 'cancelled' ||
|
||||
purchase.status === 'rejected' ||
|
||||
@@ -614,7 +683,67 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load purchase:', error);
|
||||
this.showRequestError(error, 'No se pudo cargar la compra.');
|
||||
void this.router.navigate(['/']);
|
||||
}
|
||||
}
|
||||
|
||||
private showRequestError(error: unknown, fallbackMessage: string): void {
|
||||
const payload =
|
||||
typeof error === 'object' && error !== null && 'error' in error
|
||||
? (error as { error?: { message?: unknown } }).error
|
||||
: undefined;
|
||||
const message =
|
||||
typeof payload?.message === 'string' && payload.message.trim()
|
||||
? payload.message
|
||||
: fallbackMessage;
|
||||
|
||||
this.toastService.danger(message);
|
||||
}
|
||||
|
||||
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.stopQrPolling();
|
||||
this.stopTransferPolling();
|
||||
this.toastService.danger(
|
||||
response?.code === 'purchase.expired' && response.message
|
||||
? response.message
|
||||
: 'La compra venció. Iniciá 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { FormControl, FormGroup } from '@angular/forms';
|
||||
|
||||
export type PaymentMethod = 'qr' | 'transfer' | 'telepagos';
|
||||
export type PaymentMethod = 'qr' | 'transfer';
|
||||
export type TransferField = 'cvu' | 'alias';
|
||||
export type QrPaymentStatus = 'idle' | 'waiting' | 'timed_out' | 'failed';
|
||||
export type TransferValidationStatus = 'idle' | 'checking' | 'pending' | 'error';
|
||||
export type TransferValidationStatus = 'idle' | 'checking' | 'error';
|
||||
|
||||
export interface PaymentMethodOption {
|
||||
id: PaymentMethod;
|
||||
|
||||
@@ -7,25 +7,23 @@
|
||||
|
||||
<div class="payment-methods__list" role="radiogroup" aria-label="Metodo de pago">
|
||||
@for (method of paymentMethods(); track method.id) {
|
||||
<label class="payment-method" [class.is-selected]="selectedPaymentMethod() === method.id">
|
||||
<label
|
||||
class="payment-method"
|
||||
[class.is-selected]="selectedPaymentMethod() === method.id"
|
||||
[class.is-disabled]="paymentMethodDisabled()"
|
||||
>
|
||||
<input
|
||||
class="payment-method__radio"
|
||||
type="radio"
|
||||
name="payment-method"
|
||||
[value]="method.id"
|
||||
[checked]="selectedPaymentMethod() === method.id"
|
||||
[disabled]="paymentMethodDisabled()"
|
||||
(change)="selectPaymentMethod(method.id)"
|
||||
/>
|
||||
|
||||
<span class="payment-method__label">
|
||||
@if (method.id === 'telepagos') {
|
||||
<span class="telepagos-logo" aria-label="TelePagos">
|
||||
<span class="telepagos-logo__tele">tele</span
|
||||
><span class="telepagos-logo__pagos">pagos</span>
|
||||
</span>
|
||||
} @else {
|
||||
{{ method.label }}
|
||||
}
|
||||
{{ method.label }}
|
||||
</span>
|
||||
|
||||
<i class="fa-solid fa-angle-right payment-method__chevron" aria-hidden="true"></i>
|
||||
@@ -59,8 +57,6 @@
|
||||
(submitDni)="generateTransferIntent.emit($event)"
|
||||
(completePurchase)="complete.emit()"
|
||||
/>
|
||||
} @else {
|
||||
<app-checkout-payment-telepagos />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -63,10 +63,14 @@
|
||||
cursor: pointer;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
&:not(.is-disabled):hover {
|
||||
color: #4f4f4f;
|
||||
}
|
||||
|
||||
&.is-disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
&.is-selected {
|
||||
color: var(--tenant-primary, #6376f3);
|
||||
}
|
||||
@@ -79,6 +83,10 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&.is-disabled &__radio {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
&__label {
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
@@ -91,36 +99,25 @@
|
||||
font-size: 0.95rem;
|
||||
opacity: 0;
|
||||
transform: translateX(-4px);
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
transition:
|
||||
opacity 0.2s ease,
|
||||
transform 0.2s ease;
|
||||
}
|
||||
|
||||
&.is-selected &__chevron,
|
||||
&:hover &__chevron {
|
||||
&:not(.is-disabled):hover &__chevron {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.telepagos-logo {
|
||||
display: inline-block;
|
||||
font-size: 1.45rem;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.03em;
|
||||
background: linear-gradient(90deg, #0a69d8 0 78%, #f6a11a 78% 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.payment-panel {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
|
||||
> app-checkout-payment-qr,
|
||||
> app-checkout-payment-transfer,
|
||||
> app-checkout-payment-telepagos {
|
||||
> app-checkout-payment-transfer {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
@@ -153,6 +150,4 @@
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
|
||||
|
||||
import { CheckoutPaymentQrComponent } from './components/checkout-payment-qr/checkout-payment-qr.component';
|
||||
import { CheckoutPaymentTelepagosComponent } from './components/checkout-payment-telepagos/checkout-payment-telepagos.component';
|
||||
import { CheckoutPaymentTransferComponent } from './components/checkout-payment-transfer/checkout-payment-transfer.component';
|
||||
import {
|
||||
PaymentMethod,
|
||||
@@ -15,14 +14,15 @@ import {
|
||||
@Component({
|
||||
selector: 'app-checkout-payment-step',
|
||||
standalone: true,
|
||||
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTelepagosComponent, CheckoutPaymentTransferComponent],
|
||||
imports: [CheckoutPaymentQrComponent, CheckoutPaymentTransferComponent],
|
||||
templateUrl: './checkout-payment-step.component.html',
|
||||
styleUrl: './checkout-payment-step.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class CheckoutPaymentStepComponent {
|
||||
readonly paymentMethods = input.required<ReadonlyArray<PaymentMethodOption>>();
|
||||
readonly selectedPaymentMethod = input.required<PaymentMethod>();
|
||||
readonly paymentMethodDisabled = input<boolean>(false);
|
||||
readonly copiedTransferField = input<TransferField | null>(null);
|
||||
readonly transferAccount = input<TransferAccount | null>(null);
|
||||
readonly transferDni = input<string>('');
|
||||
@@ -41,6 +41,10 @@ export class CheckoutPaymentStepComponent {
|
||||
readonly generateTransferIntent = output<string>();
|
||||
|
||||
protected selectPaymentMethod(method: PaymentMethod): void {
|
||||
if (this.paymentMethodDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.paymentMethodChange.emit(method);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
<div class="payment-panel__card">
|
||||
<h3 class="payment-panel__title">Descarga la app de TelePagos para finalizar la compra</h3>
|
||||
<div class="payment-panel__divider"></div>
|
||||
|
||||
<div class="store-badges" aria-label="Tiendas disponibles">
|
||||
<div class="store-badge">
|
||||
<i class="fa-brands fa-google-play" aria-hidden="true"></i>
|
||||
<span class="store-badge__text">
|
||||
<small>Disponible en</small>
|
||||
<strong>Google Play</strong>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="store-badge">
|
||||
<i class="fa-brands fa-apple" aria-hidden="true"></i>
|
||||
<span class="store-badge__text">
|
||||
<small>Descargalo en</small>
|
||||
<strong>App Store</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,71 +0,0 @@
|
||||
.payment-panel__card {
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
min-height: 269px;
|
||||
padding: 1.5rem 1.75rem;
|
||||
border-radius: 5px;
|
||||
background: #ffffff;
|
||||
color: #666666;
|
||||
box-shadow: 0 0 0 1px #f1f1f1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.payment-panel__title {
|
||||
max-width: 18rem;
|
||||
margin: 0;
|
||||
color: #8a8a8a;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.payment-panel__divider {
|
||||
width: 100%;
|
||||
max-width: 220px;
|
||||
height: 1px;
|
||||
margin: 1.2rem 0 1.45rem;
|
||||
background: #dddddd;
|
||||
}
|
||||
|
||||
.store-badges {
|
||||
width: 100%;
|
||||
max-width: 210px;
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.store-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 0.95rem;
|
||||
border-radius: 0.85rem;
|
||||
background: #111111;
|
||||
color: #ffffff;
|
||||
box-shadow: 0 10px 24px rgba(17, 17, 17, 0.16);
|
||||
|
||||
i {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
&__text {
|
||||
display: grid;
|
||||
text-align: left;
|
||||
line-height: 1.1;
|
||||
|
||||
small {
|
||||
font-size: 0.62rem;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
strong {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { ChangeDetectionStrategy, Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-checkout-payment-telepagos',
|
||||
standalone: true,
|
||||
imports: [],
|
||||
templateUrl: './checkout-payment-telepagos.component.html',
|
||||
styleUrl: './checkout-payment-telepagos.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class CheckoutPaymentTelepagosComponent {}
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="payment-panel__card">
|
||||
@if (validationStatus() === 'pending' || validationStatus() === 'error') {
|
||||
@if (validationStatus() === 'error') {
|
||||
<app-payment-verification-error
|
||||
[paymentAmount]="paymentAmount()"
|
||||
[whatsappUrl]="whatsappUrl()"
|
||||
@@ -102,5 +102,12 @@
|
||||
</app-button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (validationStatus() === 'checking') {
|
||||
<div class="payment-verification" role="status" aria-live="polite">
|
||||
<span class="payment-verification__spinner" aria-hidden="true"></span>
|
||||
<span class="payment-verification__message">Verificando pago</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.payment-panel__card {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
min-height: 400px;
|
||||
@@ -13,6 +14,40 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.payment-verification {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
border-radius: inherit;
|
||||
background: rgba(255, 255, 255, 0.82);
|
||||
|
||||
&__spinner {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 4px solid rgba(17, 17, 17, 0.2);
|
||||
border-top-color: #111111;
|
||||
border-radius: 50%;
|
||||
animation: payment-verification-spin 0.75s linear infinite;
|
||||
}
|
||||
|
||||
&__message {
|
||||
color: #111111;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes payment-verification-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.payment-panel__title {
|
||||
max-width: 18rem;
|
||||
margin: 0;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { getTestBed, TestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { CheckoutPaymentTransferComponent } from './checkout-payment-transfer.component';
|
||||
|
||||
describe('CheckoutPaymentTransferComponent', () => {
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
});
|
||||
|
||||
it('renders the payment verification overlay while checking the transfer', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CheckoutPaymentTransferComponent],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||
fixture.componentRef.setInput('validationStatus', 'checking');
|
||||
fixture.detectChanges();
|
||||
|
||||
const overlay = fixture.nativeElement.querySelector('.payment-verification') as HTMLElement;
|
||||
expect(overlay).not.toBeNull();
|
||||
expect(overlay.textContent).toContain('Verificando pago');
|
||||
expect(overlay.querySelector('.payment-verification__spinner')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('shows the QR payment error and WhatsApp action when validation fails', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CheckoutPaymentTransferComponent],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(CheckoutPaymentTransferComponent);
|
||||
fixture.componentRef.setInput('validationStatus', 'error');
|
||||
fixture.componentRef.setInput('paymentAmount', 300000);
|
||||
fixture.componentRef.setInput('whatsappUrl', 'https://wa.me/543412602222');
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const whatsapp = Array.from(element.querySelectorAll('button')).find((button) =>
|
||||
button.textContent?.includes('WhatsApp'),
|
||||
);
|
||||
expect(element.textContent).toMatch(/No pudimos verificar el pago de \$\s*300\.000\./);
|
||||
expect(whatsapp).toBeDefined();
|
||||
expect(element.querySelector('.payment-verification')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,7 @@
|
||||
[variants]="prod.variants"
|
||||
[selectedVariant]="prod.selected_variant ?? null"
|
||||
[inventoryPolicy]="prod.inventory_policy"
|
||||
[disabled]="!allows(prod.availability, 'select_variant')"
|
||||
(variantChange)="onVariantChange($event)"
|
||||
/>
|
||||
</section>
|
||||
@@ -53,14 +54,22 @@
|
||||
|
||||
<section class="product-detail__section">
|
||||
<div class="product-detail__purchase">
|
||||
<app-quantity-selector [(quantity)]="quantity" [max]="selectedVariantMax()" />
|
||||
@if (restrictionMessage(); as message) {
|
||||
<p class="mb-0 text-danger" role="status">{{ message }}</p>
|
||||
}
|
||||
|
||||
<app-quantity-selector
|
||||
[(quantity)]="quantity"
|
||||
[max]="selectedVariantMax()"
|
||||
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||
/>
|
||||
|
||||
<div class="product-detail__actions">
|
||||
<app-button
|
||||
class="product-detail__cta"
|
||||
variant="secondary"
|
||||
type="button"
|
||||
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
|
||||
[disabled]="!canAddToCart() || variantLoading() || addingToCart()"
|
||||
(click)="addToCart()"
|
||||
>
|
||||
@if (addingToCart()) {
|
||||
@@ -75,9 +84,7 @@
|
||||
<app-button
|
||||
class="product-detail__cta"
|
||||
type="button"
|
||||
[disabled]="
|
||||
!selectedVariantAvailable() || variantLoading() || creatingDirectPurchase()
|
||||
"
|
||||
[disabled]="!canBuyNow() || variantLoading() || creatingDirectPurchase()"
|
||||
(click)="buyNow()"
|
||||
>
|
||||
@if (variantLoading() || creatingDirectPurchase()) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { signal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
@@ -8,6 +9,8 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { ProductDetailPageComponent } from './product-detail-page.component';
|
||||
@@ -36,7 +39,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
has_tickets: false,
|
||||
minimum_use_date: null,
|
||||
maximum_use_date: null,
|
||||
stock_tecnico: 10,
|
||||
availability: createCatalogAvailability(10),
|
||||
attributes: [],
|
||||
variants: [],
|
||||
};
|
||||
@@ -175,6 +178,36 @@ describe('ProductDetailPageComponent', () => {
|
||||
expect(element.querySelector('.product-carousel__discount-badge')).toBeNull();
|
||||
});
|
||||
|
||||
it('reloads product availability when the cart changes', async () => {
|
||||
catalogServiceStub.getCatalogItem.mockReturnValue(
|
||||
of({ ...mockProduct, availability: createCatalogAvailability(4) }),
|
||||
);
|
||||
await configureTestingModule();
|
||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, undefined);
|
||||
expect(fixture.componentInstance['selectedVariantMax']()).toBe(4);
|
||||
});
|
||||
|
||||
it('stops presenting a product that becomes hidden during an availability refresh', async () => {
|
||||
catalogServiceStub.getCatalogItem.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({ status: 404 })),
|
||||
);
|
||||
await configureTestingModule();
|
||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.componentInstance['product']()).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Este producto ya no está disponible.');
|
||||
});
|
||||
|
||||
it('shows error message if the resolver cannot load the product', async () => {
|
||||
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
|
||||
await configureTestingModule();
|
||||
@@ -190,10 +223,10 @@ describe('ProductDetailPageComponent', () => {
|
||||
const detailProduct: CatalogItemDetail = {
|
||||
...mockProduct,
|
||||
images: ['https://example.com/product.png'],
|
||||
variants: [{ id: 123, stock_tecnico: 10, values: {} }],
|
||||
variants: [{ id: 123, availability: createCatalogAvailability(10), values: {} }],
|
||||
selected_variant: {
|
||||
id: 123,
|
||||
stock_tecnico: 10,
|
||||
availability: createCatalogAvailability(10),
|
||||
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
|
||||
values: {},
|
||||
},
|
||||
@@ -294,10 +327,16 @@ describe('ProductDetailPageComponent', () => {
|
||||
],
|
||||
},
|
||||
],
|
||||
variants: [{ id: 123, stock_tecnico: 10, values: { color: 'beige', material: 'Cuero' } }],
|
||||
variants: [
|
||||
{
|
||||
id: 123,
|
||||
availability: createCatalogAvailability(10),
|
||||
values: { color: 'beige', material: 'Cuero' },
|
||||
},
|
||||
],
|
||||
selected_variant: {
|
||||
id: 123,
|
||||
stock_tecnico: 10,
|
||||
availability: createCatalogAvailability(10),
|
||||
images: ['https://example.com/variant1.png'],
|
||||
values: {
|
||||
color: 'beige',
|
||||
@@ -334,8 +373,18 @@ describe('ProductDetailPageComponent', () => {
|
||||
purpose: 'entry',
|
||||
has_tickets: true,
|
||||
variants: [
|
||||
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } },
|
||||
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
|
||||
{
|
||||
id: 101,
|
||||
event_date_id: 20,
|
||||
availability: createCatalogAvailability(10),
|
||||
values: { event_date: '20' },
|
||||
},
|
||||
{
|
||||
id: 102,
|
||||
event_date_id: 21,
|
||||
availability: createCatalogAvailability(10),
|
||||
values: { event_date: '21' },
|
||||
},
|
||||
],
|
||||
attributes: [
|
||||
{
|
||||
@@ -366,7 +415,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
selected_variant: {
|
||||
id: 101,
|
||||
event_date_id: 20,
|
||||
stock_tecnico: 10,
|
||||
availability: createCatalogAvailability(10),
|
||||
images: [],
|
||||
values: {},
|
||||
},
|
||||
@@ -388,6 +437,8 @@ describe('ProductDetailPageComponent', () => {
|
||||
|
||||
options[1].click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
|
||||
});
|
||||
@@ -410,7 +461,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
|
||||
fixture.componentInstance['selectedVariant'].set({
|
||||
id: 1,
|
||||
stock_tecnico: 10,
|
||||
availability: createCatalogAvailability(10),
|
||||
values: {},
|
||||
});
|
||||
fixture.detectChanges();
|
||||
@@ -493,19 +544,45 @@ describe('ProductDetailPageComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the backend purchase-limit message for a direct checkout', async () => {
|
||||
checkoutServiceStub.startCheckout.mockRejectedValue(
|
||||
new HttpErrorResponse({
|
||||
status: 422,
|
||||
error: {
|
||||
code: 'purchase.limit_exceeded',
|
||||
message: 'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||
availability: createCatalogAvailability(2),
|
||||
},
|
||||
}),
|
||||
);
|
||||
await configureTestingModule();
|
||||
const fixture = TestBed.createComponent(ProductDetailPageComponent);
|
||||
fixture.detectChanges();
|
||||
const buyButton = Array.from(
|
||||
fixture.nativeElement.querySelectorAll('app-button button') as NodeListOf<HTMLButtonElement>,
|
||||
).find((button) => button.textContent?.trim() === 'Comprar') as HTMLButtonElement;
|
||||
|
||||
buyButton.click();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(toastServiceStub.danger).toHaveBeenCalledWith(
|
||||
'Podés agregar hasta 2 unidades más de “Auriculares Bluetooth”.',
|
||||
);
|
||||
});
|
||||
|
||||
it('calls CartService.addItem when variant is selected and Add to Cart is clicked', async () => {
|
||||
const detailProduct: CatalogItemDetail = {
|
||||
...mockProduct,
|
||||
variants: [
|
||||
{
|
||||
id: 123,
|
||||
stock_tecnico: 5,
|
||||
availability: createCatalogAvailability(5),
|
||||
values: {},
|
||||
},
|
||||
],
|
||||
selected_variant: {
|
||||
id: 123,
|
||||
stock_tecnico: 5,
|
||||
availability: createCatalogAvailability(5),
|
||||
images: [],
|
||||
values: {},
|
||||
},
|
||||
@@ -538,7 +615,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
resolveProduct({
|
||||
...mockProduct,
|
||||
variants: [],
|
||||
stock_tecnico: 4,
|
||||
availability: createCatalogAvailability(4),
|
||||
});
|
||||
|
||||
await configureTestingModule();
|
||||
@@ -564,13 +641,13 @@ describe('ProductDetailPageComponent', () => {
|
||||
variants: [
|
||||
{
|
||||
id: 123,
|
||||
stock_tecnico: 5,
|
||||
availability: createCatalogAvailability(5),
|
||||
values: {},
|
||||
},
|
||||
],
|
||||
selected_variant: {
|
||||
id: 123,
|
||||
stock_tecnico: 5,
|
||||
availability: createCatalogAvailability(5),
|
||||
images: [],
|
||||
values: {},
|
||||
},
|
||||
@@ -602,7 +679,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
it('allows unlimited variants to increase quantity without a maximum', async () => {
|
||||
const unlimitedVariant = {
|
||||
id: 321,
|
||||
stock_tecnico: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
values: {},
|
||||
};
|
||||
resolveProduct({
|
||||
@@ -610,7 +687,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
inventory_policy: 'unlimited',
|
||||
selected_variant: {
|
||||
id: 321,
|
||||
stock_tecnico: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
images: [],
|
||||
values: {},
|
||||
},
|
||||
@@ -634,7 +711,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
it('caps an unlimited variant at the per-user purchase limit', async () => {
|
||||
const unlimitedVariant = {
|
||||
id: 322,
|
||||
stock_tecnico: null,
|
||||
availability: createCatalogAvailability(2),
|
||||
values: {},
|
||||
};
|
||||
resolveProduct({
|
||||
@@ -643,7 +720,7 @@ describe('ProductDetailPageComponent', () => {
|
||||
max_units_per_user: 2,
|
||||
selected_variant: {
|
||||
id: 322,
|
||||
stock_tecnico: null,
|
||||
availability: createCatalogAvailability(2),
|
||||
images: [],
|
||||
values: { event_date: '20' },
|
||||
},
|
||||
@@ -667,14 +744,14 @@ describe('ProductDetailPageComponent', () => {
|
||||
it('disables purchase actions for tracked variants without stock', async () => {
|
||||
const trackedVariant = {
|
||||
id: 654,
|
||||
stock_tecnico: 0,
|
||||
availability: createCatalogAvailability(0),
|
||||
values: {},
|
||||
};
|
||||
resolveProduct({
|
||||
...mockProduct,
|
||||
selected_variant: {
|
||||
id: 654,
|
||||
stock_tecnico: 0,
|
||||
availability: createCatalogAvailability(0),
|
||||
images: [],
|
||||
values: {},
|
||||
},
|
||||
|
||||
@@ -17,6 +17,7 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { Subscription } from 'rxjs';
|
||||
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import {
|
||||
@@ -31,6 +32,13 @@ import { ProductDetailResolvedData } from './product-detail-page.resolver';
|
||||
import { CheckoutService } from '../../../../core/services/checkout.service';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import {
|
||||
AVAILABLE_CATALOG_AVAILABILITY,
|
||||
allowsCatalogAction,
|
||||
combineCatalogAvailability,
|
||||
maximumCatalogQuantity,
|
||||
primaryAvailabilityMessage,
|
||||
} from '../../../../core/services/catalog/catalog-availability';
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-detail-page',
|
||||
@@ -51,6 +59,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly catalogService = inject(CatalogService);
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
private readonly toastService = inject(ToastService);
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
@@ -64,6 +73,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
|
||||
private routeSub: Subscription | null = null;
|
||||
private productSub: Subscription | null = null;
|
||||
private availabilityChangedSub: Subscription | null = null;
|
||||
private carouselResizeObserver: ResizeObserver | null = null;
|
||||
private observedCarouselPreview: HTMLElement | null = null;
|
||||
private measurementTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -93,33 +103,41 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
() => this.selectedVariant()?.precio ?? this.product()?.precio,
|
||||
);
|
||||
protected readonly quantity = signal(1);
|
||||
protected readonly effectiveAvailability = computed(() => {
|
||||
const prod = this.product();
|
||||
const variant = this.selectedVariant();
|
||||
if (!prod) return AVAILABLE_CATALOG_AVAILABILITY;
|
||||
|
||||
return combineCatalogAvailability(prod.availability, variant?.availability);
|
||||
});
|
||||
protected readonly selectedVariantMax = computed<number | null>(() => {
|
||||
const prod = this.product();
|
||||
const variant = this.selectedVariant();
|
||||
if (!prod) return 0;
|
||||
if (!variant && prod.variants.length > 0) return 0;
|
||||
|
||||
const stockLimit = variant
|
||||
? variant.stock_tecnico
|
||||
: prod.variants.length === 0
|
||||
? (prod.stock_tecnico ?? null)
|
||||
: 0;
|
||||
const userLimit = prod.max_units_per_user ?? null;
|
||||
|
||||
if (stockLimit === null) return userLimit;
|
||||
if (userLimit === null) return stockLimit;
|
||||
return Math.min(stockLimit, userLimit);
|
||||
return maximumCatalogQuantity(this.effectiveAvailability());
|
||||
});
|
||||
protected readonly selectedVariantAvailable = computed(() => {
|
||||
protected readonly hasPurchasableSelection = computed(() => {
|
||||
const prod = this.product();
|
||||
if (!prod) return false;
|
||||
|
||||
const variant = this.selectedVariant();
|
||||
if (variant) return this.isVariantAvailable(variant, prod);
|
||||
if (prod.purpose === 'entry') return false;
|
||||
if (prod.variants.length > 0) return false;
|
||||
|
||||
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0;
|
||||
return prod.variants.length === 0 || this.selectedVariant() !== null;
|
||||
});
|
||||
protected readonly canAddToCart = computed(
|
||||
() =>
|
||||
this.hasPurchasableSelection() &&
|
||||
allowsCatalogAction(this.effectiveAvailability(), 'add_to_cart'),
|
||||
);
|
||||
protected readonly canBuyNow = computed(
|
||||
() =>
|
||||
this.hasPurchasableSelection() &&
|
||||
allowsCatalogAction(this.effectiveAvailability(), 'buy_now'),
|
||||
);
|
||||
protected readonly restrictionMessage = computed(() =>
|
||||
primaryAvailabilityMessage(this.effectiveAvailability()),
|
||||
);
|
||||
protected readonly allows = allowsCatalogAction;
|
||||
protected readonly descriptionExpanded = signal(false);
|
||||
protected readonly descriptionMaxHeight = signal(0);
|
||||
protected readonly descriptionHasOverflow = signal(false);
|
||||
@@ -154,6 +172,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.availabilityChangedSub = this.catalogAvailabilityService.availabilityChanged$.subscribe(
|
||||
() => this.refreshProductAvailability(),
|
||||
);
|
||||
|
||||
this.routeSub = this.route.data.subscribe((data) => {
|
||||
const resolvedData = data['productDetailData'] as ProductDetailResolvedData | undefined;
|
||||
|
||||
@@ -164,6 +186,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.availabilityChangedSub?.unsubscribe();
|
||||
this.routeSub?.unsubscribe();
|
||||
this.productSub?.unsubscribe();
|
||||
this.carouselResizeObserver?.disconnect();
|
||||
@@ -200,6 +223,36 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private refreshProductAvailability(): void {
|
||||
const currentProduct = this.product();
|
||||
if (!currentProduct) {
|
||||
return;
|
||||
}
|
||||
|
||||
const variantId = this.selectedVariant()?.id;
|
||||
this.productSub?.unsubscribe();
|
||||
this.productSub = this.catalogService
|
||||
.withCustomLoading()
|
||||
.getCatalogItem(currentProduct.id, variantId)
|
||||
.subscribe({
|
||||
next: (product) => {
|
||||
this.applyProduct(product, false);
|
||||
|
||||
const maximum = this.selectedVariantMax();
|
||||
if (maximum !== null && this.quantity() > maximum) {
|
||||
this.quantity.set(Math.max(1, maximum));
|
||||
}
|
||||
},
|
||||
error: (error: HttpErrorResponse) => {
|
||||
if (error.status === 404) {
|
||||
this.product.set(null);
|
||||
this.selectedVariant.set(null);
|
||||
this.error.set('Este producto ya no está disponible.');
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
|
||||
this.productSub?.unsubscribe();
|
||||
this.loading.set(false);
|
||||
@@ -265,8 +318,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
protected addToCart(): void {
|
||||
const currentProduct = this.product();
|
||||
const variant = this.selectedVariant();
|
||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
||||
this.toastService.danger('Por favor, selecciona una variante.');
|
||||
if (!currentProduct || !this.canAddToCart()) {
|
||||
this.toastService.danger(
|
||||
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -296,8 +351,10 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentProduct || !this.selectedVariantAvailable()) {
|
||||
this.toastService.danger('Por favor, selecciona una variante.');
|
||||
if (!currentProduct || !this.canBuyNow()) {
|
||||
this.toastService.danger(
|
||||
this.effectiveAvailability().reasons[0]?.message ?? 'Por favor, selecciona una variante.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -333,16 +390,16 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to create direct purchase:', error);
|
||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||
const message =
|
||||
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||
? error.error.message
|
||||
: 'No se pudo iniciar la compra directa.';
|
||||
this.toastService.danger(message);
|
||||
} finally {
|
||||
this.creatingDirectPurchase.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private isVariantAvailable(variant: CatalogItemVariant, product: CatalogItemDetail): boolean {
|
||||
return product.inventory_policy === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
||||
}
|
||||
|
||||
protected toggleDescription(): void {
|
||||
this.descriptionExpanded.update((current) => !current);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CatalogItemDetail } from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||
import {
|
||||
PRODUCT_DETAIL_ERROR_MESSAGE,
|
||||
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
describe('productDetailResolver', () => {
|
||||
const product: CatalogItemDetail = {
|
||||
id: 1,
|
||||
type: 'product',
|
||||
category_id: 10,
|
||||
brand_id: null,
|
||||
slug: 'auriculares-bluetooth',
|
||||
@@ -28,7 +30,7 @@ describe('productDetailResolver', () => {
|
||||
has_tickets: false,
|
||||
minimum_use_date: null,
|
||||
maximum_use_date: null,
|
||||
stock_tecnico: 0,
|
||||
availability: createCatalogAvailability(0),
|
||||
attributes: [],
|
||||
variants: [],
|
||||
};
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';
|
||||
|
||||
import { CheckoutService, PurchaseDetailResponse } from '../../../../core/services/checkout.service';
|
||||
import {
|
||||
CheckoutService,
|
||||
PurchaseDetailResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { PurchaseStatusPageComponent } from './purchase-status-page.component';
|
||||
@@ -130,4 +133,89 @@ describe('PurchaseStatusPageComponent', () => {
|
||||
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('polls every five seconds while the payment is pending and shows the confirmation', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
const checkoutService = {
|
||||
getPurchase: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ status: 'pending_payment' } as PurchaseDetailResponse)
|
||||
.mockResolvedValueOnce(purchase(true)),
|
||||
withCustomLoading() {
|
||||
return this;
|
||||
},
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PurchaseStatusPageComponent],
|
||||
providers: [
|
||||
{ provide: CheckoutService, useValue: checkoutService },
|
||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||
},
|
||||
{ provide: Router, useValue: { navigate: vi.fn(), navigateByUrl: vi.fn() } },
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(PurchaseStatusPageComponent);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||
expect(fixture.nativeElement.textContent).toContain('ESTAMOS VERIFICANDO TU PAGO');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||
expect(fixture.nativeElement.textContent).toContain('COMPRA REALIZADA!');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(checkoutService.getPurchase).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops polling when the page is destroyed', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
const checkoutService = {
|
||||
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
|
||||
withCustomLoading() {
|
||||
return this;
|
||||
},
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PurchaseStatusPageComponent],
|
||||
providers: [
|
||||
{ provide: CheckoutService, useValue: checkoutService },
|
||||
{ provide: TenantService, useValue: { tenant: () => tenant } },
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
|
||||
},
|
||||
{ provide: Router, useValue: { navigate: vi.fn(), navigateByUrl: vi.fn() } },
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(PurchaseStatusPageComponent);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
fixture.destroy();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
|
||||
expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,29 +1,47 @@
|
||||
import { ChangeDetectionStrategy, Component, OnInit, computed, inject, signal } from '@angular/core';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
PLATFORM_ID,
|
||||
computed,
|
||||
inject,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { isPlatformBrowser } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { CheckoutService, PurchaseStatusResponse } from '../../../../core/services/checkout.service';
|
||||
import {
|
||||
CheckoutService,
|
||||
PurchaseStatusResponse,
|
||||
} from '../../../../core/services/checkout.service';
|
||||
import { findMenu } from '../../../../core/services/menu.utils';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||
|
||||
type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';
|
||||
|
||||
const PAYMENT_STATUS_POLL_INTERVAL_MS = 5_000;
|
||||
|
||||
@Component({
|
||||
selector: 'app-purchase-status-page',
|
||||
standalone: true,
|
||||
imports: [ButtonComponent],
|
||||
templateUrl: './purchase-status-page.component.html',
|
||||
styleUrl: './purchase-status-page.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class PurchaseStatusPageComponent implements OnInit {
|
||||
export class PurchaseStatusPageComponent implements OnInit, OnDestroy {
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly router = inject(Router);
|
||||
private readonly checkoutService = inject(CheckoutService);
|
||||
private readonly tenantService = inject(TenantService);
|
||||
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||
|
||||
private purchaseId: string | null = null;
|
||||
private tenantCode: string | null = null;
|
||||
private pollingTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private isDestroyed = false;
|
||||
|
||||
protected readonly isLoading = signal(true);
|
||||
protected readonly status = signal<PurchaseStatusView>('pending');
|
||||
@@ -57,7 +75,12 @@ export class PurchaseStatusPageComponent implements OnInit {
|
||||
void this.loadStatus();
|
||||
}
|
||||
|
||||
private async loadStatus(): Promise<void> {
|
||||
ngOnDestroy(): void {
|
||||
this.isDestroyed = true;
|
||||
this.stopPolling();
|
||||
}
|
||||
|
||||
private async loadStatus(isPolling = false): Promise<void> {
|
||||
if (!this.purchaseId || !this.tenantCode) {
|
||||
return;
|
||||
}
|
||||
@@ -66,13 +89,52 @@ export class PurchaseStatusPageComponent implements OnInit {
|
||||
const purchase = await this.checkoutService
|
||||
.withCustomLoading()
|
||||
.getPurchase(this.tenantCode, this.purchaseId);
|
||||
this.status.set(this.resolveStatus(purchase));
|
||||
|
||||
if (this.isDestroyed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const status = this.resolveStatus(purchase);
|
||||
this.status.set(status);
|
||||
this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
|
||||
|
||||
if (status === 'pending') {
|
||||
this.schedulePolling();
|
||||
} else {
|
||||
this.stopPolling();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch purchase status:', error);
|
||||
this.status.set('error');
|
||||
|
||||
if (!this.isDestroyed) {
|
||||
if (isPolling) {
|
||||
this.schedulePolling();
|
||||
} else {
|
||||
this.status.set('error');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.isLoading.set(false);
|
||||
if (!this.isDestroyed) {
|
||||
this.isLoading.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private schedulePolling(): void {
|
||||
if (!this.isBrowser || this.isDestroyed || this.pollingTimeout) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pollingTimeout = setTimeout(() => {
|
||||
this.pollingTimeout = null;
|
||||
void this.loadStatus(true);
|
||||
}, PAYMENT_STATUS_POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private stopPolling(): void {
|
||||
if (this.pollingTimeout) {
|
||||
clearTimeout(this.pollingTimeout);
|
||||
this.pollingTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
@@ -108,6 +109,16 @@ describe('SearchPageComponent', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('repeats the current search when catalog availability changes', () => {
|
||||
const fixture = TestBed.createComponent(SearchPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||
|
||||
expect(searchCatalog).toHaveBeenCalledTimes(2);
|
||||
expect(searchCatalog).toHaveBeenLastCalledWith({ q: 'running', page: 1 });
|
||||
});
|
||||
|
||||
it('renders the search title and query subtitle with the category header layout', () => {
|
||||
const fixture = TestBed.createComponent(SearchPageComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -9,7 +9,17 @@ import {
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { catchError, distinctUntilChanged, finalize, map, of, switchMap, tap } from 'rxjs';
|
||||
import {
|
||||
catchError,
|
||||
combineLatest,
|
||||
distinctUntilChanged,
|
||||
finalize,
|
||||
map,
|
||||
of,
|
||||
startWith,
|
||||
switchMap,
|
||||
tap,
|
||||
} from 'rxjs';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
@@ -22,6 +32,7 @@ import {
|
||||
CatalogProductLayout,
|
||||
} from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { ApiPaginatedResponse } from '../../../../core/services/api-paginated-response.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
@@ -46,6 +57,7 @@ interface SearchRouteState {
|
||||
export class SearchPageComponent {
|
||||
private readonly minSearchLength = 3;
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
private readonly catalogService = inject(CatalogService);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -86,26 +98,33 @@ export class SearchPageComponent {
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.route.queryParamMap
|
||||
.pipe(
|
||||
map(
|
||||
(params): SearchRouteState => ({
|
||||
query: params.get('q')?.trim() ?? '',
|
||||
page: this.parsePage(params.get('page')),
|
||||
}),
|
||||
),
|
||||
distinctUntilChanged(
|
||||
(previous, current) => previous.query === current.query && previous.page === current.page,
|
||||
),
|
||||
tap(({ query }) => {
|
||||
this.query.set(query);
|
||||
this.results.set(null);
|
||||
this.error.set(
|
||||
query.length >= this.minSearchLength
|
||||
? null
|
||||
: `Ingresá al menos ${this.minSearchLength} caracteres para buscar.`,
|
||||
);
|
||||
const routeState$ = this.route.queryParamMap.pipe(
|
||||
map(
|
||||
(params): SearchRouteState => ({
|
||||
query: params.get('q')?.trim() ?? '',
|
||||
page: this.parsePage(params.get('page')),
|
||||
}),
|
||||
),
|
||||
distinctUntilChanged(
|
||||
(previous, current) => previous.query === current.query && previous.page === current.page,
|
||||
),
|
||||
tap(({ query }) => {
|
||||
this.query.set(query);
|
||||
this.results.set(null);
|
||||
this.error.set(
|
||||
query.length >= this.minSearchLength
|
||||
? null
|
||||
: `Ingresá al menos ${this.minSearchLength} caracteres para buscar.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
combineLatest([
|
||||
routeState$,
|
||||
this.catalogAvailabilityService.availabilityChanged$.pipe(startWith(undefined)),
|
||||
])
|
||||
.pipe(
|
||||
map(([routeState]) => routeState),
|
||||
switchMap(({ query, page }) => {
|
||||
if (query.length < this.minSearchLength) {
|
||||
return of(null);
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
</p>
|
||||
} @else {
|
||||
@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
|
||||
[layout]="group.layout"
|
||||
[groupLayout]="group.group_layout"
|
||||
|
||||
@@ -11,6 +11,10 @@ app-store-section + app-store-section {
|
||||
margin-top: clamp(3rem, 6vw, 5rem);
|
||||
}
|
||||
|
||||
app-store-section[id] {
|
||||
scroll-margin-top: 8rem;
|
||||
}
|
||||
|
||||
:host > .store-home__additional-info:not(:first-child) {
|
||||
margin-top: clamp(3rem, 6vw, 5rem);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
CatalogFeaturedItem,
|
||||
} from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { createCatalogAvailability } from '../../../../core/services/catalog/catalog-availability';
|
||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
@@ -58,6 +60,7 @@ function createCatalog(
|
||||
return [
|
||||
{
|
||||
id: 7,
|
||||
code: 'destacados',
|
||||
title: 'Destacados',
|
||||
layout: 'column_with_image',
|
||||
group_layout: 'paginated',
|
||||
@@ -77,15 +80,19 @@ function provideActivatedRoute(catalogData: StoreHomeCatalogResolvedData) {
|
||||
const pageOneItems: CatalogFeaturedItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
type: 'product',
|
||||
nombre: 'Auriculares Bluetooth',
|
||||
precio: '24999.00',
|
||||
image: '/catalog/auriculares.jpg',
|
||||
availability: createCatalogAvailability(null),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
type: 'product',
|
||||
nombre: 'Teclado Mecanico',
|
||||
precio: '18999.00',
|
||||
image: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -149,6 +156,7 @@ describe('StoreHomePageComponent', () => {
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
|
||||
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.querySelectorAll('app-product-column-with-image')).toHaveLength(2);
|
||||
expect(element.textContent).toContain('Auriculares Bluetooth');
|
||||
@@ -157,6 +165,30 @@ describe('StoreHomePageComponent', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('reloads the catalog when availability changes', async () => {
|
||||
const refreshedCatalog = createCatalog();
|
||||
const catalogServiceStub = {
|
||||
getCatalog: vi.fn().mockReturnValue(of(refreshedCatalog)),
|
||||
getFeaturedGroupItems: vi.fn(),
|
||||
withCustomLoading: vi.fn(),
|
||||
};
|
||||
catalogServiceStub.withCustomLoading.mockReturnValue(catalogServiceStub);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [StoreHomePageComponent],
|
||||
providers: [
|
||||
provideActivatedRoute({ response: createCatalog(), error: null }),
|
||||
{ provide: CatalogService, useValue: catalogServiceStub },
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(StoreHomePageComponent);
|
||||
fixture.detectChanges();
|
||||
TestBed.inject(CatalogAvailabilityService).notifyAvailabilityChanged();
|
||||
|
||||
expect(catalogServiceStub.getCatalog).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('renders the carousel URLs received in tenant extras', async () => {
|
||||
const carousel = ['https://example.com/carousel-1.webp', 'https://example.com/carousel-2.webp'];
|
||||
|
||||
@@ -376,7 +408,16 @@ describe('StoreHomePageComponent', () => {
|
||||
});
|
||||
|
||||
it('requests another page for the selected featured group', async () => {
|
||||
const pageTwoItems = [{ id: 3, nombre: 'Mouse Gamer', precio: '15999.00', image: null }];
|
||||
const pageTwoItems: CatalogFeaturedItem[] = [
|
||||
{
|
||||
id: 3,
|
||||
type: 'product',
|
||||
nombre: 'Mouse Gamer',
|
||||
precio: '15999.00',
|
||||
image: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
},
|
||||
];
|
||||
const catalogServiceStub = {
|
||||
getCatalog: vi.fn(),
|
||||
getFeaturedGroupItems: vi.fn().mockReturnValue(of(createItemsPage(pageTwoItems, 2, 2))),
|
||||
|
||||
@@ -15,6 +15,7 @@ import { finalize, Subscription } from 'rxjs';
|
||||
import { CartService } from '../../../../core/services/cart/cart.service';
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { CatalogFeaturedGroup } from '../../../../core/services/catalog/catalog.interface';
|
||||
import { CatalogAvailabilityService } from '../../../../core/services/catalog/catalog-availability.service';
|
||||
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
|
||||
import { TenantService } from '../../../../core/services/tenant.service';
|
||||
import { ToastService } from '../../../../core/services/toast.service';
|
||||
@@ -49,6 +50,7 @@ import {
|
||||
})
|
||||
export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
private readonly cartService = inject(CartService);
|
||||
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||
private readonly catalogService = inject(CatalogService);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
@@ -96,9 +98,13 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
protected readonly hasMainCarouselImages = computed(() => this.mainCarouselImages().length > 0);
|
||||
|
||||
private catalogRequestSubscription: Subscription | null = null;
|
||||
private availabilityChangedSubscription: Subscription | null = null;
|
||||
private readonly groupRequestSubscriptions = new Map<number, Subscription>();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.availabilityChangedSubscription =
|
||||
this.catalogAvailabilityService.availabilityChanged$.subscribe(() => this.loadCatalog(true));
|
||||
|
||||
const resolvedData = this.route.snapshot.data['catalogData'] as
|
||||
| StoreHomeCatalogResolvedData
|
||||
| undefined;
|
||||
@@ -112,6 +118,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.availabilityChangedSubscription?.unsubscribe();
|
||||
this.catalogRequestSubscription?.unsubscribe();
|
||||
this.groupRequestSubscriptions.forEach((subscription) => subscription.unsubscribe());
|
||||
}
|
||||
@@ -224,6 +231,11 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
if (error instanceof HttpErrorResponse && typeof error.error?.message === 'string') {
|
||||
this.toastService.danger(error.error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
this.toastService.danger('No se pudo iniciar la compra directa.');
|
||||
} finally {
|
||||
this.creatingDirectPurchase.set(false);
|
||||
@@ -259,20 +271,27 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private loadCatalog(): void {
|
||||
this.loading.set(true);
|
||||
this.error.set(null);
|
||||
private loadCatalog(silent = false): void {
|
||||
if (!silent) {
|
||||
this.loading.set(true);
|
||||
this.error.set(null);
|
||||
}
|
||||
this.catalogRequestSubscription?.unsubscribe();
|
||||
|
||||
this.catalogRequestSubscription = this.catalogService
|
||||
.withCustomLoading()
|
||||
.getCatalog()
|
||||
.subscribe({
|
||||
next: (catalog) => this.catalog.set(catalog),
|
||||
next: (catalog) => {
|
||||
this.catalog.set(catalog);
|
||||
this.error.set(null);
|
||||
},
|
||||
error: () => {
|
||||
this.catalog.set([]);
|
||||
if (!silent) {
|
||||
this.catalog.set([]);
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
}
|
||||
this.loading.set(false);
|
||||
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
|
||||
},
|
||||
complete: () => this.loading.set(false),
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<button
|
||||
type="button"
|
||||
[disabled]="disabled()"
|
||||
[class.cart-icon--disabled]="disabled()"
|
||||
[attr.aria-label]="ariaLabel()"
|
||||
[attr.aria-disabled]="disabled()"
|
||||
class="cart-icon"
|
||||
>
|
||||
<div class="cart-icon__container">
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
color: #666666;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: color 0.15s ease-in-out, transform 0.1s ease-in-out;
|
||||
transition:
|
||||
color 0.15s ease-in-out,
|
||||
transform 0.1s ease-in-out;
|
||||
border-radius: 4px;
|
||||
|
||||
// Active state subtle scale down
|
||||
@@ -29,10 +31,12 @@
|
||||
}
|
||||
|
||||
// Disabled state
|
||||
&:disabled {
|
||||
color: #A0A0A0;
|
||||
&:disabled,
|
||||
&.cart-icon--disabled {
|
||||
color: #b8b8b8;
|
||||
cursor: not-allowed;
|
||||
pointer-events: none;
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +63,11 @@
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.cart-icon:disabled .cart-icon__glyph,
|
||||
.cart-icon--disabled .cart-icon__glyph {
|
||||
color: #b8b8b8;
|
||||
}
|
||||
|
||||
.cart-icon__badge {
|
||||
position: absolute;
|
||||
top: -8px;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { CartIconComponent } from './cart-icon.component';
|
||||
describe('CartIconComponent', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartIconComponent]
|
||||
imports: [CartIconComponent],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('CartIconComponent', () => {
|
||||
|
||||
return {
|
||||
fixture,
|
||||
element: fixture.nativeElement as HTMLElement
|
||||
element: fixture.nativeElement as HTMLElement,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -47,9 +47,11 @@ describe('CartIconComponent', () => {
|
||||
});
|
||||
|
||||
it('disables the button when disabled is true', () => {
|
||||
const { element } = setup(undefined, true);
|
||||
const { element } = setup(3, true);
|
||||
const button = element.querySelector('button');
|
||||
expect(button?.disabled).toBe(true);
|
||||
expect(button?.classList).toContain('cart-icon--disabled');
|
||||
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('enables the button when disabled is false', () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ChangeDetectionStrategy, Component, computed, input } from '@angular/co
|
||||
imports: [],
|
||||
templateUrl: './cart-icon.component.html',
|
||||
styleUrl: './cart-icon.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class CartIconComponent {
|
||||
readonly quantity = input<number | null | undefined>(undefined);
|
||||
@@ -13,6 +13,10 @@ export class CartIconComponent {
|
||||
readonly ariaLabel = input<string>('Carrito de compras');
|
||||
|
||||
protected readonly hasQuantity = computed(() => {
|
||||
if (this.disabled()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const q = this.quantity();
|
||||
return q !== null && q !== undefined && q > 0;
|
||||
});
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (hasVariantSelectors() && !quantityDisabled()) {
|
||||
@if (hasVariantSelectors() && !variantDisabled()) {
|
||||
<app-variant-selector
|
||||
class="cart-item-variant-selector"
|
||||
[variants]="variants()"
|
||||
@@ -55,7 +55,7 @@
|
||||
(increase)="onIncrease()"
|
||||
(decrease)="onDecrease()"
|
||||
/>
|
||||
@if (!quantityDisabled() && showRemove()) {
|
||||
@if (!removeDisabled() && allowDelete()) {
|
||||
<app-icon-button variant="trash" class="cart-item-remove-btn" (click)="onRemove()" />
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -31,7 +31,9 @@ export class CartItemComponent {
|
||||
readonly quantity = input<number>(1);
|
||||
readonly readonly = input<boolean>(false);
|
||||
readonly quantityDisabled = input<boolean>(false);
|
||||
readonly showRemove = input<boolean>(true);
|
||||
readonly variantDisabled = input<boolean>(false);
|
||||
readonly removeDisabled = input<boolean>(false);
|
||||
readonly allowDelete = input<boolean>(true);
|
||||
|
||||
readonly quantityChange = output<number>();
|
||||
readonly remove = output<void>();
|
||||
@@ -61,7 +63,7 @@ export class CartItemComponent {
|
||||
}
|
||||
|
||||
protected onVariantChange(variant: unknown): void {
|
||||
if (!this.quantityDisabled() && typeof variant === 'number') {
|
||||
if (!this.variantDisabled() && typeof variant === 'number') {
|
||||
this.variantChange.emit(variant);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
<section
|
||||
class="d-flex flex-column h-100 overflow-hidden text-secondary"
|
||||
class="d-flex flex-column overflow-hidden text-secondary cart-shell"
|
||||
[style.background-color]="backgroundColor()"
|
||||
>
|
||||
<header class="d-flex align-items-center p-3 justify-content-between bg-transparent cart-header">
|
||||
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
|
||||
|
||||
<div class="d-flex align-items-center cart-header-actions">
|
||||
@if (!readonly() && editable() && allowEditing() && items().length > 0) {
|
||||
@if (
|
||||
allowModify() &&
|
||||
(!readonly() || showModifyWhenReadonly()) &&
|
||||
(requireEditingMode() || modifyAsAction()) &&
|
||||
items().length > 0
|
||||
) {
|
||||
<button
|
||||
class="btn btn-link p-0 border-0 cart-edit-btn"
|
||||
type="button"
|
||||
[attr.aria-pressed]="editing()"
|
||||
[attr.aria-pressed]="modifyAsAction() ? null : editing()"
|
||||
[disabled]="editingDisabled()"
|
||||
(click)="toggleEditing()"
|
||||
>
|
||||
{{ editing() ? 'Listo' : 'Modificar' }}
|
||||
{{ !modifyAsAction() && editing() ? 'Listo' : 'Modificar' }}
|
||||
</button>
|
||||
}
|
||||
|
||||
@@ -48,8 +53,22 @@
|
||||
[selectedVariant]="getItemVariant(item)"
|
||||
[quantity]="getItemQuantity(item)"
|
||||
[readonly]="readonly()"
|
||||
[quantityDisabled]="!editable() || editingDisabled() || (allowEditing() && !editing())"
|
||||
[showRemove]="allowRemove()"
|
||||
[quantityDisabled]="
|
||||
readonly() ||
|
||||
!allowUpdateQuantity() ||
|
||||
editingDisabled() ||
|
||||
(requireEditingMode() && !editing())
|
||||
"
|
||||
[variantDisabled]="
|
||||
readonly() ||
|
||||
!allowUpdateVariant() ||
|
||||
editingDisabled() ||
|
||||
(requireEditingMode() && !editing())
|
||||
"
|
||||
[removeDisabled]="
|
||||
readonly() || !allowDelete() || editingDisabled() || (requireEditingMode() && !editing())
|
||||
"
|
||||
[allowDelete]="allowDelete()"
|
||||
(quantityChange)="onItemQuantityChange(idx, $event)"
|
||||
(variantChange)="onItemVariantChange(idx, $event)"
|
||||
(remove)="onItemRemove(idx)"
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
:host {
|
||||
display: block;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
max-height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cart-shell {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.cart-header {
|
||||
|
||||
@@ -340,7 +340,7 @@ describe('CartComponent', () => {
|
||||
quantity: 1,
|
||||
},
|
||||
]);
|
||||
fixture.componentRef.setInput('allowEditing', true);
|
||||
fixture.componentRef.setInput('requireEditingMode', true);
|
||||
const editingChange = vi.fn();
|
||||
fixture.componentInstance.editing.subscribe(editingChange);
|
||||
fixture.detectChanges();
|
||||
@@ -367,6 +367,57 @@ describe('CartComponent', () => {
|
||||
expect(editingChange).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('emits Modificar as an action without toggling to Listo', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartComponent],
|
||||
providers: [
|
||||
{
|
||||
provide: CartService,
|
||||
useValue: {
|
||||
cart: signal(null).asReadonly(),
|
||||
updateItemQuantity: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
},
|
||||
},
|
||||
{ provide: ModalService, useValue: {} },
|
||||
{
|
||||
provide: ToastService,
|
||||
useValue: { success: vi.fn(), info: vi.fn(), danger: vi.fn() },
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(CartComponent);
|
||||
fixture.componentRef.setInput('items', [
|
||||
{
|
||||
cartItemId: 10,
|
||||
imageUrl: null,
|
||||
product: 'Producto de prueba',
|
||||
originalPrice: null,
|
||||
discountedPrice: 1000,
|
||||
discountPercentage: null,
|
||||
attributes: [],
|
||||
quantity: 1,
|
||||
},
|
||||
]);
|
||||
fixture.componentRef.setInput('readonly', true);
|
||||
fixture.componentRef.setInput('showModifyWhenReadonly', true);
|
||||
fixture.componentRef.setInput('modifyAsAction', true);
|
||||
const modify = vi.fn();
|
||||
fixture.componentInstance.modify.subscribe(modify);
|
||||
fixture.detectChanges();
|
||||
|
||||
const modifyButton = fixture.debugElement.query(By.css('.cart-edit-btn'));
|
||||
expect(modifyButton.nativeElement.textContent.trim()).toBe('Modificar');
|
||||
|
||||
modifyButton.nativeElement.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(modify).toHaveBeenCalledOnce();
|
||||
expect(modifyButton.nativeElement.textContent.trim()).toBe('Modificar');
|
||||
expect(fixture.componentInstance.editing()).toBe(false);
|
||||
});
|
||||
|
||||
it('allows editing directly when the optional Modificar toggle is disabled', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartComponent],
|
||||
@@ -408,7 +459,7 @@ describe('CartComponent', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('hides the edit toggle and disables quantity changes when editable is false', async () => {
|
||||
it('hides the edit toggle and disables quantity changes when quantity updates are false', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CartComponent],
|
||||
providers: [
|
||||
@@ -441,8 +492,9 @@ describe('CartComponent', () => {
|
||||
quantity: 1,
|
||||
},
|
||||
]);
|
||||
fixture.componentRef.setInput('allowEditing', true);
|
||||
fixture.componentRef.setInput('editable', false);
|
||||
fixture.componentRef.setInput('requireEditingMode', true);
|
||||
fixture.componentRef.setInput('allowModify', false);
|
||||
fixture.componentRef.setInput('allowUpdateQuantity', false);
|
||||
const quantityChange = vi.fn();
|
||||
fixture.componentInstance.itemQuantityChange.subscribe(quantityChange);
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -53,19 +53,32 @@ export class CartComponent {
|
||||
readonly total = input<number>(0);
|
||||
readonly backgroundColor = input<string>('#ffffff');
|
||||
readonly readonly = input<boolean>(false);
|
||||
readonly editable = input<boolean>(true);
|
||||
readonly allowEditing = input<boolean>(false);
|
||||
readonly allowRemove = input<boolean>(true);
|
||||
readonly allowUpdateQuantity = input<boolean>(true);
|
||||
readonly allowModify = input<boolean>(true);
|
||||
readonly showModifyWhenReadonly = input<boolean>(false);
|
||||
readonly modifyAsAction = input<boolean>(false);
|
||||
readonly requireEditingMode = input<boolean>(false);
|
||||
readonly allowUpdateVariant = input<boolean>(true);
|
||||
readonly allowDelete = input<boolean>(true);
|
||||
readonly persistQuantityChanges = input<boolean>(true);
|
||||
readonly persistVariantChanges = input<boolean>(true);
|
||||
readonly persistDeleteChanges = input<boolean>(true);
|
||||
readonly editingDisabled = input<boolean>(false);
|
||||
readonly editing = model<boolean>(false);
|
||||
|
||||
readonly closed = output<void>();
|
||||
readonly modify = output<void>();
|
||||
readonly itemQuantityChange = output<{
|
||||
item: CartItemMock;
|
||||
index: 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 variantOverrides = signal<Record<number, number>>({});
|
||||
@@ -125,7 +138,7 @@ export class CartComponent {
|
||||
}
|
||||
|
||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||
if (!this.editable()) {
|
||||
if (!this.allowUpdateQuantity()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -170,11 +183,19 @@ export class CartComponent {
|
||||
}
|
||||
|
||||
protected onItemVariantChange(index: number, variantId: number): void {
|
||||
if (this.readonly() || !this.allowUpdateVariant() || this.editingDisabled()) return;
|
||||
|
||||
const item = this.items()[index];
|
||||
const cartItemId = item?.cartItemId;
|
||||
|
||||
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.cartService
|
||||
.updateItemVariant(cartItemId, this.getItemQuantity(item), variantId)
|
||||
@@ -200,6 +221,8 @@ export class CartComponent {
|
||||
}
|
||||
|
||||
protected onItemRemove(index: number): void {
|
||||
if (this.readonly() || !this.allowDelete() || this.editingDisabled()) return;
|
||||
|
||||
const target = this.resolveRemoveTarget(index);
|
||||
|
||||
if (!target) {
|
||||
@@ -215,7 +238,14 @@ export class CartComponent {
|
||||
})
|
||||
.subscribe((confirmed) => {
|
||||
if (confirmed) {
|
||||
this.removeItem(target.cartItemId);
|
||||
const item = this.items()[index];
|
||||
if (item) {
|
||||
this.itemRemove.emit({ item, index });
|
||||
}
|
||||
|
||||
if (this.persistDeleteChanges()) {
|
||||
this.removeItem(target.cartItemId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -225,7 +255,12 @@ export class CartComponent {
|
||||
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
|
||||
|
||||
protected toggleEditing(): void {
|
||||
if (!this.editable() || this.editingDisabled()) {
|
||||
if (!this.allowModify() || this.editingDisabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.modifyAsAction()) {
|
||||
this.modify.emit();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,16 @@
|
||||
<div
|
||||
class="product-column-with-image__body p-3 d-flex flex-column align-items-center text-center flex-grow-1"
|
||||
>
|
||||
<h3 class="product-column-with-image__title text-uppercase text-black mb-4">{{ title() }}</h3>
|
||||
<h3 class="product-column-with-image__title text-uppercase text-black mb-4">
|
||||
{{ title() }}
|
||||
@if (unavailableMessage(); as message) {
|
||||
<app-tooltip [message]="message" />
|
||||
}
|
||||
</h3>
|
||||
|
||||
<div class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2">
|
||||
<div
|
||||
class="product-column-with-image__prices d-flex align-items-center justify-content-center gap-2"
|
||||
>
|
||||
<span class="product-column-with-image__price-discounted text-primary">
|
||||
{{ formattedDiscountedPrice() }}
|
||||
</span>
|
||||
@@ -53,7 +60,12 @@
|
||||
</div>
|
||||
|
||||
<div class="product-column-with-image__action mt-auto w-100">
|
||||
<app-button variant="primary" class="w-100" (click)="buy.emit()">
|
||||
<app-button
|
||||
variant="primary"
|
||||
class="w-100"
|
||||
[disabled]="!!unavailableMessage()"
|
||||
(click)="onBuy()"
|
||||
>
|
||||
{{ buttonText() }}
|
||||
</app-button>
|
||||
</div>
|
||||
|
||||
@@ -2,10 +2,11 @@ import { NgOptimizedImage } from '@angular/common';
|
||||
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
|
||||
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-column-with-image',
|
||||
imports: [ButtonComponent, NgOptimizedImage],
|
||||
imports: [ButtonComponent, NgOptimizedImage, TooltipComponent],
|
||||
templateUrl: './product-column-with-image.component.html',
|
||||
styleUrl: './product-column-with-image.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -18,9 +19,16 @@ export class ProductColumnWithImageComponent {
|
||||
readonly transferPrice = input<number | null>(null);
|
||||
readonly buttonText = input<string>('Comprar');
|
||||
readonly imagePriority = input<boolean>(false);
|
||||
readonly unavailableMessage = input<string | null>(null);
|
||||
|
||||
readonly buy = output<void>();
|
||||
|
||||
protected onBuy(): void {
|
||||
if (this.unavailableMessage()) return;
|
||||
|
||||
this.buy.emit();
|
||||
}
|
||||
|
||||
readonly discountedPrice = computed(() => {
|
||||
const original = this.originalPrice();
|
||||
const discount = this.discount();
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[availability]="itemAvailability(item)"
|
||||
[variants]="item.variants ?? []"
|
||||
[saving]="savingProductIds().has(item.id)"
|
||||
(buy)="emitRowBuy(item, $event)"
|
||||
@@ -23,6 +24,7 @@
|
||||
[title]="item.nombre"
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[availability]="itemAvailability(item)"
|
||||
[variants]="item.variants ?? []"
|
||||
[saving]="savingProductIds().has(item.id)"
|
||||
(buy)="emitColumnBuy(item, $event)"
|
||||
@@ -36,7 +38,8 @@
|
||||
[description]="item.descripcion ?? ''"
|
||||
[price]="price(item)"
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
[disabled]="loading()"
|
||||
[unavailableMessage]="availabilityMessage(item)"
|
||||
[disabled]="loading() || !allows(itemAvailability(item), 'buy_now')"
|
||||
(buy)="emitTicketBuy(item, $event)"
|
||||
/>
|
||||
}
|
||||
@@ -45,6 +48,7 @@
|
||||
[imageUrl]="loadImages() ? (item.image ?? null) : null"
|
||||
[title]="item.nombre"
|
||||
[originalPrice]="price(item)"
|
||||
[unavailableMessage]="availabilityMessage(item)"
|
||||
[imagePriority]="loadImages() && index < 4"
|
||||
(buy)="emitProductDetailBuy(item)"
|
||||
/>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { of } from 'rxjs';
|
||||
import { ApiPaginatedResponse } from '../../../core/services/api-paginated-response.interface';
|
||||
import { CartService } from '../../../core/services/cart/cart.service';
|
||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||
import { createCatalogAvailability } from '../../../core/services/catalog/catalog-availability';
|
||||
import {
|
||||
CatalogFeaturedItems,
|
||||
CatalogGroupLayout,
|
||||
@@ -23,6 +24,7 @@ describe('ProductListComponent', () => {
|
||||
descripcion: 'Primera descripcion',
|
||||
precio: '100.00',
|
||||
image: '/images/one.png',
|
||||
availability: createCatalogAvailability(null),
|
||||
variants: [],
|
||||
},
|
||||
{
|
||||
@@ -32,6 +34,7 @@ describe('ProductListComponent', () => {
|
||||
descripcion: 'Segunda descripcion',
|
||||
precio: 200,
|
||||
image: null,
|
||||
availability: createCatalogAvailability(null),
|
||||
variants: [],
|
||||
},
|
||||
];
|
||||
@@ -56,6 +59,20 @@ describe('ProductListComponent', () => {
|
||||
) {
|
||||
const getVariantOptions = vi.fn().mockReturnValue(
|
||||
of({
|
||||
variants: [
|
||||
{
|
||||
id: 401,
|
||||
precio: '10000.00',
|
||||
availability: createCatalogAvailability(1),
|
||||
values: { tipo: '1', sector: '2', fila: '3', asiento: '4' },
|
||||
},
|
||||
{
|
||||
id: 402,
|
||||
precio: '12000.00',
|
||||
availability: createCatalogAvailability(1),
|
||||
values: { tipo: '1', sector: '2', fila: '3', asiento: '5' },
|
||||
},
|
||||
],
|
||||
selectors: ['tipo', 'sector', 'fila', 'asiento'].map((key, index) => ({
|
||||
key,
|
||||
label: key,
|
||||
@@ -73,7 +90,12 @@ describe('ProductListComponent', () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ProductListComponent],
|
||||
providers: [
|
||||
{ provide: CatalogService, useValue: { getVariantOptions } },
|
||||
{
|
||||
provide: CatalogService,
|
||||
useValue: {
|
||||
withoutLoading: () => ({ getVariantOptions }),
|
||||
},
|
||||
},
|
||||
{ provide: CartService, useValue: {} },
|
||||
],
|
||||
}).compileComponents();
|
||||
@@ -193,8 +215,8 @@ describe('ProductListComponent', () => {
|
||||
const itemWithVariants: ProductListItem = {
|
||||
...items[0],
|
||||
variants: [
|
||||
{ id: 91, stock_tecnico: 3, values: { fecha: '10 de octubre' } },
|
||||
{ id: 92, stock_tecnico: 4, values: { fecha: '11 de octubre' } },
|
||||
{ id: 91, availability: createCatalogAvailability(3), values: { fecha: '10 de octubre' } },
|
||||
{ id: 92, availability: createCatalogAvailability(4), values: { fecha: '11 de octubre' } },
|
||||
],
|
||||
};
|
||||
const fixture = await render('column_with_cart', [itemWithVariants]);
|
||||
@@ -214,6 +236,58 @@ describe('ProductListComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('caps the quantity at the selected variant maximum', async () => {
|
||||
const itemWithVariants: ProductListItem = {
|
||||
...items[0],
|
||||
variants: [
|
||||
{
|
||||
id: 91,
|
||||
availability: createCatalogAvailability(2),
|
||||
values: { fecha: '10 de octubre' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const fixture = await render('column_with_cart', [itemWithVariants]);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const increase = fixture.nativeElement.querySelector(
|
||||
'.quantity-selector__button:last-child',
|
||||
) as HTMLButtonElement;
|
||||
|
||||
increase.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(
|
||||
(fixture.nativeElement as HTMLElement).querySelector('.quantity-selector__value')
|
||||
?.textContent,
|
||||
).toContain('2');
|
||||
expect(increase.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('disables purchase actions when the selected variant maximum is zero', async () => {
|
||||
const unavailableItem: ProductListItem = {
|
||||
...items[0],
|
||||
variants: [
|
||||
{
|
||||
id: 91,
|
||||
availability: createCatalogAvailability(0),
|
||||
values: { fecha: '10 de octubre' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const fixture = await render('row', [unavailableItem]);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const buttons = Array.from(
|
||||
(fixture.nativeElement as HTMLElement).querySelectorAll<HTMLButtonElement>(
|
||||
'.product-row-card__buttons button',
|
||||
),
|
||||
);
|
||||
|
||||
expect(buttons).toHaveLength(2);
|
||||
expect(buttons.every((button) => button.disabled)).toBe(true);
|
||||
});
|
||||
|
||||
it('renders pagination and emits the requested page', async () => {
|
||||
const fixture = await render('row');
|
||||
const pageChangeSpy = vi.fn();
|
||||
@@ -252,7 +326,7 @@ describe('ProductListComponent', () => {
|
||||
{
|
||||
id: 401,
|
||||
precio: '10000.00',
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: { value: 'vip', label: 'VIP' },
|
||||
sector: { value: 'a', label: 'Sector A' },
|
||||
@@ -263,7 +337,7 @@ describe('ProductListComponent', () => {
|
||||
{
|
||||
id: 402,
|
||||
precio: '12000.00',
|
||||
stock_tecnico: 1,
|
||||
availability: createCatalogAvailability(1),
|
||||
values: {
|
||||
tipo: { value: 'vip', label: 'VIP' },
|
||||
sector: { value: 'a', label: 'Sector A' },
|
||||
|
||||
@@ -18,6 +18,11 @@ import {
|
||||
CatalogGroupLayout,
|
||||
CatalogProductLayout,
|
||||
} from '../../../core/services/catalog/catalog.interface';
|
||||
import {
|
||||
AVAILABLE_CATALOG_AVAILABILITY,
|
||||
allowsCatalogAction,
|
||||
primaryAvailabilityMessage,
|
||||
} from '../../../core/services/catalog/catalog-availability';
|
||||
import { CarouselComponent } from '../carousel/carousel.component';
|
||||
import { PaginatorComponent } from '../paginator/paginator.component';
|
||||
import { ProductColumnWithImageComponent } from '../product-column-with-image/product-column-with-image.component';
|
||||
@@ -74,6 +79,7 @@ export class ProductListComponent {
|
||||
readonly buy = output<ProductListBuyEvent>();
|
||||
readonly addToCart = output<ProductListCartEvent>();
|
||||
readonly pageChange = output<number>();
|
||||
protected readonly allows = allowsCatalogAction;
|
||||
|
||||
protected readonly effectiveLayout = computed<ProductListLayout>(() =>
|
||||
this.mobile() && this.layout() === 'row' ? 'column_with_cart' : this.layout(),
|
||||
@@ -108,6 +114,14 @@ export class ProductListComponent {
|
||||
return Number.isFinite(price) ? price : 0;
|
||||
}
|
||||
|
||||
protected availabilityMessage(item: ProductListItem): string | null {
|
||||
return primaryAvailabilityMessage(this.itemAvailability(item));
|
||||
}
|
||||
|
||||
protected itemAvailability(item: ProductListItem) {
|
||||
return item.availability ?? AVAILABLE_CATALOG_AVAILABILITY;
|
||||
}
|
||||
|
||||
protected emitRowCart(
|
||||
product: ProductListItem,
|
||||
event: { quantity: number; variant: unknown },
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
<div class="product-row-card__info d-flex flex-column justify-content-center flex-grow-1">
|
||||
<h3 class="product-row-card__title text-uppercase mb-1 m-0">
|
||||
{{ title() }}
|
||||
@if (effectiveUnavailableMessage(); as message) {
|
||||
<app-tooltip [message]="message" />
|
||||
}
|
||||
</h3>
|
||||
@if (effectiveDescription()) {
|
||||
<p class="product-row-card__description m-0 mt-1">
|
||||
@@ -18,10 +21,15 @@
|
||||
<app-variant-selector
|
||||
class="product-row-card__selectors"
|
||||
[variants]="variants()"
|
||||
[disabled]="!allows(availability(), 'select_variant')"
|
||||
[(selectedVariant)]="selectedVariant"
|
||||
/>
|
||||
|
||||
<app-quantity-selector [(quantity)]="quantity"></app-quantity-selector>
|
||||
<app-quantity-selector
|
||||
[(quantity)]="quantity"
|
||||
[max]="effectiveMaximum()"
|
||||
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span class="product-row-card__price text-primary">
|
||||
@@ -31,10 +39,24 @@
|
||||
|
||||
<div class="product-row-card__buttons">
|
||||
<div class="product-row-card__btn-wrapper">
|
||||
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button>
|
||||
<app-button
|
||||
variant="primary"
|
||||
[disabled]="!hasPurchasableSelection() || !allows(effectiveAvailability(), 'buy_now')"
|
||||
(click)="onBuy()"
|
||||
>
|
||||
Comprar
|
||||
</app-button>
|
||||
</div>
|
||||
<div class="product-row-card__btn-wrapper">
|
||||
<app-button variant="secondary" [disabled]="saving()" (click)="onAddToCart()">
|
||||
<app-button
|
||||
variant="secondary"
|
||||
[disabled]="
|
||||
saving() ||
|
||||
!hasPurchasableSelection() ||
|
||||
!allows(effectiveAvailability(), 'add_to_cart')
|
||||
"
|
||||
(click)="onAddToCart()"
|
||||
>
|
||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||
</app-button>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +1,39 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
} from '@angular/core';
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
|
||||
import {
|
||||
AVAILABLE_CATALOG_AVAILABILITY,
|
||||
allowsCatalogAction,
|
||||
combineCatalogAvailability,
|
||||
maximumCatalogQuantity,
|
||||
primaryAvailabilityMessage,
|
||||
} from '../../../core/services/catalog/catalog-availability';
|
||||
|
||||
export interface Variant extends VariantSelectorVariant {
|
||||
label?: string;
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
stock_tecnico?: number | null;
|
||||
availability?: CatalogAvailability;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-row-card',
|
||||
standalone: true,
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
|
||||
templateUrl: './product-row-card.component.html',
|
||||
styleUrl: './product-row-card.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -26,6 +43,7 @@ export class ProductRowCardComponent {
|
||||
readonly title = input<string>('');
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
|
||||
readonly variants = input<Variant[]>([]);
|
||||
readonly saving = input(false);
|
||||
|
||||
@@ -48,11 +66,39 @@ export class ProductRowCardComponent {
|
||||
|
||||
return Number.isFinite(variantPrice) ? variantPrice : this.price();
|
||||
});
|
||||
protected readonly effectiveAvailability = computed(() =>
|
||||
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
|
||||
);
|
||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||
protected readonly hasPurchasableSelection = computed(
|
||||
() => !this.hasVariants() || this.selectedVariantData() !== undefined,
|
||||
);
|
||||
protected readonly effectiveMaximum = computed(() =>
|
||||
maximumCatalogQuantity(this.effectiveAvailability()),
|
||||
);
|
||||
protected readonly effectiveUnavailableMessage = computed(() =>
|
||||
primaryAvailabilityMessage(this.effectiveAvailability()),
|
||||
);
|
||||
|
||||
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
protected readonly allows = allowsCatalogAction;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const maximum = this.effectiveMaximum();
|
||||
|
||||
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||
this.quantity.set(maximum);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected onAddToCart(): void {
|
||||
if (this.saving()) {
|
||||
if (
|
||||
this.saving() ||
|
||||
!this.hasPurchasableSelection() ||
|
||||
!this.allows(this.effectiveAvailability(), 'add_to_cart')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -63,6 +109,9 @@ export class ProductRowCardComponent {
|
||||
}
|
||||
|
||||
protected onBuy(): void {
|
||||
if (!this.hasPurchasableSelection() || !this.allows(this.effectiveAvailability(), 'buy_now'))
|
||||
return;
|
||||
|
||||
this.buy.emit({
|
||||
quantity: this.quantity(),
|
||||
variant: this.selectedVariant(),
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
<article class="ticket-selector">
|
||||
<header class="ticket-selector__header">
|
||||
<div>
|
||||
<h3 class="ticket-selector__title">{{ title() }}</h3>
|
||||
<h3 class="ticket-selector__title">
|
||||
{{ title() }}
|
||||
@if (unavailableMessage(); as message) {
|
||||
<app-tooltip [message]="message" />
|
||||
}
|
||||
</h3>
|
||||
@if (description()) {
|
||||
<p class="ticket-selector__description">{{ description() }}</p>
|
||||
}
|
||||
@@ -20,6 +25,17 @@
|
||||
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
|
||||
|
||||
<div class="ticket-selector__rows">
|
||||
@if (attributes().length > 0) {
|
||||
<div class="ticket-selector__columns" aria-hidden="true">
|
||||
<div class="ticket-selector__column-labels">
|
||||
@for (attribute of attributes(); track attribute.key) {
|
||||
<span class="ticket-selector__column-label">{{ attribute.label }}</span>
|
||||
}
|
||||
</div>
|
||||
<span class="ticket-selector__action-spacer"></span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@for (row of rows(); track row.id) {
|
||||
<div class="ticket-selector__row">
|
||||
<div class="ticket-selector__row-content">
|
||||
|
||||
@@ -57,6 +57,30 @@
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__columns {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__column-labels {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(120px, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
&__column-label {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__action-spacer {
|
||||
width: 38px;
|
||||
}
|
||||
|
||||
&__row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
@@ -160,6 +184,10 @@
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
&__columns {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&__map {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
@@ -209,6 +209,23 @@ describe('ProductTicketSelectorComponent', () => {
|
||||
expect(removeButton?.classList.contains('icon-btn--bordered')).toBe(true);
|
||||
});
|
||||
|
||||
it('shows one header row with the label of every selector', async () => {
|
||||
const { fixture } = await createComponent({
|
||||
maps: [mapResponse([variant(401, 'general', 'A', '1', '1')])],
|
||||
});
|
||||
|
||||
const headerRows = fixture.nativeElement.querySelectorAll('.ticket-selector__columns');
|
||||
const labels = fixture.nativeElement.querySelectorAll('.ticket-selector__column-label');
|
||||
|
||||
expect(headerRows).toHaveLength(1);
|
||||
expect([...labels].map((label: Element) => label.textContent?.trim())).toEqual([
|
||||
'Tipo',
|
||||
'Sector',
|
||||
'Fila',
|
||||
'Asiento',
|
||||
]);
|
||||
});
|
||||
|
||||
it('clears only the seat after a stock conflict when the row still has alternatives', async () => {
|
||||
const failed = variant(401, 'general', 'A', '1', '1');
|
||||
const alternative = variant(402, 'general', 'A', '1', '2');
|
||||
|
||||
@@ -23,11 +23,16 @@ import {
|
||||
CatalogVariantSelector,
|
||||
CatalogVariantValue,
|
||||
} from '../../../core/services/catalog/catalog.interface';
|
||||
import {
|
||||
allowsCatalogAction,
|
||||
createCatalogAvailability,
|
||||
} from '../../../core/services/catalog/catalog-availability';
|
||||
import { CatalogService } from '../../../core/services/catalog/catalog.service';
|
||||
import { ModalService } from '../../../core/services/modal.service';
|
||||
import { ToastService } from '../../../core/services/toast.service';
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { IconButtonComponent } from '../icon-button/icon-button.component';
|
||||
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||
|
||||
type TicketSelectionStatus =
|
||||
| 'selecting'
|
||||
@@ -56,7 +61,7 @@ interface TicketSelectionRow {
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-ticket-selector',
|
||||
imports: [ButtonComponent, IconButtonComponent],
|
||||
imports: [ButtonComponent, IconButtonComponent, TooltipComponent],
|
||||
templateUrl: './product-ticket-selector.component.html',
|
||||
styleUrl: './product-ticket-selector.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -71,7 +76,7 @@ export class ProductTicketSelectorComponent {
|
||||
private readonly viewReady = signal(false);
|
||||
private readonly mapReady = signal(false);
|
||||
private readonly variants = signal<CatalogFeaturedItemVariant[]>([]);
|
||||
private readonly attributes = signal<VariantAttribute[]>([]);
|
||||
protected readonly attributes = signal<VariantAttribute[]>([]);
|
||||
private mapRequest: Subscription | null = null;
|
||||
|
||||
readonly productId = input.required<number>();
|
||||
@@ -80,6 +85,7 @@ export class ProductTicketSelectorComponent {
|
||||
readonly price = input<number>(0);
|
||||
readonly imageUrl = input<string | null>(null);
|
||||
readonly disabled = input(false);
|
||||
readonly unavailableMessage = input<string | null>(null);
|
||||
|
||||
readonly buy = output<number[]>();
|
||||
|
||||
@@ -351,7 +357,11 @@ export class ProductTicketSelectorComponent {
|
||||
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
|
||||
variants.push(reservedVariant);
|
||||
}
|
||||
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
|
||||
return variants.filter(
|
||||
({ id, availability }) =>
|
||||
(availability === undefined || allowsCatalogAction(availability, 'select_variant')) &&
|
||||
!reservedByOtherRows.has(id),
|
||||
);
|
||||
}
|
||||
|
||||
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
|
||||
@@ -361,7 +371,9 @@ export class ProductTicketSelectorComponent {
|
||||
return {
|
||||
id: item.variant.id,
|
||||
precio: item.variant.precio,
|
||||
stock_tecnico: item.variant.stock_tecnico,
|
||||
availability: createCatalogAvailability(
|
||||
item.variant.stock_tecnico === null ? null : item.variant.stock_tecnico + item.cantidad,
|
||||
),
|
||||
values: item.variant.values,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
<article class="product-vertical-with-cart-card">
|
||||
<div class="product-vertical-with-cart-card__content">
|
||||
<h3 class="product-vertical-with-cart-card__title">{{ title() }}</h3>
|
||||
<h3 class="product-vertical-with-cart-card__title">
|
||||
{{ title() }}
|
||||
@if (effectiveUnavailableMessage(); as message) {
|
||||
<app-tooltip [message]="message" />
|
||||
}
|
||||
</h3>
|
||||
|
||||
@if (effectiveDescription()) {
|
||||
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
|
||||
@@ -11,17 +16,29 @@
|
||||
@if (!hasVariants()) {
|
||||
<div class="product-vertical-with-cart-card__summary">
|
||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||
<app-quantity-selector [(quantity)]="quantity" />
|
||||
<app-quantity-selector
|
||||
[(quantity)]="quantity"
|
||||
[max]="effectiveMaximum()"
|
||||
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||
/>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="product-vertical-with-cart-card__variants">
|
||||
<div class="product-vertical-with-cart-card__summary">
|
||||
<span class="product-vertical-with-cart-card__price">{{ formattedPrice() }}</span>
|
||||
<app-quantity-selector [(quantity)]="quantity" />
|
||||
<app-quantity-selector
|
||||
[(quantity)]="quantity"
|
||||
[max]="effectiveMaximum()"
|
||||
[disabled]="!allows(effectiveAvailability(), 'change_quantity')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="product-vertical-with-cart-card__variant-selectors">
|
||||
<app-variant-selector [variants]="variants()" [(selectedVariant)]="selectedVariant" />
|
||||
<app-variant-selector
|
||||
[variants]="variants()"
|
||||
[disabled]="!allows(availability(), 'select_variant')"
|
||||
[(selectedVariant)]="selectedVariant"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -29,14 +46,21 @@
|
||||
<div class="product-vertical-with-cart-card__actions">
|
||||
<app-button
|
||||
variant="primary"
|
||||
[disabled]="hasVariants() && selectedVariant() === null"
|
||||
[disabled]="
|
||||
!allows(effectiveAvailability(), 'buy_now') ||
|
||||
(hasVariants() && selectedVariant() === null)
|
||||
"
|
||||
(click)="onBuy()"
|
||||
>
|
||||
Comprar
|
||||
</app-button>
|
||||
<app-button
|
||||
variant="secondary"
|
||||
[disabled]="saving() || (hasVariants() && selectedVariant() === null)"
|
||||
[disabled]="
|
||||
saving() ||
|
||||
!allows(effectiveAvailability(), 'add_to_cart') ||
|
||||
(hasVariants() && selectedVariant() === null)
|
||||
"
|
||||
(click)="onAddToCart()"
|
||||
>
|
||||
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
|
||||
|
||||
@@ -56,6 +56,29 @@ describe('ProductVerticalWithCartCardComponent', () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the backend availability message with the reusable tooltip', async () => {
|
||||
const fixture = await createComponent();
|
||||
fixture.componentRef.setInput('availability', {
|
||||
state: 'visible',
|
||||
maximum_quantity: 0,
|
||||
reasons: [
|
||||
{
|
||||
code: 'user_quota_reached',
|
||||
message: 'Alcanzaste el cupo máximo permitido para este producto.',
|
||||
},
|
||||
],
|
||||
allowed_actions: [],
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const tooltip = (fixture.nativeElement as HTMLElement).querySelector('app-tooltip');
|
||||
|
||||
expect(tooltip?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
|
||||
expect(tooltip?.textContent).toContain(
|
||||
'Alcanzaste el cupo máximo permitido para este producto.',
|
||||
);
|
||||
});
|
||||
|
||||
it('updates the quantity with the reusable quantity selector', async () => {
|
||||
const fixture = await createComponent();
|
||||
const buttons = fixture.nativeElement.querySelectorAll(
|
||||
|
||||
@@ -1,20 +1,38 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
} from '@angular/core';
|
||||
|
||||
import { ButtonComponent } from '../button/button.component';
|
||||
import { QuantitySelectorComponent } from '../quantity-selector/quantity-selector.component';
|
||||
import { TooltipComponent } from '../tooltip/tooltip.component';
|
||||
import {
|
||||
VariantSelectorComponent,
|
||||
VariantSelectorVariant,
|
||||
} from '../variant-selector/variant-selector.component';
|
||||
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
|
||||
import {
|
||||
AVAILABLE_CATALOG_AVAILABILITY,
|
||||
allowsCatalogAction,
|
||||
combineCatalogAvailability,
|
||||
maximumCatalogQuantity,
|
||||
primaryAvailabilityMessage,
|
||||
} from '../../../core/services/catalog/catalog-availability';
|
||||
|
||||
export interface VerticalCartVariant extends VariantSelectorVariant {
|
||||
descripcion?: string | null;
|
||||
precio?: string | number;
|
||||
availability?: CatalogAvailability;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-product-vertical-with-cart-card',
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, VariantSelectorComponent],
|
||||
imports: [ButtonComponent, QuantitySelectorComponent, TooltipComponent, VariantSelectorComponent],
|
||||
templateUrl: './product-vertical-with-cart-card.component.html',
|
||||
styleUrl: './product-vertical-with-cart-card.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -23,6 +41,7 @@ export class ProductVerticalWithCartCardComponent {
|
||||
readonly title = input<string>('');
|
||||
readonly description = input<string>('');
|
||||
readonly price = input<number>(0);
|
||||
readonly availability = input<CatalogAvailability>(AVAILABLE_CATALOG_AVAILABILITY);
|
||||
readonly variants = input<VerticalCartVariant[]>([]);
|
||||
readonly saving = input(false);
|
||||
|
||||
@@ -45,9 +64,29 @@ export class ProductVerticalWithCartCardComponent {
|
||||
});
|
||||
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
|
||||
protected readonly hasVariants = computed(() => this.variants().length > 0);
|
||||
protected readonly effectiveAvailability = computed(() =>
|
||||
combineCatalogAvailability(this.availability(), this.selectedVariantData()?.availability),
|
||||
);
|
||||
protected readonly effectiveMaximum = computed(() =>
|
||||
maximumCatalogQuantity(this.effectiveAvailability()),
|
||||
);
|
||||
protected readonly effectiveUnavailableMessage = computed(() =>
|
||||
primaryAvailabilityMessage(this.effectiveAvailability()),
|
||||
);
|
||||
protected readonly allows = allowsCatalogAction;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const maximum = this.effectiveMaximum();
|
||||
|
||||
if (maximum !== null && maximum > 0 && this.quantity() > maximum) {
|
||||
this.quantity.set(maximum);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected onAddToCart(): void {
|
||||
if (this.saving()) {
|
||||
if (this.saving() || !this.allows(this.effectiveAvailability(), 'add_to_cart')) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,6 +94,8 @@ export class ProductVerticalWithCartCardComponent {
|
||||
}
|
||||
|
||||
protected onBuy(): void {
|
||||
if (!this.allows(this.effectiveAvailability(), 'buy_now')) return;
|
||||
|
||||
this.buy.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
<div class="stepper-container">
|
||||
|
||||
<!-- Horizontal indicator bar -->
|
||||
<div class="stepper-header">
|
||||
<div class="stepper-header" [class.is-disabled]="disabled()" [attr.aria-disabled]="disabled()">
|
||||
@for (step of steps(); track step; let i = $index; let last = $last) {
|
||||
<div
|
||||
class="stepper-header__item"
|
||||
[ngClass]="{
|
||||
'is-active': currentStepIndex() === i,
|
||||
'is-completed': currentStepIndex() > i
|
||||
'is-completed': currentStepIndex() > i,
|
||||
}"
|
||||
>
|
||||
<!-- Connecting line before (except first) -->
|
||||
@if (i > 0) {
|
||||
<div class="stepper-header__line" [ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"></div>
|
||||
<div
|
||||
class="stepper-header__line"
|
||||
[ngClass]="{ 'is-completed': currentStepIndex() > i - 1 }"
|
||||
></div>
|
||||
}
|
||||
|
||||
<!-- Circle indicator -->
|
||||
<div
|
||||
class="stepper-header__circle"
|
||||
[attr.aria-label]="step.label()"
|
||||
[class.is-clickable]="currentStepIndex() > i"
|
||||
[class.is-clickable]="!disabled() && currentStepIndex() > i"
|
||||
(click)="goToStep(i)"
|
||||
></div>
|
||||
|
||||
@@ -33,5 +35,4 @@
|
||||
<div class="stepper-body">
|
||||
<ng-content></ng-content>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -13,6 +13,14 @@
|
||||
margin-bottom: 2rem;
|
||||
position: relative;
|
||||
|
||||
&.is-disabled {
|
||||
opacity: 0.5;
|
||||
|
||||
.stepper-header__circle {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
&__item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { StepComponent } from './step.component';
|
||||
@Component({
|
||||
imports: [StepperComponent, StepComponent],
|
||||
template: `
|
||||
<app-stepper #stepper>
|
||||
<app-stepper #stepper [disabled]="stepperDisabled()">
|
||||
<app-step label="Step 1" [isValid]="step1Valid()">
|
||||
<div id="content-1">Content 1</div>
|
||||
</app-step>
|
||||
@@ -20,6 +20,7 @@ class TestHostComponent {
|
||||
@ViewChild('stepper') stepper!: StepperComponent;
|
||||
step1Valid = signal(true);
|
||||
step2Valid = signal(true);
|
||||
stepperDisabled = signal(false);
|
||||
}
|
||||
|
||||
describe('StepperComponent & StepComponent', () => {
|
||||
@@ -137,4 +138,28 @@ describe('StepperComponent & StepComponent', () => {
|
||||
expect(component.stepper.currentStepIndex()).toBe(0);
|
||||
expect(fixture.nativeElement.querySelector('#content-1')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('blocks all navigation and shows visual feedback while disabled', async () => {
|
||||
const { fixture, component } = await setup();
|
||||
component.stepperDisabled.set(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
component.stepper.next();
|
||||
expect(component.stepper.currentStepIndex()).toBe(0);
|
||||
|
||||
component.stepperDisabled.set(false);
|
||||
fixture.detectChanges();
|
||||
component.stepper.next();
|
||||
expect(component.stepper.currentStepIndex()).toBe(1);
|
||||
|
||||
component.stepperDisabled.set(true);
|
||||
fixture.detectChanges();
|
||||
component.stepper.previous();
|
||||
component.stepper.goToStep(0);
|
||||
|
||||
expect(component.stepper.currentStepIndex()).toBe(1);
|
||||
const header = fixture.nativeElement.querySelector('.stepper-header');
|
||||
expect(header.classList.contains('is-disabled')).toBe(true);
|
||||
expect(header.getAttribute('aria-disabled')).toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,9 +18,12 @@ import { NgClass } from '@angular/common';
|
||||
export class StepperComponent {
|
||||
readonly steps = contentChildren(StepComponent);
|
||||
readonly initialStepIndex = input(0);
|
||||
readonly disabled = input(false);
|
||||
readonly currentStepIndex = linkedSignal(() => this.initialStepIndex());
|
||||
|
||||
next() {
|
||||
if (this.disabled()) return;
|
||||
|
||||
const currentSteps = this.steps();
|
||||
const currentIndex = this.currentStepIndex();
|
||||
if (currentIndex < currentSteps.length - 1) {
|
||||
@@ -32,6 +35,8 @@ export class StepperComponent {
|
||||
}
|
||||
|
||||
previous() {
|
||||
if (this.disabled()) return;
|
||||
|
||||
const currentIndex = this.currentStepIndex();
|
||||
if (currentIndex > 0) {
|
||||
this.currentStepIndex.set(currentIndex - 1);
|
||||
@@ -39,6 +44,8 @@ export class StepperComponent {
|
||||
}
|
||||
|
||||
goToStep(index: number) {
|
||||
if (this.disabled()) return;
|
||||
|
||||
const targetIndex = index;
|
||||
// Only allow navigating to completed steps or the current one
|
||||
if (targetIndex < this.currentStepIndex()) {
|
||||
|
||||
11
src/app/shared/components/tooltip/tooltip.component.html
Normal file
11
src/app/shared/components/tooltip/tooltip.component.html
Normal file
@@ -0,0 +1,11 @@
|
||||
<button
|
||||
type="button"
|
||||
class="tooltip-trigger"
|
||||
[attr.aria-describedby]="tooltipId"
|
||||
[attr.aria-label]="message()"
|
||||
>
|
||||
<i class="fa-solid fa-circle-info" aria-hidden="true"></i>
|
||||
<span class="tooltip-message" [id]="tooltipId" role="tooltip">
|
||||
{{ message() }}
|
||||
</span>
|
||||
</button>
|
||||
62
src/app/shared/components/tooltip/tooltip.component.scss
Normal file
62
src/app/shared/components/tooltip/tooltip.component.scss
Normal file
@@ -0,0 +1,62 @@
|
||||
:host {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: 0.25rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.tooltip-trigger {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--tenant-primary, var(--color-primary, #0d6efd));
|
||||
font-size: 1em;
|
||||
line-height: inherit;
|
||||
|
||||
&:focus-visible {
|
||||
border-radius: 50%;
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
&:hover .tooltip-message,
|
||||
&:focus-visible .tooltip-message {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -0.25rem);
|
||||
}
|
||||
}
|
||||
|
||||
.tooltip-message {
|
||||
position: absolute;
|
||||
z-index: 1100;
|
||||
bottom: calc(100% + 0.625rem);
|
||||
left: 50%;
|
||||
width: max-content;
|
||||
max-width: min(16rem, 75vw);
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--tenant-primary, var(--color-primary, #0d6efd));
|
||||
background: #fff;
|
||||
color: #212529;
|
||||
font-family: inherit;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 400;
|
||||
line-height: 1.35;
|
||||
text-align: center;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
white-space: normal;
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: translate(-50%, 0);
|
||||
transition:
|
||||
opacity 0.15s ease,
|
||||
transform 0.15s ease,
|
||||
visibility 0.15s ease;
|
||||
}
|
||||
32
src/app/shared/components/tooltip/tooltip.component.spec.ts
Normal file
32
src/app/shared/components/tooltip/tooltip.component.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { TooltipComponent } from './tooltip.component';
|
||||
|
||||
describe('TooltipComponent', () => {
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => TestBed.resetTestingModule());
|
||||
|
||||
it('renders the reusable danger information tooltip', async () => {
|
||||
await TestBed.configureTestingModule({ imports: [TooltipComponent] }).compileComponents();
|
||||
const fixture = TestBed.createComponent(TooltipComponent);
|
||||
fixture.componentRef.setInput('message', 'Este producto no tiene stock disponible.');
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const trigger = element.querySelector('.tooltip-trigger');
|
||||
const message = element.querySelector('.tooltip-message');
|
||||
|
||||
expect(trigger?.querySelector('i.fa-solid.fa-circle-info')).not.toBeNull();
|
||||
expect(message?.textContent?.trim()).toBe('Este producto no tiene stock disponible.');
|
||||
expect(trigger?.getAttribute('aria-describedby')).toBe(message?.id);
|
||||
});
|
||||
});
|
||||
14
src/app/shared/components/tooltip/tooltip.component.ts
Normal file
14
src/app/shared/components/tooltip/tooltip.component.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
||||
|
||||
let nextTooltipId = 0;
|
||||
|
||||
@Component({
|
||||
selector: 'app-tooltip',
|
||||
templateUrl: './tooltip.component.html',
|
||||
styleUrl: './tooltip.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class TooltipComponent {
|
||||
readonly message = input.required<string>();
|
||||
protected readonly tooltipId = `app-tooltip-${nextTooltipId++}`;
|
||||
}
|
||||
@@ -62,6 +62,8 @@ describe('VariantSelectorComponent', () => {
|
||||
]);
|
||||
fixture.componentRef.setInput('selectedVariant', 2);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
const selects = Array.from(
|
||||
fixture.nativeElement.querySelectorAll('select'),
|
||||
@@ -80,6 +82,28 @@ describe('VariantSelectorComponent', () => {
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(1);
|
||||
});
|
||||
|
||||
it('does not offer variants whose availability forbids selection', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(VariantSelectorComponent);
|
||||
fixture.componentRef.setInput('variants', [
|
||||
{ id: 1, values: { talle: 'S' } },
|
||||
{
|
||||
id: 2,
|
||||
values: { talle: 'M' },
|
||||
availability: { state: 'visible', maximum_quantity: 0, allowed_actions: [], reasons: [] },
|
||||
},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent).toContain('S');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('M');
|
||||
expect(fixture.componentInstance.selectedVariant()).toBe(1);
|
||||
});
|
||||
|
||||
it('requires manual selections when autoSelectFirst is disabled', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VariantSelectorComponent],
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
untracked,
|
||||
} from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { CatalogAvailability } from '../../../core/services/catalog/catalog.interface';
|
||||
import { allowsCatalogAction } from '../../../core/services/catalog/catalog-availability';
|
||||
|
||||
export interface VariantAttributeOption {
|
||||
value: string;
|
||||
@@ -22,6 +24,7 @@ export type VariantAttributeValue = VariantAttributeScalar | VariantAttributeSca
|
||||
export interface VariantSelectorVariant {
|
||||
id: unknown;
|
||||
values: Record<string, VariantAttributeValue>;
|
||||
availability?: CatalogAvailability;
|
||||
}
|
||||
|
||||
export interface VariantSelectorSelectionChange {
|
||||
@@ -64,10 +67,12 @@ export class VariantSelectorComponent {
|
||||
right: VariantAttributeValue | null,
|
||||
): boolean => left !== null && right !== null && this.sameValue(left, right);
|
||||
protected readonly attributeKeys = computed(() =>
|
||||
Array.from(new Set(this.variants().flatMap((variant) => Object.keys(variant.values)))),
|
||||
Array.from(
|
||||
new Set(this.getSelectableVariants().flatMap((variant) => Object.keys(variant.values))),
|
||||
),
|
||||
);
|
||||
protected readonly selectors = computed<VariantSelectorGroup[]>(() => {
|
||||
const variants = this.variants();
|
||||
const variants = this.getSelectableVariants();
|
||||
const keys = this.attributeKeys();
|
||||
const selectedValues = this.selectedValues();
|
||||
|
||||
@@ -110,7 +115,7 @@ export class VariantSelectorComponent {
|
||||
});
|
||||
|
||||
effect(() => {
|
||||
const variants = this.variants();
|
||||
const variants = this.getSelectableVariants();
|
||||
const selectedVariant = this.selectedVariant();
|
||||
const autoSelectFirst = this.autoSelectFirst();
|
||||
|
||||
@@ -139,7 +144,7 @@ export class VariantSelectorComponent {
|
||||
}
|
||||
|
||||
protected onValueChange(key: string, value: VariantAttributeValue | null): void {
|
||||
const variants = this.variants();
|
||||
const variants = this.getSelectableVariants();
|
||||
const keys = this.attributeKeys();
|
||||
const changedIndex = keys.indexOf(key);
|
||||
const values = { ...this.selectedValues() };
|
||||
@@ -198,6 +203,14 @@ export class VariantSelectorComponent {
|
||||
return Array.from(options.values());
|
||||
}
|
||||
|
||||
private getSelectableVariants(): VariantSelectorVariant[] {
|
||||
return this.variants().filter(
|
||||
(variant) =>
|
||||
variant.availability === undefined ||
|
||||
allowsCatalogAction(variant.availability, 'select_variant'),
|
||||
);
|
||||
}
|
||||
|
||||
private reconcileManualSelection(
|
||||
selectedValues: Record<string, VariantAttributeValue>,
|
||||
variants: VariantSelectorVariant[],
|
||||
|
||||
27
src/app/shared/pages/route-not-found-page.component.ts
Normal file
27
src/app/shared/pages/route-not-found-page.component.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-route-not-found-page',
|
||||
template: `
|
||||
<main class="route-not-found">
|
||||
<h1>404</h1>
|
||||
<p>No encontramos la página solicitada.</p>
|
||||
</main>
|
||||
`,
|
||||
styles: `
|
||||
.route-not-found {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class RouteNotFoundPageComponent {}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user