Compare commits

..

9 Commits

Author SHA1 Message Date
c486131905 feat(environment): add production environment configuration and file replacements 2026-08-18 15:09:11 -03:00
9ba2041f7b feat(hero-banner): update image handling to support responsive images and refactor template
feat(cart): enhance editing logic and add tests for editable state
feat(tenant): modify HeroConfig to include responsive image type
2026-08-18 14:18:20 -03:00
92ad7340fe feat(icon-button): add bordered variant style and update product ticket selector to use it 2026-08-18 11:43:49 -03:00
6b2f8de210 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.
2026-08-18 10:45:30 -03:00
69f3569ccf feat(product-ticket-selector): enhance variant selection logic and update test cases for improved accuracy 2026-08-18 09:18:45 -03:00
9937c1b484 feat(cart): refactor CartItem structure to remove nested product object and simplify access to properties 2026-08-18 09:06:17 -03:00
43e497cf97 feat(ticket-selector): refactor variant handling to use single variant property and update related tests 2026-08-18 08:51:52 -03:00
207c979f71 feat(product-ticket-selector): simplify row selection handling and improve test coverage for variant selection 2026-08-18 08:51:33 -03:00
30bfd9eff8 feat(ticket-selector): simplify validation handling and remove unused validation UI elements 2026-08-18 08:43:08 -03:00
35 changed files with 816 additions and 760 deletions

View File

@@ -59,7 +59,13 @@
"maximumError": "8kB"
}
],
"outputHashing": "all"
"outputHashing": "all",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.production.ts"
}
]
},
"development": {
"optimization": true,

View File

@@ -571,10 +571,9 @@ describe('StoreLayoutComponent', () => {
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: null,
product: {
nombre: 'Producto',
imagen: null,
},
nombre: 'Producto',
imagen: null,
variant: null,
},
],
});
@@ -624,10 +623,9 @@ describe('StoreLayoutComponent', () => {
precio_unitario: '100.00',
catalog_item_id: 1,
variant_id: null,
product: {
nombre: 'Producto',
imagen: null,
},
nombre: 'Producto',
imagen: null,
variant: null,
},
],
});

View File

