feat: enhance product ticket selector and vertical cart card components

- Refactor ProductTicketSelectorComponent to improve variant selection logic and error handling.
- Introduce a new signal for variant attributes and manage variant loading more efficiently.
- Update the UI to reflect saving state in ProductVerticalWithCartCardComponent, preventing actions while saving.
- Adjust button text based on saving state for better user feedback.
This commit is contained in:
ncoronel
2026-08-18 10:45:30 -03:00
parent 69f3569ccf
commit 6b2f8de210
18 changed files with 644 additions and 617 deletions

View File

@@ -118,6 +118,7 @@ export interface CatalogFeaturedItemVariant {
} }
export interface CatalogVariantOptionsResponse { export interface CatalogVariantOptionsResponse {
variants: CatalogFeaturedItemVariant[];
selectors: CatalogVariantSelector[]; selectors: CatalogVariantSelector[];
selected_values: Record<string, string | string[]>; selected_values: Record<string, string | string[]>;
resolved_variant: CatalogFeaturedItemVariant | null; resolved_variant: CatalogFeaturedItemVariant | null;

View File

@@ -17,6 +17,7 @@
[layout]="categoryResults.layout" [layout]="categoryResults.layout"
[groupLayout]="paginatedLayout" [groupLayout]="paginatedLayout"
[items]="categoryResults" [items]="categoryResults"
[savingProductIds]="savingProductIds()"
(buy)="onBuyProduct($event)" (buy)="onBuyProduct($event)"
(addToCart)="onAddToCart($event)" (addToCart)="onAddToCart($event)"
(pageChange)="onPageChange($event)" (pageChange)="onPageChange($event)"

View File

@@ -9,7 +9,16 @@ import {
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { catchError, combineLatest, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs'; import {
catchError,
combineLatest,
distinctUntilChanged,
finalize,
map,
of,
switchMap,
tap,
} from 'rxjs';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
@@ -52,6 +61,7 @@ export class CategoryItemsPageComponent {
protected readonly results = signal<CategoryItemsResponse | null>(null); protected readonly results = signal<CategoryItemsResponse | null>(null);
protected readonly error = signal<string | null>(null); protected readonly error = signal<string | null>(null);
protected readonly creatingDirectPurchase = signal(false); protected readonly creatingDirectPurchase = signal(false);
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated'; protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
constructor() { constructor() {
@@ -157,14 +167,31 @@ export class CategoryItemsPageComponent {
} }
protected onAddToCart(event: ProductListCartEvent): void { protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({ const productId = event.product.id;
next: (response) => { if (this.savingProductIds().has(productId)) {
this.toastService.success(response.message || 'Producto agregado al carrito'); return;
}, }
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.'; this.setProductSaving(productId, true);
this.toastService.danger(message); this.cartService
}, .addItem(productId, event.variant ?? null, event.quantity)
.pipe(finalize(() => this.setProductSaving(productId, false)))
.subscribe({
next: (response) => {
this.toastService.success(response.message || 'Producto agregado al carrito');
},
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
this.toastService.danger(message);
},
});
}
private setProductSaving(productId: number, saving: boolean): void {
this.savingProductIds.update((current) => {
const updated = new Set(current);
saving ? updated.add(productId) : updated.delete(productId);
return updated;
}); });
} }

View File

@@ -63,7 +63,9 @@
[disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()" [disabled]="!selectedVariantAvailable() || variantLoading() || addingToCart()"
(click)="addToCart()" (click)="addToCart()"
> >
@if (variantLoading() || addingToCart()) { @if (addingToCart()) {
Guardando
} @else if (variantLoading()) {
<div class="spinner-border spinner-border-sm" role="status"></div> <div class="spinner-border spinner-border-sm" role="status"></div>
} @else { } @else {
Agregar al carrito Agregar al carrito

View File

@@ -20,6 +20,7 @@
[layout]="productLayout()" [layout]="productLayout()"
[groupLayout]="groupLayout()" [groupLayout]="groupLayout()"
[items]="displayItems()" [items]="displayItems()"
[savingProductIds]="savingProductIds()"
(buy)="onBuyProduct($event)" (buy)="onBuyProduct($event)"
(addToCart)="onAddToCart($event)" (addToCart)="onAddToCart($event)"
(pageChange)="onPageChange($event)" (pageChange)="onPageChange($event)"

View File

@@ -9,7 +9,7 @@ import {
signal, signal,
} from '@angular/core'; } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { catchError, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs'; import { catchError, distinctUntilChanged, finalize, map, of, switchMap, tap } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
@@ -58,6 +58,7 @@ export class SearchPageComponent {
protected readonly results = signal<ApiPaginatedResponse<CatalogFeaturedItem[]> | null>(null); protected readonly results = signal<ApiPaginatedResponse<CatalogFeaturedItem[]> | null>(null);
protected readonly error = signal<string | null>(null); protected readonly error = signal<string | null>(null);
protected readonly creatingDirectPurchase = signal(false); protected readonly creatingDirectPurchase = signal(false);
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly productLayout = computed<CatalogProductLayout>( protected readonly productLayout = computed<CatalogProductLayout>(
() => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image', () => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image',
@@ -189,14 +190,31 @@ export class SearchPageComponent {
} }
protected onAddToCart(event: ProductListCartEvent): void { protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({ const productId = event.product.id;
next: (response) => { if (this.savingProductIds().has(productId)) {
this.toastService.success(response.message || 'Producto agregado al carrito'); return;
}, }
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.'; this.setProductSaving(productId, true);
this.toastService.danger(message); this.cartService
}, .addItem(productId, event.variant ?? null, event.quantity)
.pipe(finalize(() => this.setProductSaving(productId, false)))
.subscribe({
next: (response) => {
this.toastService.success(response.message || 'Producto agregado al carrito');
},
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
this.toastService.danger(message);
},
});
}
private setProductSaving(productId: number, saving: boolean): void {
this.savingProductIds.update((current) => {
const updated = new Set(current);
saving ? updated.add(productId) : updated.delete(productId);
return updated;
}); });
} }

View File

@@ -31,6 +31,7 @@
[loading]="isGroupLoading(group.id)" [loading]="isGroupLoading(group.id)"
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()" [loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
[unavailableVariantIds]="unavailableVariantIds()" [unavailableVariantIds]="unavailableVariantIds()"
[savingProductIds]="savingProductIds()"
(buy)="onBuyProduct($event)" (buy)="onBuyProduct($event)"
(addToCart)="onAddToCart($event)" (addToCart)="onAddToCart($event)"
(pageChange)="onPageChange(group.id, $event)" (pageChange)="onPageChange(group.id, $event)"

View File

@@ -10,7 +10,7 @@ import {
} from '@angular/core'; } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs'; import { finalize, Subscription } from 'rxjs';
import { CartService } from '../../../../core/services/cart/cart.service'; import { CartService } from '../../../../core/services/cart/cart.service';
import { AuthService } from '../../../../core/services/auth/auth.service'; import { AuthService } from '../../../../core/services/auth/auth.service';
@@ -64,6 +64,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
protected readonly mainCarouselReady = signal(false); protected readonly mainCarouselReady = signal(false);
protected readonly creatingDirectPurchase = signal(false); protected readonly creatingDirectPurchase = signal(false);
protected readonly unavailableVariantIds = signal<ReadonlySet<number>>(new Set<number>()); protected readonly unavailableVariantIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly mainCarouselImages = computed(() => this.tenant()?.extras?.carousel ?? []); protected readonly mainCarouselImages = computed(() => this.tenant()?.extras?.carousel ?? []);
protected readonly heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null); protected readonly heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null);
protected readonly additionalInfo = computed( protected readonly additionalInfo = computed(
@@ -230,14 +231,31 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
} }
protected onAddToCart(event: ProductListCartEvent): void { protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).subscribe({ const productId = event.product.id;
next: (response) => { if (this.savingProductIds().has(productId)) {
this.toastService.success(response.message || 'Producto agregado al carrito'); return;
}, }
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.'; this.setProductSaving(productId, true);
this.toastService.danger(message); this.cartService
}, .addItem(productId, event.variant ?? null, event.quantity)
.pipe(finalize(() => this.setProductSaving(productId, false)))
.subscribe({
next: (response) => {
this.toastService.success(response.message || 'Producto agregado al carrito');
},
error: (error: HttpErrorResponse) => {
const message = error.error?.message || 'No se pudo agregar el producto al carrito.';
this.toastService.danger(message);
},
});
}
private setProductSaving(productId: number, saving: boolean): void {
this.savingProductIds.update((current) => {
const updated = new Set(current);
saving ? updated.add(productId) : updated.delete(productId);
return updated;
}); });
} }

