feat: enhance product attributes and event date handling for improved user experience and data management

This commit is contained in:
2026-08-07 14:16:02 -03:00
parent 8d88e1bb13
commit 1977df6765
18 changed files with 368 additions and 187 deletions

View File

@@ -24,13 +24,24 @@ export interface ProductAttributeOption {
metadata: Record<string, unknown> | null;
}
export type ProductAttributeType =
| 'string'
| 'number'
| 'boolean'
| 'select'
| 'multiselect'
| 'color'
| 'image'
| 'event_date';
export interface ProductAttribute {
id: number;
codigo: string;
nombre: string;
is_required: boolean;
allow_multi_select?: boolean;
metadata_schema: Record<string, unknown> | null;
type: string;
type: ProductAttributeType;
options: ProductAttributeOption[];
}
@@ -38,23 +49,17 @@ export type InventoryPolicy = 'tracked' | 'unlimited';
export interface CatalogItemVariant {
id: number;
descripcion?: string | null;
precio?: string;
event_date_id?: number | null;
event_date_ids?: number[];
event_dates?: string[];
stock_tecnico: number | null;
minimum_use_date?: string | null;
maximum_use_date?: string | null;
effective_minimum_use_date?: string | null;
effective_maximum_use_date?: string | null;
values: Record<string, string>;
}
export interface CatalogItemEventDate {
id: number;
variant_id: number;
date: string;
starts_at: string;
ends_at: string;
label: string;
stock_tecnico: number | null;
values: Record<string, string | string[]>;
}
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
@@ -74,12 +79,12 @@ export interface CatalogItemDetail {
category: string | null;
brand: string | null;
inventory_policy: InventoryPolicy;
max_units_per_user?: number | null;
has_tickets: boolean;
minimum_use_date: string | null;
maximum_use_date: string | null;
attributes: ProductAttribute[];
variants: CatalogItemVariant[];
event_dates?: CatalogItemEventDate[];
selected_variant?: SelectedCatalogItemVariant;
stock_tecnico?: number | null;
images?: string[];
@@ -90,8 +95,10 @@ export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'c
export interface CatalogFeaturedItemVariant {
id: number;
descripcion?: string | null;
precio?: string;
stock_tecnico: number | null;
values: Record<string, string>;
values: Record<string, string | string[]>;
}
export interface CatalogFeaturedItem {

View File

@@ -29,7 +29,6 @@ export interface PurchaseStatusResponse {
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
id: number;
event_id: number | null;
created_at: string | null;
total: string;
}
@@ -59,7 +58,6 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
id: number;
cart_id: number | null;
tenant_codigo: string;
event_id: number | null;
user_id: number;
created_at: string | null;
payment_method: string | null;

View File

@@ -54,10 +54,9 @@ export interface ActiveEventDate {
time_end: string;
}
export interface ActiveEvent {
id: number;
name: string;
address: string;
export interface TenantEvent {
title: string;
location: string;
dates: ActiveEventDate[];
}
@@ -108,8 +107,7 @@ export interface Tenant {
website_type_code?: string | null;
website_type?: WebsiteType | null;
extras?: WebsiteExtras;
active_event_id?: number | null;
active_event?: ActiveEvent | null;
event?: TenantEvent | null;
selected_bank_account_id?: number | null;
selected_bank_account?: BankAccount | null;
search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart';

View File

@@ -0,0 +1,17 @@
export interface TimeWindowValidityTime {
id: number;
type: 'time_window';
is_valid: boolean;
start_time?: string;
end_time?: string;
}
export interface FixedWindowValidityTime {
id: number;
type: 'fixed_window';
is_valid: boolean;
fixed_starts_at?: string;
fixed_expires_at?: string;
}
export type ValidityTime = TimeWindowValidityTime | FixedWindowValidityTime;

View File

@@ -1,5 +1,5 @@
<div class="attribute-selector">
@for (attribute of attributes(); track attribute.id) {
@for (attribute of attributes(); track attribute.codigo) {
<div class="attribute-selector__row">
<span class="attribute-selector__label">{{ attribute.nombre }}:</span>
@@ -10,12 +10,14 @@
type="button"
class="attribute-selector__swatch"
[class.attribute-selector__swatch--selected]="hasSelectedOption(attribute, option)"
[class.attribute-selector__swatch--disabled]="!availableOptions()[attribute.id][option.id]"
[class.attribute-selector__swatch--disabled]="
!availableOptions()[attribute.codigo][option.id]
"
[style.background-color]="getOptionSwatchColor(option)"
[attr.aria-label]="option.label"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[title]="option.label"
[disabled]="!availableOptions()[attribute.id][option.id]"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
<span class="visually-hidden">{{ option.label }}</span>
@@ -24,10 +26,14 @@
<button
type="button"
class="attribute-selector__text-option"
[class.attribute-selector__text-option--selected]="hasSelectedOption(attribute, option)"
[class.attribute-selector__text-option--disabled]="!availableOptions()[attribute.id][option.id]"
[class.attribute-selector__text-option--selected]="
hasSelectedOption(attribute, option)
"
[class.attribute-selector__text-option--disabled]="
!availableOptions()[attribute.codigo][option.id]
"
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
[disabled]="!availableOptions()[attribute.id][option.id]"
[disabled]="!availableOptions()[attribute.codigo][option.id]"
(click)="selectAttributeOption(attribute, option)"
>
{{ option.label }}

View File

@@ -68,4 +68,46 @@ describe('ProductAttributeSelectorComponent', () => {
expect(buttons[0].disabled).toBe(true);
expect(buttons[1].disabled).toBe(false);
});
it('allows multiple event dates and emits the exact matching variant', () => {
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
const emittedIds: Array<number | null> = [];
fixture.componentInstance.variantChange.subscribe((variant) =>
emittedIds.push(variant?.id ?? null),
);
fixture.componentRef.setInput('attributes', [
{
id: 2,
codigo: 'event_date',
nombre: 'Fecha',
is_required: true,
allow_multi_select: true,
metadata_schema: null,
type: 'event_date',
options: [
{ id: 101, value: '1', label: '09/10/2026', sort_order: 0, metadata: null },
{ id: 102, value: '2', label: '10/10/2026', sort_order: 1, metadata: null },
],
} satisfies ProductAttribute,
]);
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
fixture.componentRef.setInput('variants', [
{ id: 1, stock_tecnico: null, values: { event_date: '1' } },
{ id: 2, stock_tecnico: null, values: { event_date: '2' } },
{ id: 3, stock_tecnico: null, values: { event_date: ['1', '2'] } },
]);
fixture.detectChanges();
const buttons = Array.from(
fixture.nativeElement.querySelectorAll('.attribute-selector__text-option'),
) as HTMLButtonElement[];
buttons[0].click();
fixture.detectChanges();
buttons[1].click();
fixture.detectChanges();
expect(buttons[0].getAttribute('aria-pressed')).toBe('true');
expect(buttons[1].getAttribute('aria-pressed')).toBe('true');
expect(emittedIds).toContain(3);
});
});

View File

@@ -32,48 +32,65 @@ export class ProductAttributeSelectorComponent {
public variantChange = output<CatalogItemVariant | null>();
protected readonly selectedAttributeOptions = signal<Record<number, number>>({});
protected readonly selectedAttributeOptions = signal<Record<string, number[]>>({});
protected readonly availableOptions = computed(() => {
const selections = this.selectedAttributeOptions();
const variants = this.variants();
const attributes = this.attributes();
const availability: Record<number, Record<number, boolean>> = {};
const availability: Record<string, Record<number, boolean>> = {};
for (const attribute of attributes) {
availability[attribute.id] = {};
availability[attribute.codigo] = {};
for (const option of attribute.options) {
const optionNormalized = this.normalizeText(option.value || option.label);
const selectedForAttribute = selections[attribute.codigo] ?? [];
if (
!attribute.allow_multi_select &&
selectedForAttribute.length >= 1 &&
!selectedForAttribute.includes(option.id)
) {
availability[attribute.codigo][option.id] = false;
continue;
}
const isAvailable = variants.some((variant) => {
if (!this.isVariantAvailable(variant)) return false;
const variantAttrValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
if (!variantAttrValue || this.normalizeText(variantAttrValue) !== optionNormalized) {
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
const desiredOptionIds = selectedForAttribute.includes(option.id)
? selectedForAttribute
: [...selectedForAttribute, option.id];
const desiredValues = desiredOptionIds
.map((id) => attribute.options.find((candidate) => candidate.id === id))
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
if (
!variantAttrValues.includes(optionNormalized) ||
!desiredValues.every((value) => variantAttrValues.includes(value))
) {
return false;
}
for (const otherAttr of attributes) {
if (otherAttr.id === attribute.id) continue;
const selectedOptionId = selections[otherAttr.id];
if (selectedOptionId !== undefined) {
const selectedOption = otherAttr.options.find((o) => o.id === selectedOptionId);
if (selectedOption) {
const selectedNormalized = this.normalizeText(
selectedOption.value || selectedOption.label,
);
const vAttrValue = this.getDefaultVariantAttributeValue(otherAttr, variant.values);
if (!vAttrValue || this.normalizeText(vAttrValue) !== selectedNormalized) {
return false;
}
}
if (otherAttr.codigo === attribute.codigo) continue;
const selectedOptionIds = selections[otherAttr.codigo] ?? [];
const selectedValues = selectedOptionIds
.map((id) => otherAttr.options.find((candidate) => candidate.id === id))
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
const variantValues = this.getVariantAttributeValues(otherAttr, variant.values);
if (!selectedValues.every((value) => variantValues.includes(value))) {
return false;
}
}
return true;
});
availability[attribute.id][option.id] = isAvailable;
availability[attribute.codigo][option.id] = isAvailable;
}
}
@@ -109,17 +126,28 @@ export class ProductAttributeSelectorComponent {
attribute: ProductAttribute,
option: ProductAttributeOption,
): boolean {
return this.selectedAttributeOptions()[attribute.id] === option.id;
return (this.selectedAttributeOptions()[attribute.codigo] ?? []).includes(option.id);
}
protected selectAttributeOption(
attribute: ProductAttribute,
option: ProductAttributeOption,
): void {
this.selectedAttributeOptions.update((current) => ({
...current,
[attribute.id]: option.id,
}));
this.selectedAttributeOptions.update((current) => {
const selected = current[attribute.codigo] ?? [];
const isMultiple = attribute.allow_multi_select ?? false;
let next: number[];
if (!isMultiple) {
next = [option.id];
} else if (selected.includes(option.id)) {
next = selected.filter((id) => id !== option.id);
} else {
next = [...selected, option.id];
}
return { ...current, [attribute.codigo]: next };
});
}
protected isColorOption(option: ProductAttributeOption): boolean {
@@ -134,51 +162,44 @@ export class ProductAttributeSelectorComponent {
attributes: ProductAttribute[],
defaultVariant: CatalogItemVariant | null,
): void {
const selections: Record<number, number> = {};
const selections: Record<string, number[]> = {};
for (const attribute of attributes) {
const optionId = this.findDefaultOptionId(attribute, defaultVariant);
if (optionId !== null) {
selections[attribute.id] = optionId;
const optionIds = this.findDefaultOptionIds(attribute, defaultVariant);
if (optionIds.length > 0) {
selections[attribute.codigo] = optionIds;
}
}
this.selectedAttributeOptions.set(selections);
}
private findDefaultOptionId(
private findDefaultOptionIds(
attribute: ProductAttribute,
variant: CatalogItemVariant | null,
): number | null {
): number[] {
if (!variant) {
return null;
return [];
}
const defaultValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
if (!defaultValue) {
return null;
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
if (defaultValues.length === 0) {
return [];
}
const normalizedValue = this.normalizeText(defaultValue);
const matchByValue = attribute.options.find(
(option) => this.normalizeText(option.value) === normalizedValue,
);
if (matchByValue) {
return matchByValue.id;
}
const matchByLabel = attribute.options.find(
(option) => this.normalizeText(option.label) === normalizedValue,
);
return matchByLabel?.id ?? null;
return attribute.options
.filter(
(option) =>
defaultValues.includes(this.normalizeText(option.value)) ||
defaultValues.includes(this.normalizeText(option.label)),
)
.map((option) => option.id);
}
private getDefaultVariantAttributeValue(
private getVariantAttributeValues(
attribute: ProductAttribute,
variantAttributes: Record<string, string>,
): string | null {
variantAttributes: Record<string, string | string[]>,
): string[] {
const normalizedCodigo = this.normalizeText(attribute.codigo);
const normalizedNombre = this.normalizeText(attribute.nombre);
@@ -186,11 +207,11 @@ export class ProductAttributeSelectorComponent {
const normalizedKey = this.normalizeText(key);
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
return value;
return (Array.isArray(value) ? value : [value]).map((item) => this.normalizeText(item));
}
}
return null;
return [];
}
private normalizeText(value: string | null | undefined): string {
@@ -234,7 +255,7 @@ export class ProductAttributeSelectorComponent {
}
private emitMatchingVariant(
selections: Record<number, number>,
selections: Record<string, number[]>,
variants: CatalogItemVariant[],
attributes: ProductAttribute[],
): void {
@@ -243,18 +264,22 @@ export class ProductAttributeSelectorComponent {
return;
}
const selectedValuesById: Record<number, string> = {};
const selectedValuesByCode: Record<string, string[]> = {};
let allSelected = true;
for (const attr of attributes) {
const selectedOptionId = selections[attr.id];
if (selectedOptionId === undefined) {
const selectedOptionIds = selections[attr.codigo] ?? [];
if (
selectedOptionIds.length === 0 ||
(!attr.allow_multi_select && selectedOptionIds.length !== 1)
) {
allSelected = false;
break;
}
const option = attr.options.find((o) => o.id === selectedOptionId);
if (option) {
selectedValuesById[attr.id] = this.normalizeText(option.value || option.label);
}
selectedValuesByCode[attr.codigo] = selectedOptionIds
.map((id) => attr.options.find((option) => option.id === id))
.filter((option): option is ProductAttributeOption => option !== undefined)
.map((option) => this.normalizeText(option.value || option.label))
.sort();
}
if (!allSelected) {
@@ -264,10 +289,12 @@ export class ProductAttributeSelectorComponent {
const matchingVariant = variants.find((variant) => {
return attributes.every((attr) => {
const selectedValue = selectedValuesById[attr.id];
const variantValue = this.getDefaultVariantAttributeValue(attr, variant.values);
if (!variantValue) return false;
return this.normalizeText(variantValue) === selectedValue;
const selectedValues = selectedValuesByCode[attr.codigo];
const variantValues = this.getVariantAttributeValues(attr, variant.values).sort();
return (
selectedValues.length === variantValues.length &&
selectedValues.every((value, index) => value === variantValues[index])
);
});
});

View File

@@ -26,7 +26,7 @@
<div class="product-detail__price-group">
<span class="product-detail__price-current">
{{ getFormattedPrice(prod.precio) }}
{{ getFormattedPrice(effectivePrice()) }}
</span>
@if (oldPrice(); as oldPrice) {
@@ -35,31 +35,6 @@
</div>
</section>
@if (hasEventDates()) {
<div class="product-detail__divider"></div>
<section class="product-detail__section product-detail__section--event-date">
<label class="form-label" for="event-date-selector">Fecha</label>
<select
id="event-date-selector"
class="form-select"
[value]="selectedVariant()?.id ?? ''"
(change)="onEventDateChange($event)"
>
@for (eventDate of eventDates(); track eventDate.id) {
<option
[value]="eventDate.variant_id"
[disabled]="
prod.inventory_policy !== 'unlimited' && (eventDate.stock_tecnico ?? 0) <= 0
"
>
{{ eventDate.label }}
</option>
}
</select>
</section>
}
@if (hasRenderableAttributes()) {
<div class="product-detail__divider"></div>
@@ -124,7 +99,7 @@
[class.product-detail__description-body--expanded]="descriptionExpanded()"
[style.max-height.px]="descriptionExpanded() ? descriptionMaxHeight() || null : null"
>
{{ prod.descripcion }}
{{ effectiveDescription() }}
</div>
@if (showDescriptionToggle()) {

View File

@@ -22,6 +22,7 @@ import {
describe('ProductDetailPageComponent', () => {
const mockProduct: CatalogItemDetail = {
id: 1,
type: 'product',
category_id: 10,
brand_id: null,
slug: 'auriculares-bluetooth',
@@ -327,33 +328,39 @@ describe('ProductDetailPageComponent', () => {
expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe('');
});
it('renders event dates and resolves the selected date through its variant', async () => {
it('renders event dates as a dynamic attribute and resolves their variants', async () => {
const detailProduct: CatalogItemDetail = {
...mockProduct,
purpose: 'entry',
has_tickets: true,
variants: [
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: {} },
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: {} },
{ id: 101, event_date_id: 20, stock_tecnico: 10, values: { event_date: '20' } },
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
],
event_dates: [
attributes: [
{
id: 20,
variant_id: 101,
date: '2026-10-09',
starts_at: '2026-10-09T10:00:00.000000Z',
ends_at: '2026-10-09T20:00:00.000000Z',
label: 'Viernes 9 de octubre - 10:00 a 20:00',
stock_tecnico: 10,
},
{
id: 21,
variant_id: 102,
date: '2026-10-10',
starts_at: '2026-10-10T10:00:00.000000Z',
ends_at: '2026-10-10T20:00:00.000000Z',
label: 'Sábado 10 de octubre - 10:00 a 20:00',
stock_tecnico: 10,
id: 99,
codigo: 'event_date',
nombre: 'Fecha',
is_required: true,
metadata_schema: null,
type: 'event_date',
options: [
{
id: 20,
value: '20',
label: '09/10/2026 · 10:00 a 20:00',
sort_order: 0,
metadata: null,
},
{
id: 21,
value: '21',
label: '10/10/2026 · 10:00 a 20:00',
sort_order: 1,
metadata: null,
},
],
},
],
selected_variant: {
@@ -373,12 +380,13 @@ describe('ProductDetailPageComponent', () => {
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
const select = fixture.nativeElement.querySelector('#event-date-selector') as HTMLSelectElement;
expect(select.options).toHaveLength(2);
expect(select.value).toBe('101');
const options = fixture.nativeElement.querySelectorAll(
'.attribute-selector__text-option',
) as NodeListOf<HTMLButtonElement>;
expect(options).toHaveLength(2);
expect(options[0].classList.contains('attribute-selector__text-option--selected')).toBe(true);
select.value = '102';
select.dispatchEvent(new Event('change'));
options[1].click();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
@@ -621,6 +629,39 @@ describe('ProductDetailPageComponent', () => {
expect(fixture.componentInstance['quantity']()).toBe(2);
});
it('caps an unlimited variant at the per-user purchase limit', async () => {
const unlimitedVariant = {
id: 322,
stock_tecnico: null,
values: {},
};
resolveProduct({
...mockProduct,
inventory_policy: 'unlimited',
max_units_per_user: 2,
selected_variant: {
id: 322,
stock_tecnico: null,
images: [],
values: { event_date: '20' },
},
variants: [unlimitedVariant],
});
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
const increaseButton = fixture.nativeElement.querySelector(
'app-quantity-selector button:last-child',
) as HTMLButtonElement;
increaseButton.click();
fixture.detectChanges();
expect(fixture.componentInstance['quantity']()).toBe(2);
expect(increaseButton.disabled).toBe(true);
});
it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = {
id: 654,

View File

@@ -86,13 +86,28 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly creatingDirectPurchase = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly selectedVariant = signal<CatalogItemVariant | null>(null);
protected readonly effectiveDescription = computed(
() => this.selectedVariant()?.descripcion ?? this.product()?.descripcion ?? '',
);
protected readonly effectivePrice = computed(
() => this.selectedVariant()?.precio ?? this.product()?.precio,
);
protected readonly quantity = signal(1);
protected readonly selectedVariantMax = computed<number | null>(() => {
const prod = this.product();
const variant = this.selectedVariant();
if (variant) return variant.stock_tecnico;
if (prod && prod.variants.length === 0) return prod.stock_tecnico ?? null;
return 0;
if (!prod) return 0;
const stockLimit = variant
? variant.stock_tecnico
: prod.variants.length === 0
? (prod.stock_tecnico ?? null)
: 0;
const userLimit = prod.max_units_per_user ?? null;
if (stockLimit === null) return userLimit;
if (userLimit === null) return stockLimit;
return Math.min(stockLimit, userLimit);
});
protected readonly selectedVariantAvailable = computed(() => {
const prod = this.product();
@@ -109,14 +124,8 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly descriptionMaxHeight = signal(0);
protected readonly descriptionHasOverflow = signal(false);
protected readonly renderableAttributes = computed(() =>
(this.product()?.attributes ?? []).filter(
(attribute) =>
attribute.options.length > 0 &&
!(this.product()?.purpose === 'entry' && attribute.codigo === 'fecha'),
),
(this.product()?.attributes ?? []).filter((attribute) => attribute.options.length > 0),
);
protected readonly eventDates = computed(() => this.product()?.event_dates ?? []);
protected readonly hasEventDates = computed(() => this.eventDates().length > 0);
protected readonly hasRenderableAttributes = computed(
() => this.renderableAttributes().length > 0,
);
@@ -130,6 +139,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.carouselHost();
this.descriptionBody();
this.product();
this.selectedVariant();
this.descriptionExpanded();
if (this.isBrowser) {
@@ -237,8 +247,11 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
this.selectedVariant.set(variant);
if (variant && variant.stock_tecnico !== null && this.quantity() > variant.stock_tecnico) {
this.quantity.set(Math.max(1, variant.stock_tecnico));
this.descriptionExpanded.set(false);
this.descriptionHasOverflow.set(false);
const maximum = this.selectedVariantMax();
if (maximum !== null && this.quantity() > maximum) {
this.quantity.set(Math.max(1, maximum));
}
const currentProduct = this.product();
@@ -247,12 +260,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
}
protected onEventDateChange(event: Event): void {
const variantId = Number((event.target as HTMLSelectElement).value);
const variant = this.product()?.variants.find((item) => item.id === variantId) ?? null;
this.onVariantChange(variant);
}
protected addToCart(): void {
const currentProduct = this.product();
const variant = this.selectedVariant();

View File

@@ -195,11 +195,9 @@ describe('StoreHomePageComponent', () => {
background_image_id: 'https://example.com/hero.jpg',
},
});
tenant.active_event_id = 10;
tenant.active_event = {
id: 10,
name: 'Fiesta Fútbol Infantil',
address: 'Rosario, Santa Fe',
tenant.event = {
title: 'Fiesta Fútbol Infantil',
location: 'Rosario, Santa Fe',
dates: [
{
id: 20,
@@ -331,11 +329,9 @@ describe('StoreHomePageComponent', () => {
it('renders only the active event data when the tenant does not have the hero extra', async () => {
const tenant = createTenant();
tenant.active_event_id = 12;
tenant.active_event = {
id: 12,
name: 'Fiesta Fútbol Infantil',
address: 'Sunchales, Santa Fe',
tenant.event = {
title: 'Fiesta Fútbol Infantil',
location: 'Sunchales, Santa Fe',
dates: [
{
id: 25,

View File

@@ -68,14 +68,14 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
protected readonly eventConfig = computed(() => {
const tenant = this.tenant();
const contact = tenant?.social_media ?? [];
const activeEvent = tenant?.active_event;
const event = tenant?.event;
if (activeEvent) {
if (event) {
return {
id: activeEvent.id,
title: activeEvent.name,
location: activeEvent.address,
dates: activeEvent.dates.map((eventDate) => ({
id: tenant.id,
title: event.title,
location: event.location,
dates: event.dates.map((eventDate) => ({
id: eventDate.id,
date: eventDate.date,
start_time: eventDate.time_start,

View File

@@ -109,6 +109,8 @@ export class ProductListComponent {
return (item.variants ?? []).map((variant) => ({
value: variant.id,
label: Object.values(variant.values).join(' / ') || `Variante ${variant.id}`,
descripcion: variant.descripcion,
precio: variant.precio,
}));
}

View File

@@ -6,9 +6,9 @@
<h3 class="product-row-card__title text-uppercase mb-1 m-0">
{{ title() }}
</h3>
@if (description()) {
@if (effectiveDescription()) {
<p class="product-row-card__description m-0 mt-1">
{{ description() }}
{{ effectiveDescription() }}
</p>
}
</div>

View File

@@ -14,6 +14,8 @@ import { QuantitySelectorComponent } from '../quantity-selector/quantity-selecto
export interface Variant {
label: string;
value: any;
descripcion?: string | null;
precio?: string | number;
}
@Component({
@@ -53,11 +55,20 @@ export class ProductRowCardComponent {
});
}
// Formatted string for price: "$ 10.000"
readonly formattedPrice = computed(() => {
return this.formatCurrency(this.price());
protected readonly selectedVariantData = computed(() =>
this.variants().find((variant) => Object.is(variant.value, this.selectedVariant())),
);
protected readonly effectiveDescription = computed(
() => this.selectedVariantData()?.descripcion ?? this.description(),
);
protected readonly effectivePrice = computed(() => {
const variantPrice = Number(this.selectedVariantData()?.precio);
return Number.isFinite(variantPrice) ? variantPrice : this.price();
});
readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected onAddToCart(): void {
this.addToCart.emit({
quantity: this.quantity(),

View File

@@ -2,8 +2,8 @@
<div class="product-vertical-with-cart-card__content">
<h3 class="product-vertical-with-cart-card__title">{{ title() }}</h3>
@if (description()) {
<p class="product-vertical-with-cart-card__description">{{ description() }}</p>
@if (effectiveDescription()) {
<p class="product-vertical-with-cart-card__description">{{ effectiveDescription() }}</p>
}
</div>

View File

@@ -177,4 +177,45 @@ describe('ProductVerticalWithCartCardComponent', () => {
expect(buySpy).toHaveBeenCalledWith({ quantity: 1, variant: 31 });
});
it('prioritizes the selected variant description and price', async () => {
const fixture = await createComponent('Descripción general');
fixture.componentRef.setInput('variants', [
{
id: 40,
descripcion: 'Almuerzo en comedor',
precio: '10000.00',
values: { servicio: 'Comedor' },
},
{
id: 41,
descripcion: 'Almuerzo en vianda',
precio: '8000.00',
values: { servicio: 'Vianda' },
},
]);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(
element.querySelector('.product-vertical-with-cart-card__description')?.textContent,
).toContain('Almuerzo en comedor');
expect(
element.querySelector('.product-vertical-with-cart-card__price')?.textContent?.trim(),
).toBe('$ 10.000');
const select = element.querySelector(
'.product-vertical-with-cart-card__variant-select',
) as HTMLSelectElement;
select.value = select.options[1].value;
select.dispatchEvent(new Event('change'));
fixture.detectChanges();
expect(
element.querySelector('.product-vertical-with-cart-card__description')?.textContent,
).toContain('Almuerzo en vianda');
expect(
element.querySelector('.product-vertical-with-cart-card__price')?.textContent?.trim(),
).toBe('$ 8.000');
});
});

View File

@@ -16,6 +16,8 @@ import { QuantitySelectorComponent } from '../quantity-selector/quantity-selecto
export interface VerticalCartVariant {
id: number;
descripcion?: string | null;
precio?: string | number;
values: Record<string, string>;
}
@@ -46,7 +48,18 @@ export class ProductVerticalWithCartCardComponent {
protected readonly selectedValues = signal<Record<string, string>>({});
protected readonly formattedPrice = computed(() => this.formatCurrency(this.price()));
protected readonly selectedVariantData = computed(() =>
this.variants().find((variant) => variant.id === this.selectedVariant()),
);
protected readonly effectiveDescription = computed(
() => this.selectedVariantData()?.descripcion ?? this.description(),
);
protected readonly effectivePrice = computed(() => {
const variantPrice = Number(this.selectedVariantData()?.precio);
return Number.isFinite(variantPrice) ? variantPrice : this.price();
});
protected readonly formattedPrice = computed(() => this.formatCurrency(this.effectivePrice()));
protected readonly variantSelectors = computed<VariantSelector[]>(() => {
const variants = this.variants();
const keys = Array.from(new Set(variants.flatMap((variant) => Object.keys(variant.values))));