@@ -53,7 +53,7 @@ export class StoreLayoutComponent implements OnInit {
});
private mapCartItemToMock(item: CartItem): CartItemMock {
const fullName = item.product?.nombre ?? '';
const fullName = item.nombre ?? '';
let product = fullName;
let attributes: { label: string; value: string }[] = [];
@@ -70,10 +70,7 @@ export class StoreLayoutComponent implements OnInit {
});
}
const variants = item.product?.variants ?? [];
const selectedVariant = item.product?.variants?.find(
(variant) => variant.id === item.variant_id,
);
const selectedVariant = item.variant;
if (selectedVariant) {
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
@@ -84,7 +81,7 @@ export class StoreLayoutComponent implements OnInit {
return {
cartItemId: item.id,
imageUrl: item.product?.imagen ?? null,
imageUrl: item.imagen,
product,
originalPrice: null,
discountedPrice: parseFloat(item.precio_unitario),
@@ -92,7 +89,6 @@ export class StoreLayoutComponent implements OnInit {
attributes,
quantity: item.cantidad,
variantId: item.variant_id,
variants,
};
}

View File

@@ -1,9 +1,3 @@
export interface CartItemProduct {
nombre: string;
imagen: string | null;
variants?: CartItemVariant[];
}
export interface CartItemVariantOption {
value: string;
label: string;
@@ -27,7 +21,9 @@ export interface CartItem {
precio_unitario: string;
catalog_item_id: number;
variant_id: number | null;
product: CartItemProduct | null;
nombre: string | null;
imagen: string | null;
variant: CartItemVariant | null;
}
export interface Cart {

View File

@@ -24,9 +24,13 @@ describe('CartService', () => {
precio_unitario: '10.00',
catalog_item_id: 5,
variant_id: 10,
product: {
nombre: 'Test Product (Size: M)',
imagen: null,
nombre: 'Test Product (Size: M)',
imagen: null,
variant: {
id: 10,
precio: '10.00',
stock_tecnico: 1,
values: { size: 'M' },
},
},
],

View File

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

View File

@@ -20,13 +20,18 @@ export interface WebsiteType {
}
export interface HeroConfig {
background_image_id?: string | null;
background_image_id?: string | ResponsiveImage | null;
title_html?: string | null;
description_html?: string | null;
button_text?: string | null;
button_href?: string | null;
}
export interface ResponsiveImage {
desktop: string;
mobile: string;
}
export interface AdditionalInfoConfig {
description?: string | null;
}

View File

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

View File

@@ -9,7 +9,16 @@ import {
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
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 { CartService } from '../../../../core/services/cart/cart.service';
@@ -52,6 +61,7 @@ export class CategoryItemsPageComponent {
protected readonly results = signal<CategoryItemsResponse | null>(null);
protected readonly error = signal<string | null>(null);
protected readonly creatingDirectPurchase = signal(false);
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly paginatedLayout: CatalogGroupLayout = 'paginated';
constructor() {
@@ -157,14 +167,31 @@ export class CategoryItemsPageComponent {
}
protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).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);
},
const productId = event.product.id;
if (this.savingProductIds().has(productId)) {
return;
}
this.setProductSaving(productId, true);
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()"
(click)="addToCart()"
>
@if (variantLoading() || addingToCart()) {
@if (addingToCart()) {
Guardando
} @else if (variantLoading()) {
<div class="spinner-border spinner-border-sm" role="status"></div>
} @else {
Agregar al carrito

View File

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

View File

@@ -9,7 +9,7 @@ import {
signal,
} from '@angular/core';
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 { CartService } from '../../../../core/services/cart/cart.service';
@@ -58,6 +58,7 @@ export class SearchPageComponent {
protected readonly results = signal<ApiPaginatedResponse<CatalogFeaturedItem[]> | null>(null);
protected readonly error = signal<string | null>(null);
protected readonly creatingDirectPurchase = signal(false);
protected readonly savingProductIds = signal<ReadonlySet<number>>(new Set<number>());
protected readonly productLayout = computed<CatalogProductLayout>(
() => this.tenantService.tenant()?.search_product_layout ?? 'column_with_image',
@@ -189,14 +190,31 @@ export class SearchPageComponent {
}
protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).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);
},
const productId = event.product.id;
if (this.savingProductIds().has(productId)) {
return;
}
this.setProductSaving(productId, true);
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)"
[loadImages]="!hasMainCarouselImages() || mainCarouselReady()"
[unavailableVariantIds]="unavailableVariantIds()"
[savingProductIds]="savingProductIds()"
(buy)="onBuyProduct($event)"
(addToCart)="onAddToCart($event)"
(pageChange)="onPageChange(group.id, $event)"

View File

@@ -254,9 +254,10 @@ describe('StoreHomePageComponent', () => {
const hero = (fixture.nativeElement as HTMLElement).querySelector(
'app-hero-banner .hero-banner',
) as HTMLElement;
const heroImage = hero.querySelector('img');
expect(hero).not.toBeNull();
expect(hero.style.backgroundImage).toContain('https://example.com/hero.jpg');
expect(heroImage?.getAttribute('src')).toBe('https://example.com/hero.jpg');
expect(hero.textContent).toContain('Fiesta Fútbol Infantil');
expect(hero.textContent).toContain('Viví una jornada inolvidable de fútbol infantil.');
expect(hero.textContent).toContain('Rosario, Santa Fe');

View File

@@ -10,7 +10,7 @@ import {
} from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { finalize, Subscription } from 'rxjs';
import { CartService } from '../../../../core/services/cart/cart.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 creatingDirectPurchase = signal(false);
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 heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null);
protected readonly additionalInfo = computed(
@@ -230,14 +231,31 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
}
protected onAddToCart(event: ProductListCartEvent): void {
this.cartService.addItem(event.product.id, event.variant ?? null, event.quantity).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);
},
const productId = event.product.id;
if (this.savingProductIds().has(productId)) {
return;
}
this.setProductSaving(productId, true);
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

@@ -6,7 +6,7 @@
<h2 class="m-0 text-uppercase fw-bold cart-title">{{ title() }}</h2>
<div class="d-flex align-items-center cart-header-actions">
@if (!readonly() && allowEditing() && items().length > 0) {
@if (!readonly() && editable() && allowEditing() && items().length > 0) {
<button
class="btn btn-link p-0 border-0 cart-edit-btn"
type="button"
@@ -48,7 +48,7 @@
[selectedVariant]="getItemVariant(item)"
[quantity]="getItemQuantity(item)"
[readonly]="readonly()"
[quantityDisabled]="editingDisabled() || (allowEditing() && !editing())"
[quantityDisabled]="!editable() || editingDisabled() || (allowEditing() && !editing())"
[showRemove]="allowRemove()"
(quantityChange)="onItemQuantityChange(idx, $event)"
(variantChange)="onItemVariantChange(idx, $event)"

View File

@@ -408,6 +408,54 @@ describe('CartComponent', () => {
).toBe(false);
});
it('hides the edit toggle and disables quantity changes when editable is false', 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('allowEditing', true);
fixture.componentRef.setInput('editable', false);
const quantityChange = vi.fn();
fixture.componentInstance.itemQuantityChange.subscribe(quantityChange);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.cart-edit-btn'))).toBeNull();
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
expect(cartItem.componentInstance.quantityDisabled()).toBe(true);
cartItem.triggerEventHandler('quantityChange', 2);
expect(quantityChange).not.toHaveBeenCalled();
});
it('persists a variant selected from a cart row', async () => {
const updateItemVariant = vi.fn().mockReturnValue(
of({

View File

@@ -53,6 +53,7 @@ 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 persistQuantityChanges = input<boolean>(true);
@@ -124,6 +125,10 @@ export class CartComponent {
}
protected onItemQuantityChange(index: number, newQuantity: number): void {
if (!this.editable()) {
return;
}
const mockItem = this.items()[index];
if (!mockItem) {
return;
@@ -220,7 +225,7 @@ export class CartComponent {
protected readonly formattedTotal = computed(() => this.formatCurrency(this.total()));
protected toggleEditing(): void {
if (this.editingDisabled()) {
if (!this.editable() || this.editingDisabled()) {
return;
}
@@ -254,7 +259,7 @@ export class CartComponent {
return {
cartItemId: item.id,
productName: item.product?.nombre ?? 'este producto',
productName: item.nombre ?? 'este producto',
};
}

View File

@@ -1,14 +1,13 @@
<div class="hero-banner-container">
<div class="hero-banner position-relative rounded">
<div
class="hero-media"
aria-hidden="true"
[ngStyle]="{
'background-image': heroConfig?.background_image_id
? 'url(' + heroConfig.background_image_id + ')'
: 'none',
}"
></div>
@if (desktopImageUrl) {
<picture class="hero-media" aria-hidden="true">
@if (mobileImageUrl) {
<source media="(max-width: 767.98px)" [srcset]="mobileImageUrl" />
}
<img [src]="desktopImageUrl" alt="" />
</picture>
}
@if (heroConfig) {
<div

View File

@@ -12,11 +12,20 @@
.hero-media {
position: absolute;
inset: 0;
display: block;
overflow: hidden;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
border-radius: inherit;
img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
&::after {
content: '';
position: absolute;

View File

@@ -2,6 +2,28 @@ import { TestBed } from '@angular/core/testing';
import { HeroBannerComponent } from './hero-banner.component';
describe('HeroBannerComponent', () => {
it('renders desktop and mobile crop variants', async () => {
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();
const fixture = TestBed.createComponent(HeroBannerComponent);
fixture.componentRef.setInput('heroConfig', {
background_image_id: {
desktop: 'https://example.com/desktop.jpg',
mobile: 'https://example.com/mobile.jpg',
},
});
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('source')?.getAttribute('srcset')).toBe(
'https://example.com/mobile.jpg',
);
expect(element.querySelector('img')?.getAttribute('src')).toBe(
'https://example.com/desktop.jpg',
);
});
it('expands and collapses the event schedules', async () => {
await TestBed.configureTestingModule({ imports: [HeroBannerComponent] }).compileComponents();

View File

@@ -18,6 +18,18 @@ export class HeroBannerComponent {
protected schedulesExpanded = false;
protected get desktopImageUrl(): string | null {
const image = this.heroConfig?.background_image_id;
return typeof image === 'string' ? image : (image?.desktop ?? null);
}
protected get mobileImageUrl(): string | null {
const image = this.heroConfig?.background_image_id;
return typeof image === 'string' ? image : (image?.mobile ?? image?.desktop ?? null);
}
get formattedDates(): string {
if (this.eventConfig?.dates_text) {
return this.eventConfig.dates_text;

View File

@@ -48,6 +48,17 @@
}
}
.icon-btn--bordered {
width: 38px;
height: 38px;
border: 1px solid var(--border-color);
&:hover:not(:disabled),
&:focus-visible:not(:disabled) {
border-color: currentcolor;
}
}
// Hover/Active/Focus colors (non-disabled)
.icon-btn:hover:not(:disabled),
.icon-btn:focus-visible:not(:disabled),

View File

@@ -22,6 +22,7 @@ export type IconButtonVariant =
})
export class IconButtonComponent {
readonly variant = input.required<IconButtonVariant>();
readonly bordered = input(false);
readonly disabled = input(false);
readonly ariaLabel = input<string>('');
readonly ariaExpanded = input<boolean | null>(null);
@@ -45,6 +46,10 @@ export class IconButtonComponent {
});
protected readonly buttonClasses = computed(() => {
return ['icon-btn', `icon-btn--${this.variant()}`];
return {
'icon-btn': true,
[`icon-btn--${this.variant()}`]: true,
'icon-btn--bordered': this.bordered(),
};
});
}

View File

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

View File

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

View File

@@ -34,7 +34,9 @@
<app-button variant="primary" (click)="onBuy()"> Comprar </app-button>
</div>
<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>

View File

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

View File

@@ -17,53 +17,48 @@
</header>
<div class="ticket-selector__selection">
<div class="ticket-selector__label-row">
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
@if (validationStatus(); as status) {
<span
class="ticket-selector__validation ticket-selector__validation--{{ status }}"
role="status"
aria-live="polite"
>
@switch (status) {
@case ('validating') {
<span class="ticket-selector__validation-spinner" aria-hidden="true"></span>
Validando
}
@case ('validated') {
<i class="fa-solid fa-check" aria-hidden="true"></i>
Validado
}
@case ('error') {
<i class="fa-solid fa-xmark" aria-hidden="true"></i>
Error
}
}
</span>
}
</div>
<span class="ticket-selector__label">Seleccioná Entrada/s:</span>
<div class="ticket-selector__rows">
@for (row of rows(); track row.id) {
<div class="ticket-selector__row">
<div class="ticket-selector__fields variant-selector">
@for (selector of row.selectors; track selector.key) {
<select
class="form-select variant-selector__select"
[attr.aria-label]="selector.label"
[disabled]="rowDisabled(row) || !selector.enabled"
[value]="selectedOptionKey(row, selector.key)"
(change)="onSelectionKeyChange(row.id, selector, $any($event.target).value)"
>
<option value="" disabled>Seleccioná {{ selector.label }}</option>
@for (option of selector.options; track $index) {
<option [value]="optionKey(option)">{{ optionLabel(option) }}</option>
}
</select>
<div class="ticket-selector__row-content">
<div class="ticket-selector__fields variant-selector">
@for (selector of row.selectors; track selector.key) {
<select
class="form-select variant-selector__select"
[attr.aria-label]="selector.label"
[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
[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>
<app-icon-button
variant="trash"
[bordered]="true"
ariaLabel="Eliminar entrada"
[disabled]="rowDisabled(row)"
(clicked)="removeRow(row.id)"

View File

@@ -44,49 +44,14 @@
padding-top: 1rem;
}
&__label-row {
display: flex;
align-items: center;
gap: 0.65rem;
min-height: 1.5rem;
margin-bottom: 0.5rem;
}
&__label {
display: inline-block;
margin-bottom: 0.5rem;
color: #555;
font-size: 15px;
font-weight: 700;
}
&__validation {
display: inline-flex;
align-items: center;
gap: 0.3rem;
font-size: 13px;
font-weight: 600;
&--validating {
color: #777;
}
&--validated {
color: var(--success-color, #198754);
}
&--error {
color: var(--danger-color, #dc3545);
}
}
&__validation-spinner {
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;
}
&__rows {
display: grid;
gap: 0.5rem;
@@ -95,10 +60,14 @@
&__row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
align-items: start;
gap: 0.5rem;
}
&__row-content {
min-width: 0;
}
&__fields {
min-width: 0;
display: grid;
@@ -131,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 {
margin: 0;
color: #777;
@@ -157,8 +145,8 @@
}
@media (prefers-reduced-motion: reduce) {
.ticket-selector__validation-spinner {
animation-duration: 1.4s;
.ticket-selector__row-status::before {
animation: none;
}
}

View File

@@ -3,7 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http';
import { signal } from '@angular/core';
import { TestBed, getTestBed } from '@angular/core/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 { 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 { 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', () => {
beforeAll(() => {
try {
@@ -23,230 +81,26 @@ describe('ProductTicketSelectorComponent', () => {
afterEach(() => TestBed.resetTestingModule());
it('checks partial selections and reserves the resolved variant in the cart', async () => {
const openConfirmDelete = vi.fn().mockReturnValue(of(true));
const removeItem = vi.fn().mockReturnValue(
of({
data: {
id: 10,
tenant_codigo: 'demo',
status: 'active',
subtotal: '0.00',
items: [],
},
}),
);
const resolvedVariant = {
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,
product: null,
},
],
},
}),
),
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();
expect(catalogService.getVariantOptions).toHaveBeenCalledTimes(1);
expect(catalogService.withoutLoading).toHaveBeenCalled();
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();
const validation = fixture.nativeElement.querySelector('.ticket-selector__validation');
expect(validation.textContent).toContain('Validado');
expect(validation.querySelector('.fa-check')).not.toBeNull();
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,
product: {
nombre: 'Entrada',
imagen: null,
variants: [
{
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' }],
enabled: true,
},
{ key: 'seat', label: 'Seat', options: ['1'], enabled: true },
],
selected_values: { sector: 'a', seat: '1' },
resolved_variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 1,
values: { sector: { value: 'a', label: 'Sector A' }, seat: '1' },
},
}),
),
};
async function createComponent({
maps,
addItem = vi.fn(),
cartState = signal(cartWith()),
toastDanger = vi.fn(),
}: {
maps: ReturnType<typeof mapResponse>[];
addItem?: ReturnType<typeof vi.fn>;
cartState?: ReturnType<typeof signal<ReturnType<typeof cartWith>>>;
toastDanger?: ReturnType<typeof vi.fn>;
}) {
const getVariantOptions = vi.fn();
maps.forEach((response) => getVariantOptions.mockReturnValueOnce(of(response)));
const catalogService = { withoutLoading: vi.fn(), getVariantOptions };
const cartService = {
cart: cartState.asReadonly(),
withoutLoading: vi.fn(),
addItem: vi.fn(),
addItem,
updateItemVariant: vi.fn(),
removeItem: vi.fn().mockReturnValue(of({ data: cartWith() })),
};
catalogService.withoutLoading.mockReturnValue(catalogService);
cartService.withoutLoading.mockReturnValue(cartService);
@@ -256,8 +110,14 @@ describe('ProductTicketSelectorComponent', () => {
providers: [
{ provide: CatalogService, useValue: catalogService },
{ provide: CartService, useValue: cartService },
{
provide: ModalService,
useValue: { openConfirmDelete: vi.fn().mockReturnValue(of(true)) },
},
{ provide: ToastService, useValue: { danger: toastDanger } },
],
}).compileComponents();
const fixture = TestBed.createComponent(ProductTicketSelectorComponent);
fixture.componentRef.setInput('productId', 7);
fixture.componentRef.setInput('title', 'Entrada');
@@ -265,169 +125,169 @@ describe('ProductTicketSelectorComponent', () => {
await fixture.whenStable();
fixture.detectChanges();
expect(catalogService.getVariantOptions).toHaveBeenCalledWith(7, {
selected_values: { sector: 'a', seat: '1' },
cart_item_id: 25,
});
expect(fixture.componentInstance['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
cartItemId: 25,
selectedValues: { sector: 'a', seat: '1' },
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 A',
'1',
]);
expect(
fixture.nativeElement.querySelector('.ticket-selector__validation').textContent,
).toContain('Validado');
});
return { fixture, getVariantOptions, cartService, toastDanger };
}
it('keeps the reserved selection and shows a toast when a variant change cannot be completed', 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,
product: {
nombre: 'Entrada',
imagen: null,
variants: [
{
id: 401,
precio: '10000.00',
stock_tecnico: 0,
values: { seat: '1' },
},
],
},
},
],
it('loads one map, recalculates the cascade locally and reserves only after the last select', async () => {
const selectedVariant = variant(401, 'general', 'A', '1', '1');
const variants = [
selectedVariant,
variant(402, 'general', 'A', '1', '2'),
variant(403, 'general', 'B', '2', '1'),
];
const addItem = vi.fn().mockReturnValue(of({ data: cartWith(selectedVariant) }));
const { fixture, getVariantOptions } = await createComponent({
maps: [mapResponse(variants)],
addItem,
});
const selector = {
key: 'seat',
label: 'Asiento',
const component = fixture.componentInstance;
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'],
enabled: true,
};
const summary = {
valid: true,
available_variant_count: 2,
matching_variant_count: 1,
price_range: { minimum: '10000.00', maximum: '10000.00' },
selectors: [selector],
};
const catalogService = {
withoutLoading: vi.fn(),
getVariantOptions: vi
.fn()
.mockReturnValueOnce(
of({
...summary,
selected_values: { seat: '1' },
resolved_variant: {
id: 401,
precio: '10000.00',
stock_tecnico: 0,
values: { seat: '1' },
},
});
component['onSelectionChange'](1, 'asiento', '1');
expect(getVariantOptions).toHaveBeenCalledTimes(1);
expect(addItem).toHaveBeenCalledWith(7, 401, 1);
expect(component['rows']()[0]).toMatchObject({
variantId: 401,
reservedVariantId: 401,
status: 'reserved',
});
});
it('shows a saving status while the selected seat is being reserved', async () => {
const selectedVariant = variant(401, 'general', 'A', '1', '1');
const reservation = new Subject<{ data: ReturnType<typeof cartWith> }>();
const addItem = vi.fn().mockReturnValue(reservation);
const { fixture } = await createComponent({
maps: [mapResponse([selectedVariant])],
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');
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('shows the remove action as a bordered icon button', async () => {
const { fixture } = await createComponent({
maps: [mapResponse([variant(401, 'general', 'A', '1', '1')])],
});
const removeButton = fixture.nativeElement.querySelector(
'app-icon-button[ariaLabel="Eliminar entrada"] button',
) as HTMLButtonElement | null;
expect(removeButton?.classList.contains('icon-btn--bordered')).toBe(true);
});
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');
fixture.detectChanges();
component['onSelectionChange'](1, 'tipo', 'general');
component['onSelectionChange'](1, 'sector', 'A');
component['onSelectionChange'](1, 'fila', '1');
component['onSelectionChange'](1, 'asiento', '1');
expect(cartService.updateItemVariant).toHaveBeenCalledTimes(1);
expect(toastService.danger).toHaveBeenLastCalledWith(unavailableMessage);
expect(getVariantOptions).toHaveBeenCalledTimes(2);
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({
variantId: 401,
reservedVariantId: 401,
selectedValues: { seat: '1' },
cartItemId: 25,
selectedValues: { tipo: 'general', sector: 'A', fila: '1', asiento: '1' },
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 { Subscription } from 'rxjs';
import { CartItem } from '../../../core/services/cart/cart.interface';
import { CartService } from '../../../core/services/cart/cart.service';
import { CartItem, CartItemVariantValue } from '../../../core/services/cart/cart.interface';
import { ModalService } from '../../../core/services/modal.service';
import { ToastService } from '../../../core/services/toast.service';
import {
CatalogFeaturedItemVariant,
CatalogVariantOptionsResponse,
CatalogVariantSelector,
CatalogVariantValue,
} from '../../../core/services/catalog/catalog.interface';
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';
@@ -36,7 +37,10 @@ type TicketSelectionStatus =
| 'removing'
| 'error';
type TicketValidationStatus = 'validating' | 'validated' | 'error';
interface VariantAttribute {
key: string;
label: string;
}
interface TicketSelectionRow {
id: number;
@@ -46,7 +50,6 @@ interface TicketSelectionRow {
selectedValues: Record<string, string | string[]>;
selectors: CatalogVariantSelector[];
reservedSelectedValues: Record<string, string | string[]>;
reservedSelectors: CatalogVariantSelector[];
status: TicketSelectionStatus;
error: string | null;
}
@@ -64,9 +67,12 @@ export class ProductTicketSelectorComponent {
private readonly modalService = inject(ModalService);
private readonly toastService = inject(ToastService);
private readonly destroyRef = inject(DestroyRef);
private readonly optionRequests = new Map<number, Subscription>();
private readonly reservationRequests = new Map<number, Subscription>();
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 title = input.required<string>();
@@ -78,10 +84,17 @@ export class ProductTicketSelectorComponent {
readonly buy = output<number[]>();
protected readonly rows = signal<TicketSelectionRow[]>([this.createRow(1)]);
protected readonly availableVariantCount = signal(0);
private readonly remotePriceRange = signal<{ minimum: number; maximum: number } | null>(null);
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(
() =>
this.rows().length > 0 &&
@@ -92,15 +105,6 @@ export class ProductTicketSelectorComponent {
row.variantId === row.reservedVariantId,
),
);
protected readonly validationStatus = computed<TicketValidationStatus | null>(() => {
const rows = this.rows();
if (rows.some((row) => this.isBusy(row))) return 'validating';
if (rows.some((row) => row.status === 'error' || row.error !== null)) return 'error';
if (rows.length > 0 && rows.every((row) => row.status === 'reserved')) return 'validated';
return null;
});
protected readonly canAddRow = computed(
() =>
this.availableVariantCount() > 0 &&
@@ -111,7 +115,6 @@ export class ProductTicketSelectorComponent {
const range = this.remotePriceRange();
const minimum = range?.minimum ?? this.price();
const maximum = range?.maximum ?? this.price();
return {
minimum: this.formatCurrency(minimum),
maximum: this.formatCurrency(maximum),
@@ -122,24 +125,22 @@ export class ProductTicketSelectorComponent {
constructor() {
effect(() => {
const viewReady = this.viewReady();
const mapReady = this.mapReady();
const cart = this.cartService.cart?.() ?? null;
if (!viewReady) return;
untracked(() => {
if (cart === null) {
this.ensureEmptyRowLoaded();
if (!mapReady) {
this.loadVariantMap();
return;
}
this.synchronizeWithCart(cart.items);
this.synchronizeWithCart(cart?.items ?? []);
});
});
afterNextRender(() => this.viewReady.set(true));
this.destroyRef.onDestroy(() => {
this.optionRequests.forEach((request) => request.unsubscribe());
this.mapRequest?.unsubscribe();
this.reservationRequests.forEach((request) => request.unsubscribe());
});
}
@@ -148,24 +149,20 @@ export class ProductTicketSelectorComponent {
const variantIds = this.rows().flatMap((row) =>
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 {
if (!this.canAddRow()) return;
const row = this.createRow(this.nextRowId++);
row.status = 'selecting';
row.selectors = this.buildSelectors(row.selectedValues, row);
this.rows.update((rows) => [...rows, row]);
this.loadOptions(row.id, {});
}
protected removeRow(rowId: number): void {
const row = this.findRow(rowId);
if (!row || this.isBusy(row)) return;
this.modalService
.openConfirmDelete({
title: 'Eliminar entrada',
@@ -181,32 +178,24 @@ export class ProductTicketSelectorComponent {
}
private confirmRemoveRow(row: TicketSelectionRow): void {
const rowId = row.id;
this.optionRequests.get(rowId)?.unsubscribe();
if (row.cartItemId === null) {
this.deleteRow(rowId);
this.deleteRow(row.id);
return;
}
this.patchRow(rowId, { status: 'removing', error: null });
this.patchRow(row.id, { status: 'removing', error: null });
const request = this.cartService
.withoutLoading()
.removeItem(row.cartItemId)
.subscribe({
next: () => {
this.availableVariantCount.update((count) => count + 1);
this.deleteRow(rowId);
},
next: () => this.deleteRow(row.id),
error: (error: HttpErrorResponse) => {
this.patchRow(rowId, {
this.patchRow(row.id, {
status: 'reserved',
error: this.errorMessage(error, 'No se pudo liberar la entrada.'),
});
},
});
this.reservationRequests.set(rowId, request);
this.reservationRequests.set(row.id, request);
}
protected onSelectionChange(
@@ -216,22 +205,25 @@ export class ProductTicketSelectorComponent {
): void {
const row = this.findRow(rowId);
if (!row || this.isBusy(row)) return;
const selectorIndex = this.attributes().findIndex(({ key }) => key === selectorKey);
if (selectorIndex < 0) return;
const selectorIndex = row.selectors.findIndex((selector) => selector.key === selectorKey);
const retainedKeys = new Set(row.selectors.slice(0, selectorIndex + 1).map(({ key }) => key));
const selectedValues = Object.fromEntries(
Object.entries(row.selectedValues).filter(([key]) => retainedKeys.has(key)),
);
const selectedValues = { ...row.selectedValues };
if (value === null) delete selectedValues[selectorKey];
else selectedValues[selectorKey] = this.normalizeValue(value);
this.attributes()
.slice(selectorIndex + 1)
.forEach(({ key }) => delete selectedValues[key]);
const preservesReservedSelection =
row.reservedVariantId !== null &&
row.selectors.length > 0 &&
row.selectors.every(({ key }) => key in selectedValues);
this.loadOptions(rowId, selectedValues, preservesReservedSelection);
const variant = this.resolveVariant(row, selectedValues);
this.patchRow(rowId, {
variantId: variant?.id ?? null,
selectedValues,
selectors: this.buildSelectors(selectedValues, row),
status: 'selecting',
error: null,
});
if (variant !== null) this.reserveRow(rowId, variant.id, selectedValues);
}
protected optionLabel(value: CatalogVariantValue): string {
@@ -249,7 +241,6 @@ export class ProductTicketSelectorComponent {
protected selectedOptionKey(row: TicketSelectionRow, key: string): string {
const selectedOption = this.selectedOption(row, key);
return selectedOption === null ? '' : this.valueKey(selectedOption);
}
@@ -260,7 +251,6 @@ export class ProductTicketSelectorComponent {
): void {
const selectedOption =
selector.options.find((option) => this.valueKey(option) === selectedKey) ?? null;
this.onSelectionChange(rowId, selector.key, selectedOption);
}
@@ -268,111 +258,130 @@ export class ProductTicketSelectorComponent {
return this.disabled() || this.isBusy(row);
}
private loadOptions(
rowId: number,
selectedValues: Record<string, string | string[]>,
preserveReservedSelection = false,
private loadVariantMap(
onLoaded?: () => void,
onError?: (error: HttpErrorResponse) => void,
): void {
const row = this.findRow(rowId);
if (!row) return;
this.optionRequests.get(rowId)?.unsubscribe();
this.patchRow(rowId, {
selectedValues: preserveReservedSelection ? row.reservedSelectedValues : selectedValues,
status: 'checking',
error: null,
});
if (this.mapRequest !== null && !onLoaded) return;
this.mapRequest?.unsubscribe();
const request = this.catalogService
.withoutLoading()
.getVariantOptions(this.productId(), {
selected_values: selectedValues,
cart_item_id: row.cartItemId,
})
.getVariantOptions(this.productId(), { selected_values: {} })
.subscribe({
next: (response) => {
this.applySummary(response, row);
if (!response.valid) {
if (row.reservedVariantId !== null) {
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,
);
}
}
this.applyVariantMap(response);
this.mapReady.set(true);
this.mapRequest = null;
onLoaded?.();
},
error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.');
if (row.reservedVariantId !== null) {
this.restoreReservedRowAfterError(rowId, row, message);
this.mapRequest = null;
if (onError) {
onError(error);
return;
}
this.patchRow(rowId, { status: 'error', error: message });
const message = this.errorMessage(error, 'No se pudo consultar la disponibilidad.');
this.rows.update((rows) =>
rows.map((row) => ({ ...row, status: 'error', error: 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(
rowId: number,
variantId: number,
selectedValues: Record<string, string | string[]>,
selectors: CatalogVariantSelector[],
): void {
const row = this.findRow(rowId);
if (!row || (row.status === 'reserved' && row.reservedVariantId === variantId)) return;
this.patchRow(rowId, {
selectedValues: row.reservedVariantId === null ? selectedValues : row.reservedSelectedValues,
selectors: row.reservedVariantId === null ? selectors : row.reservedSelectors,
status: 'reserving',
error: null,
});
this.patchRow(rowId, { status: 'reserving', error: null });
const cartService = this.cartService.withoutLoading();
const operation =
row.cartItemId === null
@@ -387,7 +396,6 @@ export class ProductTicketSelectorComponent {
item.catalog_item_id === this.productId() && item.variant_id === variantId,
)
: response.data.items.find((item) => item.id === row.cartItemId);
if (!cartItem) {
this.patchRow(rowId, {
variantId: row.reservedVariantId,
@@ -396,62 +404,104 @@ export class ProductTicketSelectorComponent {
});
return;
}
const currentRow = this.findRow(rowId) ?? row;
this.patchRow(rowId, {
variantId,
reservedVariantId: variantId,
selectedValues,
selectors,
selectors: this.buildSelectors(selectedValues, currentRow),
reservedSelectedValues: selectedValues,
reservedSelectors: selectors,
cartItemId: cartItem.id,
status: 'reserved',
error: null,
});
if (row.cartItemId === null) {
this.availableVariantCount.update((count) => Math.max(0, count - 1));
}
},
error: (error: HttpErrorResponse) => {
const message = this.errorMessage(error, 'La entrada ya no está disponible.');
if (row.reservedVariantId !== null) {
this.restoreReservedRowAfterError(rowId, row, message);
if (error.status === 422) {
this.recoverFromUnavailableVariant(rowId, variantId, message);
return;
}
this.patchRow(rowId, { variantId: null, status: 'error', error: message });
this.toastService.danger(message);
this.restoreReservedRowAfterError(rowId, row, message);
},
});
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(
rowId: number,
row: TicketSelectionRow,
message: string,
): void {
this.patchRow(rowId, {
variantId: row.reservedVariantId,
selectedValues: row.reservedSelectedValues,
selectors: row.reservedSelectors,
status: 'reserved',
error: null,
});
if (row.reservedVariantId === null) {
this.patchRow(rowId, { variantId: null, status: 'error', error: message });
} else {
const selectedValues = row.reservedSelectedValues;
this.patchRow(rowId, {
variantId: row.reservedVariantId,
selectedValues,
selectors: this.buildSelectors(selectedValues, row),
status: 'reserved',
error: null,
});
}
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 {
return {
id,
@@ -461,20 +511,16 @@ export class ProductTicketSelectorComponent {
selectedValues: {},
selectors: [],
reservedSelectedValues: {},
reservedSelectors: [],
status: 'checking',
error: null,
};
}
private createCartRow(item: CartItem, id = this.nextRowId++): TicketSelectionRow | null {
if (item.variant_id === null) return null;
const variant = item.product?.variants?.find(({ id }) => id === item.variant_id);
if (!variant) return null;
const selectedValues = this.normalizeCartValues(variant.values);
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 {
id,
variantId: item.variant_id,
@@ -483,8 +529,7 @@ export class ProductTicketSelectorComponent {
selectedValues,
selectors: [],
reservedSelectedValues: selectedValues,
reservedSelectors: [],
status: 'checking',
status: 'reserved',
error: null,
};
}
@@ -494,85 +539,47 @@ export class ProductTicketSelectorComponent {
(item) => item.catalog_item_id === this.productId() && item.variant_id !== null,
);
const currentRows = this.rows();
if (cartItems.length === 0) {
if (currentRows.some((row) => row.cartItemId !== null)) {
this.replaceRows([this.createRow(this.nextRowId++)]);
}
this.ensureEmptyRowLoaded();
const localRows = currentRows.filter((row) => row.cartItemId === null);
const rows = localRows.length > 0 ? localRows : [this.createRow(this.nextRowId++)];
this.replaceRows(this.withRefreshedSelectors(rows));
return;
}
const rowsToLoad: TicketSelectionRow[] = [];
const synchronizedRows = cartItems.flatMap((item) => {
const existingRow = currentRows.find((row) => row.cartItemId === item.id);
if (existingRow?.reservedVariantId === item.variant_id) return [existingRow];
const cartRow = this.createCartRow(item, existingRow?.id);
if (!cartRow) return [];
if (
existingRow &&
existingRow.reservedVariantId === cartRow.reservedVariantId &&
this.sameSelectedValues(existingRow.selectedValues, cartRow.selectedValues)
) {
return [existingRow];
}
rowsToLoad.push(cartRow);
return [cartRow];
return cartRow === null ? [] : [cartRow];
});
const localRows = currentRows.filter(
(row) => row.cartItemId === null && Object.keys(row.selectedValues).length > 0,
);
this.replaceRows([...synchronizedRows, ...localRows]);
rowsToLoad.forEach((row) => this.loadOptions(row.id, row.selectedValues));
this.replaceRows(this.withRefreshedSelectors([...synchronizedRows, ...localRows]));
}
private ensureEmptyRowLoaded(): void {
const currentRows = this.rows();
if (currentRows.length === 0) {
const row = this.createRow(this.nextRowId++);
this.rows.set([row]);
this.loadOptions(row.id, {});
return;
}
if (currentRows.length === 1 && !this.optionRequests.has(currentRows[0].id)) {
this.loadOptions(currentRows[0].id, currentRows[0].selectedValues);
}
private withRefreshedSelectors(rows: TicketSelectionRow[]): TicketSelectionRow[] {
const previousRows = this.rows();
this.rows.set(rows);
const refreshed = rows.map((row) => ({
...row,
status: row.status === 'checking' ? ('selecting' as const) : row.status,
selectors: this.buildSelectors(row.selectedValues, row),
}));
this.rows.set(previousRows);
return refreshed;
}
private replaceRows(rows: TicketSelectionRow[]): void {
const retainedIds = new Set(rows.map(({ id }) => id));
this.rows().forEach((row) => {
if (retainedIds.has(row.id)) return;
this.optionRequests.get(row.id)?.unsubscribe();
this.reservationRequests.get(row.id)?.unsubscribe();
this.optionRequests.delete(row.id);
this.reservationRequests.delete(row.id);
});
this.rows.set(rows);
}
private normalizeCartValues(
values: Record<string, CartItemVariantValue>,
): Record<string, string | string[]> {
return Object.fromEntries(
Object.entries(values).map(([key, value]) => [key, this.normalizeValue(value)]),
);
}
private sameSelectedValues(
left: Record<string, string | string[]>,
right: Record<string, string | string[]>,
): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
private findRow(rowId: number): TicketSelectionRow | undefined {
return this.rows().find((row) => row.id === rowId);
}
@@ -583,7 +590,6 @@ export class ProductTicketSelectorComponent {
private deleteRow(rowId: number): void {
this.rows.update((rows) => rows.filter((row) => row.id !== rowId));
this.optionRequests.delete(rowId);
this.reservationRequests.delete(rowId);
}

View File

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

View File

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

View File

@@ -0,0 +1,6 @@
export const environment = {
production: true,
nombre: "Producción - activo",
url: "https://backend.shopit.com.ar/api/",
urlDescarga: "url/"
};