View File

@@ -13,6 +13,7 @@
[description]="item.descripcion ?? ''" [description]="item.descripcion ?? ''"
[price]="price(item)" [price]="price(item)"
[variants]="item.variants ?? []" [variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitRowBuy(item, $event)" (buy)="emitRowBuy(item, $event)"
(addToCart)="emitRowCart(item, $event)" (addToCart)="emitRowCart(item, $event)"
/> />
@@ -23,6 +24,7 @@
[description]="item.descripcion ?? ''" [description]="item.descripcion ?? ''"
[price]="price(item)" [price]="price(item)"
[variants]="item.variants ?? []" [variants]="item.variants ?? []"
[saving]="savingProductIds().has(item.id)"
(buy)="emitColumnBuy(item, $event)" (buy)="emitColumnBuy(item, $event)"
(addToCart)="emitColumnCart(item, $event)" (addToCart)="emitColumnCart(item, $event)"
/> />

View File

@@ -69,6 +69,7 @@ export class ProductListComponent {
readonly loading = input(false); readonly loading = input(false);
readonly loadImages = input(true); readonly loadImages = input(true);
readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>()); readonly unavailableVariantIds = input<ReadonlySet<number>>(new Set<number>());
readonly savingProductIds = input<ReadonlySet<number>>(new Set<number>());
readonly buy = output<ProductListBuyEvent>(); readonly buy = output<ProductListBuyEvent>();
readonly addToCart = output<ProductListCartEvent>(); readonly addToCart = output<ProductListCartEvent>();

View File

@@ -34,7 +34,9 @@
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button> <app-button variant="primary" (click)="onBuy()"> Comprar </app-button>
</div> </div>
<div class="product-row-card__btn-wrapper"> <div class="product-row-card__btn-wrapper">
<app-button variant="secondary" (click)="onAddToCart()"> Agregar al carrito </app-button> <app-button variant="secondary" [disabled]="saving()" (click)="onAddToCart()">
{{ saving() ? 'Guardando' : 'Agregar al carrito' }}
</app-button>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -27,6 +27,7 @@ export class ProductRowCardComponent {
readonly description = input<string>(''); readonly description = input<string>('');
readonly price = input<number>(0); readonly price = input<number>(0);
readonly variants = input<Variant[]>([]); readonly variants = input<Variant[]>([]);
readonly saving = input(false);
// Internal state models // Internal state models
readonly quantity = model<number>(1); readonly quantity = model<number>(1);
@@ -51,6 +52,10 @@ export class ProductRowCardComponent {
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice())); readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected onAddToCart(): void { protected onAddToCart(): void {
if (this.saving()) {
return;
}
this.addToCart.emit({ this.addToCart.emit({
quantity: this.quantity(), quantity: this.quantity(),
variant: this.selectedVariant(), variant: this.selectedVariant(),

View File

@@ -22,26 +22,38 @@
<div class="ticket-selector__rows"> <div class="ticket-selector__rows">
@for (row of rows(); track row.id) { @for (row of rows(); track row.id) {
<div class="ticket-selector__row"> <div class="ticket-selector__row">
<div class="ticket-selector__fields variant-selector"> <div class="ticket-selector__row-content">
@for (selector of row.selectors; track selector.key) { <div class="ticket-selector__fields variant-selector">
<select @for (selector of row.selectors; track selector.key) {
class="form-select variant-selector__select" <select
[attr.aria-label]="selector.label" class="form-select variant-selector__select"
[disabled]="rowDisabled(row)" [attr.aria-label]="selector.label"
(change)="onSelectionKeyChange(row.id, selector, $any($event.target).value)" [disabled]="rowDisabled(row) || !selector.enabled"
> (change)="onSelectionKeyChange(row.id, selector, $any($event.target).value)"
<option value="" disabled [selected]="selectedOptionKey(row, selector.key) === ''"> >
Seleccioná {{ selector.label }}
</option>
@for (option of selector.options; track $index) {
<option <option
[value]="optionKey(option)" value=""
[selected]="optionKey(option) === selectedOptionKey(row, selector.key)" disabled
[selected]="selectedOptionKey(row, selector.key) === ''"
> >
{{ optionLabel(option) }} Seleccioná {{ selector.label }}
</option> </option>
} @for (option of selector.options; track $index) {
</select> <option
[value]="optionKey(option)"
[selected]="optionKey(option) === selectedOptionKey(row, selector.key)"
>
{{ optionLabel(option) }}
</option>
}
</select>
}
</div>
@if (row.status === 'reserving') {
<span class="ticket-selector__row-status" role="status" aria-live="polite">
Guardando...
</span>
} }
</div> </div>
<app-icon-button <app-icon-button

View File

@@ -60,10 +60,14 @@
&__row { &__row {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr) auto; grid-template-columns: minmax(0, 1fr) auto;
align-items: end; align-items: start;
gap: 0.5rem; gap: 0.5rem;
} }
&__row-content {
min-width: 0;
}
&__fields { &__fields {
min-width: 0; min-width: 0;
display: grid; display: grid;
@@ -96,6 +100,25 @@
} }
} }
&__row-status {
display: inline-flex;
align-items: center;
gap: 0.4rem;
margin-top: 0.35rem;
color: #777;
font-size: 13px;
&::before {
width: 0.8rem;
height: 0.8rem;
border: 2px solid currentcolor;
border-right-color: transparent;
border-radius: 50%;
animation: ticket-selector-spin 0.7s linear infinite;
content: '';
}
}
&__empty { &__empty {
margin: 0; margin: 0;
color: #777; color: #777;
@@ -115,6 +138,18 @@
} }
} }
@keyframes ticket-selector-spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.ticket-selector__row-status::before {
animation: none;
}
}
@media (max-width: 767.98px) { @media (max-width: 767.98px) {
.ticket-selector { .ticket-selector {
&__header { &__header {

View File

@@ -3,7 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http';
import { signal } from '@angular/core'; import { signal } from '@angular/core';
import { TestBed, getTestBed } from '@angular/core/testing'; import { TestBed, getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { of, throwError } from 'rxjs'; import { of, Subject, throwError } from 'rxjs';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { CartService } from '../../../core/services/cart/cart.service'; import { CartService } from '../../../core/services/cart/cart.service';
@@ -12,6 +12,64 @@ import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service'; import { ToastService } from '../../../core/services/toast.service';
import { ProductTicketSelectorComponent } from './product-ticket-selector.component'; import { ProductTicketSelectorComponent } from './product-ticket-selector.component';
const attributes = [
{ key: 'tipo', label: 'Tipo' },
{ key: 'sector', label: 'Sector' },
{ key: 'fila', label: 'Fila' },
{ key: 'asiento', label: 'Asiento' },
];
function variant(id: number, tipo: string, sector: string, fila: string, asiento: string) {
return {
id,
precio: '10000.00',
stock_tecnico: 1,
values: { tipo, sector, fila, asiento },
};
}
function mapResponse(variants: ReturnType<typeof variant>[]) {
return {
variants,
selectors: attributes.map(({ key, label }, index) => ({
key,
label,
options: index === 0 ? ['general'] : [],
enabled: index === 0,
})),
selected_values: {},
resolved_variant: null,
valid: variants.length > 0,
available_variant_count: variants.length,
matching_variant_count: variants.length,
price_range: { minimum: '10000.00', maximum: '10000.00' },
};
}
function cartWith(item: ReturnType<typeof variant> | null = null) {
return {
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: item === null ? '0.00' : '10000.00',
items:
item === null
? []
: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: item.id,
nombre: 'Entrada',
imagen: null,
variant: item,
},
],
};
}
describe('ProductTicketSelectorComponent', () => { describe('ProductTicketSelectorComponent', () => {
beforeAll(() => { beforeAll(() => {
try { try {
@@ -23,234 +81,26 @@ describe('ProductTicketSelectorComponent', () => {
afterEach(() => TestBed.resetTestingModule()); afterEach(() => TestBed.resetTestingModule());
it('checks partial selections and reserves the resolved variant in the cart', async () => { async function createComponent({
const openConfirmDelete = vi.fn().mockReturnValue(of(true)); maps,
const removeItem = vi.fn().mockReturnValue( addItem = vi.fn(),
of({ cartState = signal(cartWith()),
data: { toastDanger = vi.fn(),
id: 10, }: {
tenant_codigo: 'demo', maps: ReturnType<typeof mapResponse>[];
status: 'active', addItem?: ReturnType<typeof vi.fn>;
subtotal: '0.00', cartState?: ReturnType<typeof signal<ReturnType<typeof cartWith>>>;
items: [], toastDanger?: ReturnType<typeof vi.fn>;
}, }) {
}), const getVariantOptions = vi.fn();
); maps.forEach((response) => getVariantOptions.mockReturnValueOnce(of(response)));
const resolvedVariant = { const catalogService = { withoutLoading: vi.fn(), getVariantOptions };
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: { sector: { value: 'a', label: 'Sector A' }, seat: '1' },
};
const summary = {
valid: true,
available_variant_count: 1,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
};
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi
.fn()
.mockReturnValueOnce(
of({
...summary,
selectors: [
{
key: 'sector',
label: 'Sector',
options: [{ value: 'a', label: 'Sector A' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: false },
],
selected_values: {},
resolved_variant: null,
}),
)
.mockReturnValueOnce(
of({
...summary,
selectors: [
{
key: 'sector',
label: 'Sector',
options: [{ value: 'a', label: 'Sector A' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: true },
],
selected_values: { sector: 'a' },
resolved_variant: null,
}),
)
.mockReturnValueOnce(
of({
...summary,
selectors: [],
selected_values: { sector: 'a', seat: '1' },
resolved_variant: resolvedVariant,
}),
),
};
const cartService = {
cart: signal(null).asReadonly(),
withoutLoading: vi.fn(),
addItem: vi.fn().mockReturnValue(
of({
data: {
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '10000.00',
items: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: 401,
nombre: 'Entrada',
imagen: null,
variant: resolvedVariant,
},
],
},
}),
),
removeItem,
};
catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService);
await TestBed.configureTestingModule({
imports: [ProductTicketSelectorComponent],
providers: [
{ provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService },
{ provide: ModalService, useValue: { openConfirmDelete } },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
expect(catalogService.getVariantOptions).toHaveBeenCalledTimes(1);
expect(catalogService.withoutLoading).toHaveBeenCalled();
expect(
Array.from<HTMLSelectElement>(fixture.nativeElement.querySelectorAll('select')).every(
(select) => !select.disabled,
),
).toBe(true);
fixture.componentInstance['onSelectionChange'](1, 'sector', {
value: 'a',
label: 'Sector A',
});
expect(catalogService.getVariantOptions).toHaveBeenLastCalledWith(7, {
selected_values: { sector: 'a' },
cart_item_id: null,
});
expect(fixture.componentInstance['rows']()[0].status).toBe('selecting');
fixture.componentInstance['onSelectionChange'](1, 'seat', '1');
expect(cartService.addItem).toHaveBeenCalledWith(7, 401, 1);
expect(cartService.withoutLoading).toHaveBeenCalled();
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
cartItemId: 25,
status: 'reserved',
});
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.ticket-selector__row-status')).toBeNull();
expect(fixture.nativeElement.querySelector('.ticket-selector__row-error')).toBeNull();
const deleteButton = fixture.nativeElement.querySelector(
'app-icon-button button',
) as HTMLButtonElement;
expect(deleteButton.classList.contains('icon-btn--bordered')).toBe(true);
deleteButton.click();
expect(openConfirmDelete).toHaveBeenCalledWith({
title: 'Eliminar entrada',
content:
'Se eliminará esta entrada de “Entrada”. Si ya estaba reservada, se liberará del carrito.',
confirmLabel: 'Sí, eliminar',
cancelLabel: 'Cancelar',
size: 'md',
});
expect(removeItem).toHaveBeenCalledWith(25);
expect(fixture.componentInstance['rows']()).toHaveLength(0);
});
it('restores selections that are already reserved in the cart', async () => {
const cartState = signal({
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '10000.00',
items: [
{
id: 25,
cantidad: 1,
precio_unitario: '10000.00',
catalog_item_id: 7,
variant_id: 401,
nombre: 'Entrada',
imagen: null,
variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: {
sector: { value: 'a', label: 'Sector A' },
seat: '1',
},
},
},
],
});
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi.fn().mockReturnValue(
of({
valid: true,
available_variant_count: 1,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
selectors: [
{
key: 'sector',
label: 'Sector',
options: [
{ value: 'a', label: 'Sector A' },
{ value: 'b', label: 'Sector B' },
],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1', '2'], enabled: true },
],
selected_values: { sector: 'b', seat: '2' },
resolved_variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: { sector: { value: 'b', label: 'Sector B' }, seat: '2' },
},
}),
),
};
const cartService = { const cartService = {
cart: cartState.asReadonly(), cart: cartState.asReadonly(),
withoutLoading: vi.fn(), withoutLoading: vi.fn(),
addItem: vi.fn(), addItem,
updateItemVariant: vi.fn(), updateItemVariant: vi.fn(),
removeItem: vi.fn().mockReturnValue(of({ data: cartWith() })),
}; };
catalogService.withoutLoading.mockReturnValue(catalogService); catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService); cartService.withoutLoading.mockReturnValue(cartService);
@@ -260,8 +110,14 @@ describe('ProductTicketSelectorComponent', () => {
providers: [ providers: [
{ provide: CatalogService, useValue: catalogService }, { provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService }, { provide: CartService, useValue: cartService },
{
provide: ModalService,
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
},
{ provide: ToastService, useValue: { danger: toastDanger } },
], ],
}).compileComponents(); }).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent); const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7); fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada'); fixture.componentRef.setInput('title', 'Entrada');
@@ -269,162 +125,157 @@ describe('ProductTicketSelectorComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
expect(catalogService.getVariantOptions).toHaveBeenCalledWith(7, { return { fixture, getVariantOptions, cartService, toastDanger };
selected_values: {}, }
cart_item_id: 25,
});
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
cartItemId: 25,
selectedValues: { sector: 'b', seat: '2' },
status: 'reserved',
});
expect(cartService.addItem).not.toHaveBeenCalled();
expect(cartService.updateItemVariant).not.toHaveBeenCalled();
const selects = Array.from<HTMLSelectElement>(fixture.nativeElement.querySelectorAll('select'));
expect(selects.map((select) => select.selectedOptions[0]?.textContent?.trim())).toEqual([
'Sector B',
'2',
]);
});
it('keeps the reserved selection and shows a toast when a variant change cannot be completed', async () => { it('loads one map, recalculates the cascade locally and reserves only after the last select', async () => {
const cartState = signal({ const selectedVariant = variant(401, 'general', 'A', '1', '1');
id: 10, const variants = [
tenant_codigo: 'demo', selectedVariant,
status: 'active', variant(402, 'general', 'A', '1', '2'),
subtotal: '10000.00', variant(403, 'general', 'B', '2', '1'),
items: [ ];
{ const addItem = vi.fn().mockReturnValue(of({ data: cartWith(selectedVariant) }));
id: 25, const { fixture, getVariantOptions } = await createComponent({
cantidad: 1, maps: [mapResponse(variants)],
precio_unitario: '10000.00', addItem,
catalog_item_id: 7,
variant_id: 401,
nombre: 'Entrada',
imagen: null,
variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 0,
values: { seat: '1' },
},
},
],
}); });
const selector = { const component = fixture.componentInstance;
key: 'seat',
label: 'Asiento', expect(getVariantOptions).toHaveBeenCalledTimes(1);
expect(getVariantOptions).toHaveBeenCalledWith(7, { selected_values: {} });
component['onSelectionChange'](1, 'tipo', 'general');
component['onSelectionChange'](1, 'sector', 'A');
component['onSelectionChange'](1, 'fila', '1');
expect(getVariantOptions).toHaveBeenCalledTimes(1);
expect(addItem).not.toHaveBeenCalled();
expect(component['rows']()[0].selectors[3]).toMatchObject({
key: 'asiento',
options: ['1', '2'], options: ['1', '2'],
enabled: true, enabled: true,
}; });
const summary = {
valid: true, component['onSelectionChange'](1, 'asiento', '1');
available_variant_count: 2,
matching_variant_count: 1, expect(getVariantOptions).toHaveBeenCalledTimes(1);
price_range: { minimum: '10000.00', maximum: '10000.00' }, expect(addItem).toHaveBeenCalledWith(7, 401, 1);
selectors: [selector], expect(component['rows']()[0]).toMatchObject({
}; variantId: 401,
const catalogService = { reservedVariantId: 401,
withoutLoading: vi.fn(), status: 'reserved',
getVariantOptions: vi });
.fn() });
.mockReturnValueOnce(
of({ it('shows a saving status while the selected seat is being reserved', async () => {
...summary, const selectedVariant = variant(401, 'general', 'A', '1', '1');
selected_values: { seat: '1' }, const reservation = new Subject<{ data: ReturnType<typeof cartWith> }>();
resolved_variant: { const addItem = vi.fn().mockReturnValue(reservation);
id: 401, const { fixture } = await createComponent({
precio: '10000.00', maps: [mapResponse([selectedVariant])],
stock_tecnico: 0, addItem,
values: { seat: '1' }, });
}, const component = fixture.componentInstance;
component['onSelectionChange'](1, 'tipo', 'general');
component['onSelectionChange'](1, 'sector', 'A');
component['onSelectionChange'](1, 'fila', '1');
component['onSelectionChange'](1, 'asiento', '1');
fixture.detectChanges();
const savingStatus = fixture.nativeElement.querySelector(
'.ticket-selector__row-status',
) as HTMLElement | null;
expect(savingStatus?.textContent?.trim()).toBe('Guardando...');
expect(savingStatus?.getAttribute('role')).toBe('status');
reservation.next({ data: cartWith(selectedVariant) });
reservation.complete();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.ticket-selector__row-status')).toBeNull();
});
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');
const message = 'El asiento ya no está disponible.';
const addItem = vi.fn().mockReturnValue(
throwError(
() =>
new HttpErrorResponse({
status: 422,
error: { message },
}), }),
)
.mockReturnValueOnce(
of({
...summary,
selected_values: { seat: '2' },
resolved_variant: {
id: 402,
precio: '10000.00',
stock_tecnico: 1,
values: { seat: '2' },
},
}),
),
};
const errorMessage = 'La entrada seleccionada ya no está disponible.';
const cartService = {
cart: cartState.asReadonly(),
withoutLoading: vi.fn(),
updateItemVariant: vi.fn().mockReturnValue(
throwError(
() =>
new HttpErrorResponse({
status: 422,
error: { message: errorMessage },
}),
),
), ),
};
const toastService = { danger: vi.fn() };
catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService);
await TestBed.configureTestingModule({
imports: [ProductTicketSelectorComponent],
providers: [
{ provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService },
{ provide: ToastService, useValue: toastService },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
fixture.detectChanges();
await fixture.whenStable();
fixture.componentInstance['onSelectionChange'](1, 'seat', '2');
fixture.detectChanges();
expect(cartService.updateItemVariant).toHaveBeenCalledWith(25, 1, 402);
expect(toastService.danger).toHaveBeenCalledWith(errorMessage);
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
selectedValues: { seat: '1' },
status: 'reserved',
error: null,
});
const select = fixture.nativeElement.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe(JSON.stringify('1'));
const unavailableMessage = 'La combinación seleccionada ya no está disponible.';
catalogService.getVariantOptions.mockReturnValueOnce(
of({
...summary,
valid: false,
matching_variant_count: 0,
selected_values: {},
resolved_variant: null,
}),
); );
const { fixture, getVariantOptions, toastDanger } = await createComponent({
maps: [mapResponse([failed, alternative]), mapResponse([alternative])],
addItem,
});
const component = fixture.componentInstance;
fixture.componentInstance['onSelectionChange'](1, 'seat', '2'); component['onSelectionChange'](1, 'tipo', 'general');
fixture.detectChanges(); component['onSelectionChange'](1, 'sector', 'A');
component['onSelectionChange'](1, 'fila', '1');
component['onSelectionChange'](1, 'asiento', '1');
expect(cartService.updateItemVariant).toHaveBeenCalledTimes(1); expect(getVariantOptions).toHaveBeenCalledTimes(2);
expect(toastService.danger).toHaveBeenLastCalledWith(unavailableMessage); expect(component['rows']()[0]).toMatchObject({
selectedValues: { tipo: 'general', sector: 'A', fila: '1' },
variantId: null,
status: 'selecting',
error: message,
});
expect(component['rows']()[0].selectors[3].options).toEqual(['2']);
expect(toastDanger).toHaveBeenCalledWith(message);
});
it('also clears the row when the refreshed map has no seats for that row', async () => {
const failed = variant(401, 'general', 'A', '1', '1');
const otherRow = variant(402, 'general', 'A', '2', '1');
const addItem = vi
.fn()
.mockReturnValue(
throwError(() => new HttpErrorResponse({ status: 422, error: { message: 'Sin stock.' } })),
);
const { fixture } = await createComponent({
maps: [mapResponse([failed, otherRow]), mapResponse([otherRow])],
addItem,
});
const component = fixture.componentInstance;
component['onSelectionChange'](1, 'tipo', 'general');
component['onSelectionChange'](1, 'sector', 'A');
component['onSelectionChange'](1, 'fila', '1');
component['onSelectionChange'](1, 'asiento', '1');
expect(component['rows']()[0].selectedValues).toEqual({ tipo: 'general', sector: 'A' });
expect(component['rows']()[0].selectors[2]).toMatchObject({
key: 'fila',
options: ['2'],
enabled: true,
});
expect(component['rows']()[0].selectors[3].enabled).toBe(false);
});
it('restores a variant already reserved in the cart without another options request', async () => {
const reserved = variant(401, 'general', 'A', '1', '1');
const cartState = signal(cartWith(reserved));
const { fixture, getVariantOptions, cartService } = await createComponent({
maps: [mapResponse([])],
cartState,
});
expect(getVariantOptions).toHaveBeenCalledTimes(1);
expect(cartService.updateItemVariant).not.toHaveBeenCalled();
expect(fixture.componentInstance['rows']()[0]).toMatchObject({ expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401, variantId: 401,
reservedVariantId: 401, reservedVariantId: 401,
selectedValues: { seat: '1' }, cartItemId: 25,
selectedValues: { tipo: 'general', sector: 'A', fila: '1', asiento: '1' },
status: 'reserved', status: 'reserved',
error: null,
}); });
expect(select.value).toBe(JSON.stringify('1'));
}); });
}); });

View File

@@ -15,16 +15,17 @@ import {
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { CartService } from '../../../core/services/cart/cart.service';
import { CartItem } from '../../../core/services/cart/cart.interface'; import { CartItem } from '../../../core/services/cart/cart.interface';
import { ModalService } from '../../../core/services/modal.service'; import { CartService } from '../../../core/services/cart/cart.service';
import { ToastService } from '../../../core/services/toast.service';
import { import {
CatalogFeaturedItemVariant,
CatalogVariantOptionsResponse, CatalogVariantOptionsResponse,
CatalogVariantSelector, CatalogVariantSelector,
CatalogVariantValue, CatalogVariantValue,
} from '../../../core/services/catalog/catalog.interface'; } from '../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../core/services/catalog/catalog.service'; 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 { ButtonComponent } from '../button/button.component';
import { IconButtonComponent } from '../icon-button/icon-button.component'; import { IconButtonComponent } from '../icon-button/icon-button.component';
@@ -36,6 +37,11 @@ type TicketSelectionStatus =
| 'removing' | 'removing'
| 'error'; | 'error';
interface VariantAttribute {
key: string;
label: string;
}
interface TicketSelectionRow { interface TicketSelectionRow {
id: number; id: number;
variantId: number | null; variantId: number | null;
@@ -44,7 +50,6 @@ interface TicketSelectionRow {
selectedValues: Record<string, string | string[]>; selectedValues: Record<string, string | string[]>;
selectors: CatalogVariantSelector[]; selectors: CatalogVariantSelector[];
reservedSelectedValues: Record<string, string | string[]>; reservedSelectedValues: Record<string, string | string[]>;
reservedSelectors: CatalogVariantSelector[];
status: TicketSelectionStatus; status: TicketSelectionStatus;
error: string | null; error: string | null;
} }
@@ -62,9 +67,12 @@ export class ProductTicketSelectorComponent {
private readonly modalService = inject(ModalService); private readonly modalService = inject(ModalService);
private readonly toastService = inject(ToastService); private readonly toastService = inject(ToastService);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly optionRequests = new Map<number, Subscription>();
private readonly reservationRequests = new Map<number, Subscription>(); private readonly reservationRequests = new Map<number, Subscription>();
private readonly viewReady = signal(false); private readonly viewReady = signal(false);
private readonly mapReady = signal(false);
private readonly variants = signal<CatalogFeaturedItemVariant[]>([]);
private readonly attributes = signal<VariantAttribute[]>([]);
private mapRequest: Subscription | null = null;
readonly productId = input.required<number>(); readonly productId = input.required<number>();
readonly title = input.required<string>(); readonly title = input.required<string>();
@@ -76,10 +84,17 @@ export class ProductTicketSelectorComponent {
readonly buy = output<number[]>(); readonly buy = output<number[]>();
protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]); protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]);
protected readonly availableVariantCount = signal(0);
private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null); private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null);
private nextRowId = 2; private nextRowId = 2;
protected readonly availableVariantCount = computed(() => {
const reservedIds = new Set(
this.rows().flatMap(({ reservedVariantId }) =>
reservedVariantId === null ? [] : [reservedVariantId],
),
);
return this.variants().filter(({ id }) => !reservedIds.has(id)).length;
});
protected readonly hasSelection = computed( protected readonly hasSelection = computed(
() => () =>
this.rows().length > 0 && this.rows().length > 0 &&
@@ -100,7 +115,6 @@ export class ProductTicketSelectorComponent {
const range = this.remotePriceRange(); const range = this.remotePriceRange();
const minimum = range?.minimum ?? this.price(); const minimum = range?.minimum ?? this.price();
const maximum = range?.maximum ?? this.price(); const maximum = range?.maximum ?? this.price();
return { return {
minimum: this.formatCurrency(minimum), minimum: this.formatCurrency(minimum),
maximum: this.formatCurrency(maximum), maximum: this.formatCurrency(maximum),
@@ -111,24 +125,22 @@ export class ProductTicketSelectorComponent {
constructor() { constructor() {
effect(() => { effect(() => {
const viewReady = this.viewReady(); const viewReady = this.viewReady();
const mapReady = this.mapReady();
const cart = this.cartService.cart?.() ?? null; const cart = this.cartService.cart?.() ?? null;
if (!viewReady) return; if (!viewReady) return;
untracked(() => { untracked(() => {
if (cart === null) { if (!mapReady) {
this.ensureEmptyRowLoaded(); this.loadVariantMap();
return; return;
} }
this.synchronizeWithCart(cart?.items ?? []);
this.synchronizeWithCart(cart.items);
}); });
}); });
afterNextRender(() => this.viewReady.set(true)); afterNextRender(() => this.viewReady.set(true));
this.destroyRef.onDestroy(() => { this.destroyRef.onDestroy(() => {
this.optionRequests.forEach((request) => request.unsubscribe()); this.mapRequest?.unsubscribe();
this.reservationRequests.forEach((request) => request.unsubscribe()); this.reservationRequests.forEach((request) => request.unsubscribe());
}); });
} }
@@ -137,24 +149,20 @@ export class ProductTicketSelectorComponent {
const variantIds = this.rows().flatMap((row) => const variantIds = this.rows().flatMap((row) =>
row.reservedVariantId === null ? [] : [row.reservedVariantId], row.reservedVariantId === null ? [] : [row.reservedVariantId],
); );
if (this.hasSelection() && variantIds.length > 0) this.buy.emit(variantIds);
if (this.hasSelection() && variantIds.length > 0) {
this.buy.emit(variantIds);
}
} }
protected addRow(): void { protected addRow(): void {
if (!this.canAddRow()) return; if (!this.canAddRow()) return;
const row = this.createRow(this.nextRowId++); const row = this.createRow(this.nextRowId++);
row.status = 'selecting';
row.selectors = this.buildSelectors(row.selectedValues, row);
this.rows.update((rows) => [...rows, row]); this.rows.update((rows) => [...rows, row]);
this.loadOptions(row.id, {});
} }
protected removeRow(rowId: number): void { protected removeRow(rowId: number): void {
const row = this.findRow(rowId); const row = this.findRow(rowId);
if (!row || this.isBusy(row)) return; if (!row || this.isBusy(row)) return;
this.modalService this.modalService
.openConfirmDelete({ .openConfirmDelete({
title: 'Eliminar entrada', title: 'Eliminar entrada',
@@ -170,32 +178,24 @@ export class ProductTicketSelectorComponent {
} }
private confirmRemoveRow(row: TicketSelectionRow): void { private confirmRemoveRow(row: TicketSelectionRow): void {
const rowId = row.id;
this.optionRequests.get(rowId)?.unsubscribe();
if (row.cartItemId === null) { if (row.cartItemId === null) {
this.deleteRow(rowId); this.deleteRow(row.id);
return; return;
} }
this.patchRow(row.id, { status: 'removing', error: null });
this.patchRow(rowId, { status: 'removing', error: null });
const request = this.cartService const request = this.cartService
.withoutLoading() .withoutLoading()
.removeItem(row.cartItemId) .removeItem(row.cartItemId)
.subscribe({ .subscribe({
next: () => { next: () => this.deleteRow(row.id),
this.availableVariantCount.update((count) => count + 1);
this.deleteRow(rowId);
},
error: (error: HttpErrorResponse) => { error: (error: HttpErrorResponse) => {
this.patchRow(rowId, { this.patchRow(row.id, {
status: 'reserved', status: 'reserved',
error: this.errorMessage(error, 'No se pudo liberar la entrada.'), error: this.errorMessage(error, 'No se pudo liberar la entrada.'),
}); });
}, },
}); });
this.reservationRequests.set(rowId, request); this.reservationRequests.set(row.id, request);
} }
protected onSelectionChange( protected onSelectionChange(
@@ -205,18 +205,25 @@ export class ProductTicketSelectorComponent {
): void { ): void {
const row = this.findRow(rowId); const row = this.findRow(rowId);
if (!row || this.isBusy(row)) return; if (!row || this.isBusy(row)) return;
const selectorIndex = this.attributes().findIndex(({ key }) => key === selectorKey);
if (selectorIndex < 0) return;
const selectedValues = { ...row.selectedValues }; const selectedValues = { ...row.selectedValues };
if (value === null) delete selectedValues[selectorKey]; if (value === null) delete selectedValues[selectorKey];
else selectedValues[selectorKey] = this.normalizeValue(value); else selectedValues[selectorKey] = this.normalizeValue(value);
this.attributes()
.slice(selectorIndex + 1)
.forEach(({ key }) => delete selectedValues[key]);
const preservesReservedSelection = const variant = this.resolveVariant(row, selectedValues);
row.reservedVariantId !== null && this.patchRow(rowId, {
row.selectors.length > 0 && variantId: variant?.id ?? null,
row.selectors.every(({ key }) => key in selectedValues); selectedValues,
selectors: this.buildSelectors(selectedValues, row),
this.loadOptions(rowId, selectedValues, preservesReservedSelection); status: 'selecting',
error: null,
});
if (variant !== null) this.reserveRow(rowId, variant.id, selectedValues);
} }
protected optionLabel(value: CatalogVariantValue): string { protected optionLabel(value: CatalogVariantValue): string {
@@ -234,7 +241,6 @@ export class ProductTicketSelectorComponent {
protected selectedOptionKey(row: TicketSelectionRow, key: string): string { protected selectedOptionKey(row: TicketSelectionRow, key: string): string {
const selectedOption = this.selectedOption(row, key); const selectedOption = this.selectedOption(row, key);
return selectedOption === null ? '' : this.valueKey(selectedOption); return selectedOption === null ? '' : this.valueKey(selectedOption);
} }
@@ -245,7 +251,6 @@ export class ProductTicketSelectorComponent {
): void { ): void {
const selectedOption = const selectedOption =
selector.options.find((option) => this.valueKey(option) === selectedKey) ?? null; selector.options.find((option) => this.valueKey(option) === selectedKey) ?? null;
this.onSelectionChange(rowId, selector.key, selectedOption); this.onSelectionChange(rowId, selector.key, selectedOption);
} }
@@ -253,111 +258,130 @@ export class ProductTicketSelectorComponent {
return this.disabled() || this.isBusy(row); return this.disabled() || this.isBusy(row);
} }
private loadOptions( private loadVariantMap(
rowId: number, onLoaded?: () => void,
selectedValues: Record<string, string | string[]>, onError?: (error: HttpErrorResponse) => void,
preserveReservedSelection = false,
): void { ): void {
const row = this.findRow(rowId); if (this.mapRequest !== null && !onLoaded) return;
if (!row) return; this.mapRequest?.unsubscribe();
this.optionRequests.get(rowId)?.unsubscribe();
this.patchRow(rowId, {
selectedValues: preserveReservedSelection ? row.reservedSelectedValues : selectedValues,
status: 'checking',
error: null,
});
const request = this.catalogService const request = this.catalogService
.withoutLoading() .withoutLoading()
.getVariantOptions(this.productId(), { .getVariantOptions(this.productId(), { selected_values: {} })
selected_values: selectedValues,
cart_item_id: row.cartItemId,
})
.subscribe({ .subscribe({
next: (response) => { next: (response) => {
this.applySummary(response, row); this.applyVariantMap(response);
this.mapReady.set(true);
if (!response.valid) { this.mapRequest = null;
if (row.reservedVariantId !== null) { onLoaded?.();
this.restoreReservedRowAfterError(
rowId,
row,
'La combinación seleccionada ya no está disponible.',
);
return;
}
this.patchRow(rowId, {
variantId: null,
selectedValues: {},
selectors: response.selectors,
status: response.available_variant_count === 0 ? 'selecting' : 'error',
error:
response.available_variant_count === 0
? null
: 'La combinación seleccionada ya no está disponible.',
});
return;
}
this.patchRow(rowId, {
variantId: response.resolved_variant?.id ?? null,
selectedValues: preserveReservedSelection
? row.reservedSelectedValues
: response.selected_values,
selectors: preserveReservedSelection ? row.reservedSelectors : response.selectors,
status: 'selecting',
error: null,
});
if (response.resolved_variant !== null) {
if (row.cartItemId !== null && row.reservedVariantId === response.resolved_variant.id) {
this.patchRow(rowId, {
reservedSelectedValues: response.selected_values,
reservedSelectors: response.selectors,
status: 'reserved',
});
} else {
this.reserveRow(
rowId,
response.resolved_variant.id,
response.selected_values,
response.selectors,
);
}
}
}, },
error: (error: HttpErrorResponse) => { error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.'); this.mapRequest = null;
if (onError) {
if (row.reservedVariantId !== null) { onError(error);
this.restoreReservedRowAfterError(rowId, row, message);
return; return;
} }
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.');
this.patchRow(rowId, { status: 'error', error: message }); this.rows.update((rows) =>
rows.map((row) => ({ ...row, status: 'error', error: message })),
);
this.toastService.danger(message); this.toastService.danger(message);
}, },
}); });
this.optionRequests.set(rowId, request); this.mapRequest = request;
}
private applyVariantMap(response: CatalogVariantOptionsResponse): void {
this.variants.set(response.variants);
this.attributes.set(response.selectors.map(({ key, label }) => ({ key, label })));
this.remotePriceRange.set({
minimum: Number(response.price_range.minimum),
maximum: Number(response.price_range.maximum),
});
}
private buildSelectors(
selectedValues: Record<string, string | string[]>,
row: TicketSelectionRow,
variants = this.availableVariantsFor(row),
): CatalogVariantSelector[] {
return this.attributes().map(({ key, label }, index, attributes) => {
const previousKeys = attributes.slice(0, index).map((attribute) => attribute.key);
const compatibleVariants = variants.filter((variant) =>
previousKeys.every(
(previousKey) =>
previousKey in selectedValues &&
this.valueKey(variant.values[previousKey]) ===
this.valueKey(selectedValues[previousKey]),
),
);
return {
key,
label,
options: this.uniqueValues(compatibleVariants.map((variant) => variant.values[key])),
enabled: index === 0 || previousKeys.every((previousKey) => previousKey in selectedValues),
};
});
}
private resolveVariant(
row: TicketSelectionRow,
selectedValues: Record<string, string | string[]>,
): CatalogFeaturedItemVariant | null {
const attributes = this.attributes();
if (attributes.length === 0 || attributes.some(({ key }) => !(key in selectedValues)))
return null;
const matches = this.availableVariantsFor(row).filter((variant) =>
attributes.every(
({ key }) => this.valueKey(variant.values[key]) === this.valueKey(selectedValues[key]),
),
);
return matches.length === 1 ? matches[0] : null;
}
private availableVariantsFor(row: TicketSelectionRow): CatalogFeaturedItemVariant[] {
const reservedByOtherRows = new Set(
this.rows().flatMap((candidate) =>
candidate.id !== row.id && candidate.reservedVariantId !== null
? [candidate.reservedVariantId]
: [],
),
);
const variants = [...this.variants()];
const reservedVariant = this.reservedVariantData(row);
if (reservedVariant !== null && !variants.some(({ id }) => id === reservedVariant.id)) {
variants.push(reservedVariant);
}
return variants.filter(({ id }) => !reservedByOtherRows.has(id));
}
private reservedVariantData(row: TicketSelectionRow): CatalogFeaturedItemVariant | null {
if (row.cartItemId === null || row.reservedVariantId === null) return null;
const item = this.cartService.cart?.()?.items.find(({ id }) => id === row.cartItemId);
if (!item?.variant) return null;
return {
id: item.variant.id,
precio: item.variant.precio,
stock_tecnico: item.variant.stock_tecnico,
values: item.variant.values,
};
}
private uniqueValues(values: Array<CatalogVariantValue | undefined>): CatalogVariantValue[] {
const unique = new Map<string, CatalogVariantValue>();
values.forEach((value) => {
if (value !== undefined) unique.set(this.valueKey(value), value);
});
return [...unique.values()];
} }
private reserveRow( private reserveRow(
rowId: number, rowId: number,
variantId: number, variantId: number,
selectedValues: Record<string, string | string[]>, selectedValues: Record<string, string | string[]>,
selectors: CatalogVariantSelector[],
): void { ): void {
const row = this.findRow(rowId); const row = this.findRow(rowId);
if (!row || (row.status === 'reserved' && row.reservedVariantId === variantId)) return; if (!row || (row.status === 'reserved' && row.reservedVariantId === variantId)) return;
this.patchRow(rowId, { status: 'reserving', error: null });
this.patchRow(rowId, {
selectedValues: row.reservedVariantId === null ? selectedValues : row.reservedSelectedValues,
selectors: row.reservedVariantId === null ? selectors : row.reservedSelectors,
status: 'reserving',
error: null,
});
const cartService = this.cartService.withoutLoading(); const cartService = this.cartService.withoutLoading();
const operation = const operation =
row.cartItemId === null row.cartItemId === null
@@ -372,7 +396,6 @@ export class ProductTicketSelectorComponent {
item.catalog_item_id === this.productId() && item.variant_id === variantId, item.catalog_item_id === this.productId() && item.variant_id === variantId,
) )
: response.data.items.find((item) => item.id === row.cartItemId); : response.data.items.find((item) => item.id === row.cartItemId);
if (!cartItem) { if (!cartItem) {
this.patchRow(rowId, { this.patchRow(rowId, {
variantId: row.reservedVariantId, variantId: row.reservedVariantId,
@@ -381,62 +404,104 @@ export class ProductTicketSelectorComponent {
}); });
return; return;
} }
const currentRow = this.findRow(rowId) ?? row;
this.patchRow(rowId, { this.patchRow(rowId, {
variantId, variantId,
reservedVariantId: variantId, reservedVariantId: variantId,
selectedValues, selectedValues,
selectors, selectors: this.buildSelectors(selectedValues, currentRow),
reservedSelectedValues: selectedValues, reservedSelectedValues: selectedValues,
reservedSelectors: selectors,
cartItemId: cartItem.id, cartItemId: cartItem.id,
status: 'reserved', status: 'reserved',
error: null, error: null,
}); });
if (row.cartItemId === null) {
this.availableVariantCount.update((count) => Math.max(0, count - 1));
}
}, },
error: (error: HttpErrorResponse) => { error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'La entrada ya no está disponible.'); const message = this.errorMessage(error, 'La entrada ya no está disponible.');
if (error.status === 422) {
if (row.reservedVariantId !== null) { this.recoverFromUnavailableVariant(rowId, variantId, message);
this.restoreReservedRowAfterError(rowId, row, message);
return; return;
} }
this.restoreReservedRowAfterError(rowId, row, message);
this.patchRow(rowId, { variantId: null, status: 'error', error: message });
this.toastService.danger(message);
}, },
}); });
this.reservationRequests.set(rowId, request); this.reservationRequests.set(rowId, request);
} }
private recoverFromUnavailableVariant(
rowId: number,
failedVariantId: number,
message: string,
): void {
this.patchRow(rowId, { status: 'checking', error: null });
this.loadVariantMap(
() => this.backtrackSelection(rowId, failedVariantId, message),
() => {
const row = this.findRow(rowId);
if (row) this.restoreReservedRowAfterError(rowId, row, message);
},
);
}
private backtrackSelection(rowId: number, failedVariantId: number, message: string): void {
const row = this.findRow(rowId);
if (!row) return;
const variants = this.availableVariantsFor(row).filter(({ id }) => id !== failedVariantId);
const selectedValues = { ...row.selectedValues };
const attributes = this.attributes();
for (let index = attributes.length - 1; index >= 0; index--) {
delete selectedValues[attributes[index].key];
const prefixKeys = attributes.slice(0, index).map(({ key }) => key);
const hasCompatibleVariant = variants.some((variant) =>
prefixKeys.every(
(key) =>
key in selectedValues &&
this.valueKey(variant.values[key]) === this.valueKey(selectedValues[key]),
),
);
if (!hasCompatibleVariant) continue;
this.patchRow(rowId, {
variantId: null,
selectedValues: { ...selectedValues },
selectors: this.buildSelectors(selectedValues, row, variants),
status: 'selecting',
error: message,
});
this.toastService.danger(message);
return;
}
this.patchRow(rowId, {
variantId: null,
selectedValues: {},
selectors: this.buildSelectors({}, row, variants),
status: 'error',
error: message,
});
this.toastService.danger(message);
}
private restoreReservedRowAfterError( private restoreReservedRowAfterError(
rowId: number, rowId: number,
row: TicketSelectionRow, row: TicketSelectionRow,
message: string, message: string,
): void { ): void {
this.patchRow(rowId, { if (row.reservedVariantId === null) {
variantId: row.reservedVariantId, this.patchRow(rowId, { variantId: null, status: 'error', error: message });
selectedValues: row.reservedSelectedValues, } else {
selectors: row.reservedSelectors, const selectedValues = row.reservedSelectedValues;
status: 'reserved', this.patchRow(rowId, {
error: null, variantId: row.reservedVariantId,
}); selectedValues,
selectors: this.buildSelectors(selectedValues, row),
status: 'reserved',
error: null,
});
}
this.toastService.danger(message); this.toastService.danger(message);
} }
private applySummary(response: CatalogVariantOptionsResponse, row: TicketSelectionRow): void {
this.availableVariantCount.set(
Math.max(0, response.available_variant_count - (row.cartItemId === null ? 0 : 1)),
);
this.remotePriceRange.set({
minimum: Number(response.price_range.minimum),
maximum: Number(response.price_range.maximum),
});
}
private createRow(id: number): TicketSelectionRow { private createRow(id: number): TicketSelectionRow {
return { return {
id, id,
@@ -446,25 +511,25 @@ export class ProductTicketSelectorComponent {
selectedValues: {}, selectedValues: {},
selectors: [], selectors: [],
reservedSelectedValues: {}, reservedSelectedValues: {},
reservedSelectors: [],
status: 'checking', status: 'checking',
error: null, error: null,
}; };
} }
private createCartRow(item: CartItem, id = this.nextRowId++): TicketSelectionRow | null { private createCartRow(item: CartItem, id = this.nextRowId++): TicketSelectionRow | null {
if (item.variant_id === null) return null; if (item.variant_id === null || item.variant === null) return null;
const selectedValues = Object.fromEntries(
Object.entries(item.variant.values).map(([key, value]) => [key, this.normalizeValue(value)]),
);
return { return {
id, id,
variantId: item.variant_id, variantId: item.variant_id,
reservedVariantId: item.variant_id, reservedVariantId: item.variant_id,
cartItemId: item.id, cartItemId: item.id,
selectedValues: {}, selectedValues,
selectors: [], selectors: [],
reservedSelectedValues: {}, reservedSelectedValues: selectedValues,
reservedSelectors: [], status: 'reserved',
status: 'checking',
error: null, error: null,
}; };
} }
@@ -474,61 +539,42 @@ export class ProductTicketSelectorComponent {
(item) => item.catalog_item_id === this.productId() && item.variant_id !== null, (item) => item.catalog_item_id === this.productId() && item.variant_id !== null,
); );
const currentRows = this.rows(); const currentRows = this.rows();
if (cartItems.length === 0) { if (cartItems.length === 0) {
if (currentRows.some((row) => row.cartItemId !== null)) { const localRows = currentRows.filter((row) => row.cartItemId === null);
this.replaceRows([this.createRow(this.nextRowId++)]); const rows = localRows.length > 0 ? localRows : [this.createRow(this.nextRowId++)];
} this.replaceRows(this.withRefreshedSelectors(rows));
this.ensureEmptyRowLoaded();
return; return;
} }
const rowsToLoad: TicketSelectionRow[] = [];
const synchronizedRows = cartItems.flatMap((item) => { const synchronizedRows = cartItems.flatMap((item) => {
const existingRow = currentRows.find((row) => row.cartItemId === item.id); const existingRow = currentRows.find((row) => row.cartItemId === item.id);
if (existingRow?.reservedVariantId === item.variant_id) return [existingRow];
const cartRow = this.createCartRow(item, existingRow?.id); const cartRow = this.createCartRow(item, existingRow?.id);
return cartRow === null ? [] : [cartRow];
if (!cartRow) return [];
if (existingRow && existingRow.reservedVariantId === cartRow.reservedVariantId) {
return [existingRow];
}
rowsToLoad.push(cartRow);
return [cartRow];
}); });
const localRows = currentRows.filter( const localRows = currentRows.filter(
(row) => row.cartItemId === null && Object.keys(row.selectedValues).length > 0, (row) => row.cartItemId === null && Object.keys(row.selectedValues).length > 0,
); );
this.replaceRows(this.withRefreshedSelectors([...synchronizedRows, ...localRows]));
this.replaceRows([...synchronizedRows, ...localRows]);
rowsToLoad.forEach((row) => this.loadOptions(row.id, row.selectedValues));
} }
private ensureEmptyRowLoaded(): void { private withRefreshedSelectors(rows: TicketSelectionRow[]): TicketSelectionRow[] {
const currentRows = this.rows(); const previousRows = this.rows();
this.rows.set(rows);
if (currentRows.length === 0) { const refreshed = rows.map((row) => ({
const row = this.createRow(this.nextRowId++); ...row,
this.rows.set([row]); status: row.status === 'checking' ? ('selecting' as const) : row.status,
this.loadOptions(row.id, {}); selectors: this.buildSelectors(row.selectedValues, row),
return; }));
} this.rows.set(previousRows);
return refreshed;
if (currentRows.length === 1 && !this.optionRequests.has(currentRows[0].id)) {
this.loadOptions(currentRows[0].id, currentRows[0].selectedValues);
}
} }
private replaceRows(rows: TicketSelectionRow[]): void { private replaceRows(rows: TicketSelectionRow[]): void {
const retainedIds = new Set(rows.map(({ id }) => id)); const retainedIds = new Set(rows.map(({ id }) => id));
this.rows().forEach((row) => { this.rows().forEach((row) => {
if (retainedIds.has(row.id)) return; if (retainedIds.has(row.id)) return;
this.optionRequests.get(row.id)?.unsubscribe();
this.reservationRequests.get(row.id)?.unsubscribe(); this.reservationRequests.get(row.id)?.unsubscribe();
this.optionRequests.delete(row.id);
this.reservationRequests.delete(row.id); this.reservationRequests.delete(row.id);
}); });
this.rows.set(rows); this.rows.set(rows);
@@ -544,7 +590,6 @@ export class ProductTicketSelectorComponent {
private deleteRow(rowId: number): void { private deleteRow(rowId: number): void {
this.rows.update((rows) => rows.filter((row) => row.id !== rowId)); this.rows.update((rows) => rows.filter((row) => row.id !== rowId));
this.optionRequests.delete(rowId);
this.reservationRequests.delete(rowId); this.reservationRequests.delete(rowId);
} }

View File

@@ -36,10 +36,10 @@
</app-button> </app-button>
<app-button <app-button
variant="secondary" variant="secondary"
[disabled]="hasVariants() && selectedVariant() === null" [disabled]="saving() || (hasVariants() && selectedVariant() === null)"
(click)="onAddToCart()" (click)="onAddToCart()"
> >
Agregar al carrito {{ saving() ? 'Guardando' : 'Agregar al carrito' }}
</app-button> </app-button>
</div> </div>
</div> </div>

View File

@@ -24,6 +24,7 @@ export class ProductVerticalWithCartCardComponent {
readonly description = input<string>(''); readonly description = input<string>('');
readonly price = input<number>(0); readonly price = input<number>(0);
readonly variants = input<VerticalCartVariant[]>([]); readonly variants = input<VerticalCartVariant[]>([]);
readonly saving = input(false);
readonly quantity = model<number>(1); readonly quantity = model<number>(1);
readonly selectedVariant = model<number | null>(null); readonly selectedVariant = model<number | null>(null);
@@ -46,6 +47,10 @@ export class ProductVerticalWithCartCardComponent {
protected readonly hasVariants = computed(() => this.variants().length > 0); protected readonly hasVariants = computed(() => this.variants().length > 0);
protected onAddToCart(): void { protected onAddToCart(): void {
if (this.saving()) {
return;
}
this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() }); this.addToCart.emit({ quantity: this.quantity(), variant: this.selectedVariant() });
} }