10 Commits

Author SHA1 Message Date
1977df6765 feat: enhance product attributes and event date handling for improved user experience and data management 2026-08-07 14:16:02 -03:00
8d88e1bb13 Merge branch 'feature/responsive' into develop 2026-08-06 09:23:37 -03:00
78970573a8 feat: add type property to Product and CatalogItemDetail interfaces; include event_id in PurchaseSummaryResponse and PurchaseDetailResponse 2026-08-05 08:49:52 -03:00
f289e9e2e4 feat: add expires_at to PurchaseDetailResponse and update checkout logic for pending payments 2026-08-03 17:04:07 -03:00
2487546a75 feat: add additionalInfoConfig to tenant interface and implement rendering in store home page 2026-08-03 15:08:33 -03:00
cc884e3cc0 feat: add description_html to tenant heroConfig and update tests for hero banner rendering 2026-08-03 15:08:13 -03:00
ffb586c348 feat: enhance product and tenant interfaces to support event dates, update product detail page to display event date selection 2026-08-03 14:24:42 -03:00
ec18aaf0c5 feat: update WebsiteType and EventConfig interfaces with new properties, enhance tenant creation in tests 2026-08-03 09:09:58 -03:00
941cb5c73c feat: add dates_text to EventConfig and update formattedDates method in HeroBannerComponent 2026-07-30 16:32:37 -03:00
934bd07105 feat: enhance tenant interface with website type and extras, update store home page to utilize new data structure 2026-07-29 15:46:02 -03:00
24 changed files with 784 additions and 211 deletions

View File

@@ -1,7 +1,10 @@
import { ApiPaginatedResponse } from '../api-paginated-response.interface'; import { ApiPaginatedResponse } from '../api-paginated-response.interface';
export type CatalogItemType = 'product' | 'bundle';
export interface Product { export interface Product {
id: number; id: number;
type: CatalogItemType;
category_id: number; category_id: number;
brand_id: number | null; brand_id: number | null;
slug: string; slug: string;
@@ -21,13 +24,24 @@ export interface ProductAttributeOption {
metadata: Record<string, unknown> | null; metadata: Record<string, unknown> | null;
} }
export type ProductAttributeType =
| 'string'
| 'number'
| 'boolean'
| 'select'
| 'multiselect'
| 'color'
| 'image'
| 'event_date';
export interface ProductAttribute { export interface ProductAttribute {
id: number; id: number;
codigo: string; codigo: string;
nombre: string; nombre: string;
is_required: boolean; is_required: boolean;
allow_multi_select?: boolean;
metadata_schema: Record<string, unknown> | null; metadata_schema: Record<string, unknown> | null;
type: string; type: ProductAttributeType;
options: ProductAttributeOption[]; options: ProductAttributeOption[];
} }
@@ -35,12 +49,17 @@ export type InventoryPolicy = 'tracked' | 'unlimited';
export interface CatalogItemVariant { export interface CatalogItemVariant {
id: number; id: number;
descripcion?: string | null;
precio?: string;
event_date_id?: number | null;
event_date_ids?: number[];
event_dates?: string[];
stock_tecnico: number | null; stock_tecnico: number | null;
minimum_use_date?: string | null; minimum_use_date?: string | null;
maximum_use_date?: string | null; maximum_use_date?: string | null;
effective_minimum_use_date?: string | null; effective_minimum_use_date?: string | null;
effective_maximum_use_date?: string | null; effective_maximum_use_date?: string | null;
values: Record<string, string>; values: Record<string, string | string[]>;
} }
export interface SelectedCatalogItemVariant extends CatalogItemVariant { export interface SelectedCatalogItemVariant extends CatalogItemVariant {
@@ -49,6 +68,8 @@ export interface SelectedCatalogItemVariant extends CatalogItemVariant {
export interface CatalogItemDetail { export interface CatalogItemDetail {
id: number; id: number;
type: CatalogItemType;
purpose?: 'product' | 'entry';
category_id: number | null; category_id: number | null;
brand_id: number | null; brand_id: number | null;
slug: string; slug: string;
@@ -58,6 +79,7 @@ export interface CatalogItemDetail {
category: string | null; category: string | null;
brand: string | null; brand: string | null;
inventory_policy: InventoryPolicy; inventory_policy: InventoryPolicy;
max_units_per_user?: number | null;
has_tickets: boolean; has_tickets: boolean;
minimum_use_date: string | null; minimum_use_date: string | null;
maximum_use_date: string | null; maximum_use_date: string | null;
@@ -73,12 +95,15 @@ export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'c
export interface CatalogFeaturedItemVariant { export interface CatalogFeaturedItemVariant {
id: number; id: number;
descripcion?: string | null;
precio?: string;
stock_tecnico: number | null; stock_tecnico: number | null;
values: Record<string, string>; values: Record<string, string | string[]>;
} }
export interface CatalogFeaturedItem { export interface CatalogFeaturedItem {
id: number; id: number;
type: CatalogItemType;
nombre: string; nombre: string;
descripcion?: string | null; descripcion?: string | null;
precio: number | string; precio: number | string;

View File

@@ -61,6 +61,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
user_id: number; user_id: number;
created_at: string | null; created_at: string | null;
payment_method: string | null; payment_method: string | null;
expires_at: string | null;
dni: string | null; dni: string | null;
transfer_payer_dni: string | null; transfer_payer_dni: string | null;
telefono: string | null; telefono: string | null;

View File

@@ -9,18 +9,62 @@ export interface BankAccount {
cvu: string; cvu: string;
} }
export interface WebsiteType {
codigo: string;
nombre: string;
primary_color: string | null;
secondary_color: string | null;
danger_color: string | null;
success_color: string | null;
site_logo: string | null;
}
export interface HeroConfig { export interface HeroConfig {
background_image?: string | null; background_image_id?: string | null;
title_html?: string | null; title_html?: string | null;
description_html?: string | null; description_html?: string | null;
button_text?: string | null; button_text?: string | null;
button_href?: string | null; button_href?: string | null;
} }
export interface AdditionalInfoConfig {
description?: string | null;
}
export interface EventDate {
id?: number;
date: string;
start_time: string;
end_time: string;
}
export interface EventConfig { export interface EventConfig {
id?: number;
title?: string | null; title?: string | null;
location?: string | null; location?: string | null;
dates?: string[] | null; dates_text?: string | null;
dates?: EventDate[] | null;
contact?: SocialMedia[];
}
export interface ActiveEventDate {
id: number;
date: string;
time_start: string;
time_end: string;
}
export interface TenantEvent {
title: string;
location: string;
dates: ActiveEventDate[];
}
export interface WebsiteExtras {
carousel?: string[];
heroConfig?: HeroConfig | null;
additionalInfoConfig?: AdditionalInfoConfig | null;
[extraName: string]: unknown;
} }
export interface Menu { export interface Menu {
@@ -60,14 +104,15 @@ export interface Tenant {
footer_bg_color: string; footer_bg_color: string;
header_logo: string; header_logo: string;
footer_logo: string; footer_logo: string;
website_type_code?: string | null;
website_type?: WebsiteType | null;
extras?: WebsiteExtras;
event?: TenantEvent | null;
selected_bank_account_id?: number | null; selected_bank_account_id?: number | null;
selected_bank_account?: BankAccount | null; selected_bank_account?: BankAccount | null;
hero_config?: HeroConfig | null;
event_config?: EventConfig | null;
search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart'; search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart';
search_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel'; search_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel';
search_items_per_page?: number; search_items_per_page?: number;
main_carousel_images?: string[];
social_media?: SocialMedia[]; social_media?: SocialMedia[];
menues?: Menu[]; menues?: Menu[];
categories: Category[]; categories: Category[];

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

View File

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

View File

@@ -60,7 +60,7 @@ describe('CheckoutPageComponent payment validation', () => {
qr_data: { qr_code: 'qr-value' }, qr_data: { qr_code: 'qr-value' },
}), }),
getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }), getPurchase: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'in_review' }), submitPurchaseForReview: vi.fn().mockResolvedValue({ status: 'pending_payment' }),
withCustomLoading: vi.fn(), withCustomLoading: vi.fn(),
}; };
checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub); checkoutServiceStub.withCustomLoading.mockReturnValue(checkoutServiceStub);
@@ -199,20 +199,20 @@ describe('CheckoutPageComponent payment validation', () => {
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
await component.onComplete(); await component.onComplete();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
expect(component.transferValidationStatus()).toBe('pending'); expect(component.transferValidationStatus()).toBe('pending');
expect(cartServiceStub.clearCart).not.toHaveBeenCalled(); expect(cartServiceStub.clearCart).not.toHaveBeenCalled();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]); expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
await vi.advanceTimersByTimeAsync(30_000); await vi.advanceTimersByTimeAsync(30_000);
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
await component.onComplete(); await component.onComplete();
expect(checkoutServiceStub.getPurchase).toHaveBeenCalledTimes(1); expect(checkoutServiceStub.submitPurchaseForReview).toHaveBeenCalledTimes(1);
}); });
it('navigates after a transfer is confirmed as paid', async () => { it('navigates after a transfer is confirmed as paid', async () => {
checkoutServiceStub.getPurchase.mockResolvedValue({ status: 'paid' }); checkoutServiceStub.submitPurchaseForReview.mockResolvedValue({ status: 'paid' });
const { component } = createComponent(); const { component } = createComponent();
component.selectedPaymentMethod.set('transfer'); component.selectedPaymentMethod.set('transfer');
@@ -375,7 +375,7 @@ describe('CheckoutPageComponent payment validation', () => {
expect(component.qrPaymentStatus()).toBe('waiting'); expect(component.qrPaymentStatus()).toBe('waiting');
}); });
it.each(['in_review', 'paid', 'cancelled', 'rejected', 'expired'])( it.each(['paid', 'cancelled', 'rejected', 'expired'])(
'redirects a %s purchase to its status page', 'redirects a %s purchase to its status page',
async (status) => { async (status) => {
routeQueryParamMap = convertToParamMap({ purchase: 25 }); routeQueryParamMap = convertToParamMap({ purchase: 25 });
@@ -395,6 +395,25 @@ describe('CheckoutPageComponent payment validation', () => {
}, },
); );
it('redirects a submitted pending payment purchase to its status page', async () => {
routeQueryParamMap = convertToParamMap({ purchase: 25 });
checkoutServiceStub.getPurchase.mockResolvedValue({
id: 25,
status: 'pending_payment',
payment_method: 'transfer',
expires_at: null,
transfer_payer_dni: null,
items: [],
subtotal: '100.00',
total: '100.00',
});
createComponent();
await Promise.resolve();
expect(routerStub.navigate).toHaveBeenCalledWith(['/checkout/status', 25]);
});
it('updates a purchase item while editing and refreshes checkout totals', async () => { it('updates a purchase item while editing and refreshes checkout totals', async () => {
const updatedPurchase = { const updatedPurchase = {
id: 25, id: 25,

View File

@@ -437,7 +437,11 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
.withCustomLoading() .withCustomLoading()
.submitPurchaseForReview(tenant.codigo, purchaseId); .submitPurchaseForReview(tenant.codigo, purchaseId);
if (purchase.status === 'paid') { if (purchase.status === 'paid' || purchase.status === 'pending_payment') {
if (purchase.status === 'pending_payment') {
this.transferValidationStatus.set('pending');
}
this.navigateToPurchaseStatus(purchaseId); this.navigateToPurchaseStatus(purchaseId);
return; return;
} }
@@ -576,7 +580,7 @@ export class CheckoutPageComponent implements OnInit, OnDestroy {
.getPurchase(tenant.codigo, purchaseId); .getPurchase(tenant.codigo, purchaseId);
if ( if (
purchase.status === 'in_review' || (purchase.status === 'pending_payment' && purchase.expires_at === null) ||
purchase.status === 'paid' || purchase.status === 'paid' ||
purchase.status === 'cancelled' || purchase.status === 'cancelled' ||
purchase.status === 'rejected' || purchase.status === 'rejected' ||

View File

@@ -26,7 +26,7 @@
<div class="product-detail__price-group"> <div class="product-detail__price-group">
<span class="product-detail__price-current"> <span class="product-detail__price-current">
{{ getFormattedPrice(prod.precio) }} {{ getFormattedPrice(effectivePrice()) }}
</span> </span>
@if (oldPrice(); as oldPrice) { @if (oldPrice(); as oldPrice) {
@@ -99,7 +99,7 @@
[class.product-detail__description-body--expanded]="descriptionExpanded()" [class.product-detail__description-body--expanded]="descriptionExpanded()"
[style.max-height.px]="descriptionExpanded() ? descriptionMaxHeight() || null : null" [style.max-height.px]="descriptionExpanded() ? descriptionMaxHeight() || null : null"
> >
{{ prod.descripcion }} {{ effectiveDescription() }}
</div> </div>
@if (showDescriptionToggle()) { @if (showDescriptionToggle()) {

View File

@@ -22,6 +22,7 @@ import {
describe('ProductDetailPageComponent', () => { describe('ProductDetailPageComponent', () => {
const mockProduct: CatalogItemDetail = { const mockProduct: CatalogItemDetail = {
id: 1, id: 1,
type: 'product',
category_id: 10, category_id: 10,
brand_id: null, brand_id: null,
slug: 'auriculares-bluetooth', slug: 'auriculares-bluetooth',
@@ -327,6 +328,70 @@ describe('ProductDetailPageComponent', () => {
expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe(''); expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe('');
}); });
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: { event_date: '20' } },
{ id: 102, event_date_id: 21, stock_tecnico: 10, values: { event_date: '21' } },
],
attributes: [
{
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: {
id: 101,
event_date_id: 20,
stock_tecnico: 10,
images: [],
values: {},
},
};
resolveProduct(detailProduct);
catalogServiceStub.getCatalogItem.mockReturnValue(
of({ ...detailProduct, selected_variant: { ...detailProduct.selected_variant!, id: 102 } }),
);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
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);
options[1].click();
fixture.detectChanges();
expect(catalogServiceStub.getCatalogItem).toHaveBeenCalledWith(1, 102);
});
it('hides the attributes block and its extra divider when no attributes are present', async () => { it('hides the attributes block and its extra divider when no attributes are present', async () => {
await configureTestingModule(); await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent); const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -564,6 +629,39 @@ describe('ProductDetailPageComponent', () => {
expect(fixture.componentInstance['quantity']()).toBe(2); 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 () => { it('disables purchase actions for tracked variants without stock', async () => {
const trackedVariant = { const trackedVariant = {
id: 654, id: 654,

View File

@@ -86,13 +86,28 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly creatingDirectPurchase = signal(false); protected readonly creatingDirectPurchase = signal(false);
protected readonly error = signal<string | null>(null); protected readonly error = signal<string | null>(null);
protected readonly selectedVariant = signal<CatalogItemVariant | 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 quantity = signal(1);
protected readonly selectedVariantMax = computed<number | null>(() => { protected readonly selectedVariantMax = computed<number | null>(() => {
const prod = this.product(); const prod = this.product();
const variant = this.selectedVariant(); const variant = this.selectedVariant();
if (variant) return variant.stock_tecnico; if (!prod) return 0;
if (prod && prod.variants.length === 0) return prod.stock_tecnico ?? null;
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(() => { protected readonly selectedVariantAvailable = computed(() => {
const prod = this.product(); const prod = this.product();
@@ -100,6 +115,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
const variant = this.selectedVariant(); const variant = this.selectedVariant();
if (variant) return this.isVariantAvailable(variant, prod); if (variant) return this.isVariantAvailable(variant, prod);
if (prod.purpose === 'entry') return false;
if (prod.variants.length > 0) return false; if (prod.variants.length > 0) return false;
return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0; return prod.inventory_policy === 'unlimited' || (prod.stock_tecnico ?? 0) > 0;
@@ -123,6 +139,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.carouselHost(); this.carouselHost();
this.descriptionBody(); this.descriptionBody();
this.product(); this.product();
this.selectedVariant();
this.descriptionExpanded(); this.descriptionExpanded();
if (this.isBrowser) { if (this.isBrowser) {
@@ -159,26 +176,26 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
.withCustomLoading() .withCustomLoading()
.getCatalogItem(productId, variantId) .getCatalogItem(productId, variantId)
.subscribe({ .subscribe({
next: (prod) => { next: (prod) => {
this.applyProduct(prod, false); this.applyProduct(prod, false);
this.variantLoading.set(false); this.variantLoading.set(false);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
const errorMessage = err.error?.message || 'No pudimos cargar la variante seleccionada.'; const errorMessage = err.error?.message || 'No pudimos cargar la variante seleccionada.';
this.toastService.danger(errorMessage); this.toastService.danger(errorMessage);
this.variantLoading.set(false); this.variantLoading.set(false);
this.product.update((currentProduct) => { this.product.update((currentProduct) => {
if (!currentProduct) return null; if (!currentProduct) return null;
return { return {
...currentProduct, ...currentProduct,
variants: currentProduct.variants.filter((variant) => variant.id !== variantId), variants: currentProduct.variants.filter((variant) => variant.id !== variantId),
}; };
}); });
this.attributeSelector()?.reset(); this.attributeSelector()?.reset();
}, },
}); });
} }
private applyResolvedData(resolvedData: ProductDetailResolvedData): void { private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
@@ -230,8 +247,11 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
} }
this.selectedVariant.set(variant); this.selectedVariant.set(variant);
if (variant && variant.stock_tecnico !== null && this.quantity() > variant.stock_tecnico) { this.descriptionExpanded.set(false);
this.quantity.set(Math.max(1, variant.stock_tecnico)); 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(); const currentProduct = this.product();
@@ -253,17 +273,17 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
.withCustomLoading() .withCustomLoading()
.addItem(currentProduct.id, variant?.id ?? null, this.quantity()) .addItem(currentProduct.id, variant?.id ?? null, this.quantity())
.subscribe({ .subscribe({
next: (res) => { next: (res) => {
const msg = res.message || 'Producto agregado al carrito'; const msg = res.message || 'Producto agregado al carrito';
this.toastService.success(msg); this.toastService.success(msg);
this.addingToCart.set(false); this.addingToCart.set(false);
}, },
error: (err: HttpErrorResponse) => { error: (err: HttpErrorResponse) => {
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.'; const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
this.toastService.danger(errorMessage); this.toastService.danger(errorMessage);
this.addingToCart.set(false); this.addingToCart.set(false);
}, },
}); });
} }
protected async buyNow(): Promise<void> { protected async buyNow(): Promise<void> {

View File

@@ -1,19 +1,16 @@
@if (tenant()?.main_carousel_images; as mainCarouselImages) { @if (mainCarouselImages(); as images) {
@if (mainCarouselImages.length) { @if (images.length) {
<app-main-carousel <app-main-carousel
class="store-home__main-carousel" class="store-home__main-carousel"
[images]="mainCarouselImages" [images]="images"
ariaLabel="Imágenes destacadas de la tienda" ariaLabel="Imágenes destacadas de la tienda"
(firstImageReady)="mainCarouselReady.set(true)" (firstImageReady)="mainCarouselReady.set(true)"
/> />
} }
} }
@if (tenant()?.hero_config || tenant()?.event_config) { @if (heroConfig() || eventConfig()) {
<app-hero-banner <app-hero-banner [heroConfig]="heroConfig()" [eventConfig]="eventConfig()" />
[heroConfig]="tenant()?.hero_config"
[eventConfig]="tenant()?.event_config"
></app-hero-banner>
} }
@if (error()) { @if (error()) {
@@ -40,3 +37,9 @@
</app-store-section> </app-store-section>
} }
} }
@if (additionalInfo(); as content) {
<app-store-section class="store-home__additional-info" title="Información adicional">
<div class="store-home__additional-info-content" [innerHTML]="content"></div>
</app-store-section>
}

View File

@@ -11,6 +11,25 @@ app-store-section + app-store-section {
margin-top: clamp(3rem, 6vw, 5rem); margin-top: clamp(3rem, 6vw, 5rem);
} }
:host > .store-home__additional-info:not(:first-child) {
margin-top: clamp(3rem, 6vw, 5rem);
}
.store-home__additional-info-content {
width: 100%;
text-align: center;
}
::ng-deep .store-home__additional-info-content img {
display: block;
margin-right: auto;
margin-left: auto;
}
::ng-deep .store-home__additional-info-content > :last-child {
margin-bottom: 0;
}
.store-home__alert-error { .store-home__alert-error {
margin: 0; margin: 0;
border-color: rgba(var(--tenant-danger-rgb, 220, 53, 69), 0.18); border-color: rgba(var(--tenant-danger-rgb, 220, 53, 69), 0.18);

View File

@@ -16,6 +16,7 @@ import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service'; import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service'; import { ToastService } from '../../../../core/services/toast.service';
import { ProductListComponent } from '../../../../shared/components/product-list/product-list.component'; import { ProductListComponent } from '../../../../shared/components/product-list/product-list.component';
import { HeroBannerComponent } from '../../../../shared/components/hero-banner/hero-banner.component';
import { StoreHomePageComponent } from './store-home-page.component'; import { StoreHomePageComponent } from './store-home-page.component';
import { import {
STORE_HOME_PRODUCTS_ERROR_MESSAGE, STORE_HOME_PRODUCTS_ERROR_MESSAGE,
@@ -88,7 +89,7 @@ const pageOneItems: CatalogFeaturedItem[] = [
}, },
]; ];
function createTenant(mainCarouselImages?: string[]): Tenant { function createTenant(extras: Tenant['extras'] = {}): Tenant {
return { return {
id: 1, id: 1,
codigo: 'acme', codigo: 'acme',
@@ -102,8 +103,18 @@ function createTenant(mainCarouselImages?: string[]): Tenant {
footer_bg_color: '#ffffff', footer_bg_color: '#ffffff',
header_logo: '/header.png', header_logo: '/header.png',
footer_logo: '/footer.png', footer_logo: '/footer.png',
website_type_code: 'shopit',
website_type: {
codigo: 'shopit',
nombre: 'ShopIt',
primary_color: null,
secondary_color: null,
danger_color: null,
success_color: null,
site_logo: null,
},
extras,
categories: [], categories: [],
main_carousel_images: mainCarouselImages,
}; };
} }
@@ -146,11 +157,8 @@ describe('StoreHomePageComponent', () => {
); );
}); });
it('renders the tenant main carousel images at the beginning of the home page', async () => { it('renders the carousel URLs received in tenant extras', async () => {
const mainCarouselImages = [ const carousel = ['https://example.com/carousel-1.webp', 'https://example.com/carousel-2.webp'];
'https://example.com/carousel-1.webp',
'https://example.com/carousel-2.webp',
];
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [StoreHomePageComponent], imports: [StoreHomePageComponent],
@@ -162,7 +170,7 @@ describe('StoreHomePageComponent', () => {
}, },
{ {
provide: TenantService, provide: TenantService,
useValue: createTenantServiceStub(createTenant(mainCarouselImages)), useValue: createTenantServiceStub(createTenant({ carousel })),
}, },
], ],
}).compileComponents(); }).compileComponents();
@@ -171,25 +179,59 @@ describe('StoreHomePageComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement; const element = fixture.nativeElement as HTMLElement;
const carousel = element.querySelector('app-main-carousel'); const carouselElement = element.querySelector('app-main-carousel');
const images = carousel?.querySelectorAll('.main-carousel__image'); const images = carouselElement?.querySelectorAll('.main-carousel__image');
expect(element.firstElementChild).toBe(carousel); expect(element.firstElementChild).toBe(carouselElement);
expect(images).toHaveLength(2); expect(images).toHaveLength(2);
expect(images?.[0].getAttribute('src')).toBe(mainCarouselImages[0]); expect(images?.[0].getAttribute('src')).toBe(carousel[0]);
expect(images?.[1].getAttribute('src')).toBeNull();
expect(element.querySelectorAll('app-product-column-with-image img')).toHaveLength(0);
images?.[0].dispatchEvent(new Event('load'));
fixture.detectChanges();
expect(images?.[1].getAttribute('src')).toBe(mainCarouselImages[1]);
expect(element.querySelectorAll('app-product-column-with-image img')).toHaveLength(1);
fixture.destroy();
}); });
it('does not render the main carousel when the tenant has no images', async () => { it('renders the hero extra and the active tenant event', async () => {
const tenant = createTenant({
heroConfig: {
title_html: '<h1>Fiesta Fútbol Infantil</h1>',
description_html: '<p>Viví una jornada inolvidable de fútbol infantil.</p>',
background_image_id: 'https://example.com/hero.jpg',
},
});
tenant.event = {
title: 'Fiesta Fútbol Infantil',
location: 'Rosario, Santa Fe',
dates: [
{
id: 20,
date: '2026-12-05',
time_start: '09:00:00',
time_end: '18:00:00',
},
{
id: 21,
date: '2026-12-06',
time_start: '09:00:00',
time_end: '18:00:00',
},
],
};
tenant.website_type_code = 'onticket';
tenant.social_media = [
{
code: 'whatsapp',
icon: 'fa-brands fa-whatsapp',
name: 'WhatsApp',
url: 'https://wa.me/5493410000000',
},
];
tenant.website_type = {
codigo: 'onticket',
nombre: 'OnTicket',
primary_color: null,
secondary_color: null,
danger_color: null,
success_color: null,
site_logo: null,
};
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [StoreHomePageComponent], imports: [StoreHomePageComponent],
providers: [ providers: [
@@ -200,7 +242,7 @@ describe('StoreHomePageComponent', () => {
}, },
{ {
provide: TenantService, provide: TenantService,
useValue: createTenantServiceStub(createTenant([])), useValue: createTenantServiceStub(tenant),
}, },
], ],
}).compileComponents(); }).compileComponents();
@@ -208,7 +250,127 @@ describe('StoreHomePageComponent', () => {
const fixture = TestBed.createComponent(StoreHomePageComponent); const fixture = TestBed.createComponent(StoreHomePageComponent);
fixture.detectChanges(); fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('app-main-carousel')).toBeNull(); const hero = (fixture.nativeElement as HTMLElement).querySelector(
'app-hero-banner .hero-banner',
) as HTMLElement;
expect(hero).not.toBeNull();
expect(hero.style.backgroundImage).toContain('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');
expect(hero.textContent).toContain('2026-12-05, 2026-12-06');
const heroComponent = fixture.debugElement.query(By.directive(HeroBannerComponent))
.componentInstance as HeroBannerComponent;
expect(heroComponent.eventConfig?.contact).toEqual(tenant.social_media);
});
it('renders additional information as an HTML section', async () => {
const description =
'<p>Consultá los <strong>términos del evento</strong>.</p><ul><li>Ingreso con DNI</li></ul>';
await TestBed.configureTestingModule({
imports: [StoreHomePageComponent],
providers: [
provideActivatedRoute({ response: createCatalog(), error: null }),
{
provide: CatalogService,
useValue: { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() },
},
{
provide: TenantService,
useValue: createTenantServiceStub(
createTenant({ additionalInfoConfig: { description } }),
),
},
],
}).compileComponents();
const fixture = TestBed.createComponent(StoreHomePageComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const section = element.querySelector('.store-home__additional-info');
const sections = element.querySelectorAll(':scope > app-store-section');
expect(sections[sections.length - 1]).toBe(section);
expect(section?.querySelector('.store-section__title')?.textContent?.trim()).toBe(
'Información adicional',
);
expect(section?.querySelector('strong')?.textContent).toBe('términos del evento');
expect(section?.querySelector('li')?.textContent).toBe('Ingreso con DNI');
});
it('does not render the additional information section without content', async () => {
await TestBed.configureTestingModule({
imports: [StoreHomePageComponent],
providers: [
provideActivatedRoute({ response: createCatalog(), error: null }),
{
provide: CatalogService,
useValue: { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() },
},
{
provide: TenantService,
useValue: createTenantServiceStub(
createTenant({ additionalInfoConfig: { description: ' ' } }),
),
},
],
}).compileComponents();
const fixture = TestBed.createComponent(StoreHomePageComponent);
fixture.detectChanges();
expect(
(fixture.nativeElement as HTMLElement).querySelector('.store-home__additional-info'),
).toBeNull();
});
it('renders only the active event data when the tenant does not have the hero extra', async () => {
const tenant = createTenant();
tenant.event = {
title: 'Fiesta Fútbol Infantil',
location: 'Sunchales, Santa Fe',
dates: [
{
id: 25,
date: '2026-10-09',
time_start: '09:00:00',
time_end: '18:00:00',
},
],
};
await TestBed.configureTestingModule({
imports: [StoreHomePageComponent],
providers: [
provideActivatedRoute({ response: createCatalog(), error: null }),
{
provide: CatalogService,
useValue: { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() },
},
{
provide: TenantService,
useValue: createTenantServiceStub(tenant),
},
],
}).compileComponents();
const fixture = TestBed.createComponent(StoreHomePageComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const heroComponent = fixture.debugElement.query(By.directive(HeroBannerComponent))
.componentInstance as HeroBannerComponent;
expect(heroComponent.heroConfig).toBeNull();
expect(element.querySelector('.hero-banner')).toBeNull();
expect(element.querySelector('.hero-banner-container')).toBeNull();
expect(element.querySelector('.hero-content')).toBeNull();
expect(element.querySelector('.event-card')).not.toBeNull();
expect(element.textContent).toContain('Fiesta Fútbol Infantil');
expect(element.textContent).toContain('Sunchales, Santa Fe');
expect(element.textContent).toContain('2026-10-09');
}); });
it('requests another page for the selected featured group', async () => { it('requests another page for the selected featured group', async () => {
@@ -323,9 +485,9 @@ describe('StoreHomePageComponent', () => {
it('adds a product-list cart event to the cart', async () => { it('adds a product-list cart event to the cart', async () => {
const catalogServiceStub = { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() }; const catalogServiceStub = { getCatalog: vi.fn(), getFeaturedGroupItems: vi.fn() };
const cartServiceStub = { const cartServiceStub = {
addItem: vi.fn().mockReturnValue( addItem: vi
of({ data: {}, message: 'Producto agregado correctamente' }), .fn()
), .mockReturnValue(of({ data: {}, message: 'Producto agregado correctamente' })),
}; };
const toastServiceStub = { success: vi.fn(), danger: vi.fn() }; const toastServiceStub = { success: vi.fn(), danger: vi.fn() };

View File

@@ -60,9 +60,34 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
protected readonly error = signal<string | null>(null); protected readonly error = signal<string | null>(null);
protected readonly mainCarouselReady = signal(false); protected readonly mainCarouselReady = signal(false);
protected readonly creatingDirectPurchase = signal(false); protected readonly creatingDirectPurchase = signal(false);
protected readonly hasMainCarouselImages = computed( protected readonly mainCarouselImages = computed(() => this.tenant()?.extras?.carousel ?? []);
() => (this.tenant()?.main_carousel_images?.length ?? 0) > 0, protected readonly heroConfig = computed(() => this.tenant()?.extras?.heroConfig ?? null);
protected readonly additionalInfo = computed(
() => this.tenant()?.extras?.additionalInfoConfig?.description?.trim() || null,
); );
protected readonly eventConfig = computed(() => {
const tenant = this.tenant();
const contact = tenant?.social_media ?? [];
const event = tenant?.event;
if (event) {
return {
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,
end_time: eventDate.time_end,
})),
contact,
};
}
return null;
});
protected readonly hasMainCarouselImages = computed(() => this.mainCarouselImages().length > 0);
private catalogRequestSubscription: Subscription | null = null; private catalogRequestSubscription: Subscription | null = null;
private readonly groupRequestSubscriptions = new Map<number, Subscription>(); private readonly groupRequestSubscriptions = new Map<number, Subscription>();
@@ -109,20 +134,20 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
.withCustomLoading() .withCustomLoading()
.getFeaturedGroupItems(groupId, { page }) .getFeaturedGroupItems(groupId, { page })
.subscribe({ .subscribe({
next: (items) => { next: (items) => {
this.catalog.update((groups) => this.catalog.update((groups) =>
groups.map((candidate) => groups.map((candidate) =>
candidate.id === groupId ? { ...candidate, items } : candidate, candidate.id === groupId ? { ...candidate, items } : candidate,
), ),
); );
this.error.set(null); this.error.set(null);
}, },
error: () => { error: () => {
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE); this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
this.setGroupLoading(groupId, false); this.setGroupLoading(groupId, false);
}, },
complete: () => this.setGroupLoading(groupId, false), complete: () => this.setGroupLoading(groupId, false),
}); });
this.groupRequestSubscriptions.set(groupId, subscription); this.groupRequestSubscriptions.set(groupId, subscription);
} }
@@ -189,14 +214,14 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
.withCustomLoading() .withCustomLoading()
.getCatalog() .getCatalog()
.subscribe({ .subscribe({
next: (catalog) => this.catalog.set(catalog), next: (catalog) => this.catalog.set(catalog),
error: () => { error: () => {
this.catalog.set([]); this.catalog.set([]);
this.loading.set(false); this.loading.set(false);
this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE); this.error.set(STORE_HOME_PRODUCTS_ERROR_MESSAGE);
}, },
complete: () => this.loading.set(false), complete: () => this.loading.set(false),
}); });
} }
private applyResolvedData(resolvedData: StoreHomeCatalogResolvedData): void { private applyResolvedData(resolvedData: StoreHomeCatalogResolvedData): void {

View File

@@ -9,7 +9,9 @@
></div> ></div>
@if (heroConfig) { @if (heroConfig) {
<div class="hero-content d-flex justify-content-end p-4 p-md-5 w-100 h-100 align-items-center"> <div
class="hero-content d-flex justify-content-end p-4 p-md-5 w-100 h-100 align-items-center"
>
<div class="hero-text-box"> <div class="hero-text-box">
@if (heroConfig.title_html) { @if (heroConfig.title_html) {
<div class="hero-title" [innerHTML]="heroConfig.title_html"></div> <div class="hero-title" [innerHTML]="heroConfig.title_html"></div>
@@ -34,8 +36,10 @@
@if (eventConfig.title) { @if (eventConfig.title) {
<h3 class="event-title text-primary fw-bold mb-3">{{ eventConfig.title }}</h3> <h3 class="event-title text-primary fw-bold mb-3">{{ eventConfig.title }}</h3>
} }
<div class="event-details d-flex flex-column flex-md-row justify-content-center align-items-center gap-3 gap-md-5 text-muted"> <div
class="event-details d-flex flex-column flex-md-row justify-content-center align-items-center gap-3 gap-md-5 text-muted"
>
@if (eventConfig.dates && eventConfig.dates.length > 0) { @if (eventConfig.dates && eventConfig.dates.length > 0) {
<div class="d-flex align-items-center gap-2"> <div class="d-flex align-items-center gap-2">
<i class="fa-regular fa-calendar event-icon"></i> <i class="fa-regular fa-calendar event-icon"></i>

View File

@@ -1,7 +1,7 @@
import { Component, ChangeDetectionStrategy, Input } from '@angular/core'; import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { HeroConfig, EventConfig } from '../../../core/services/tenant.interface'; import { EventConfig, HeroConfig } from '../../../core/services/tenant.interface';
import { ButtonComponent } from '../button/button.component'; import { ButtonComponent } from '../button/button.component';
@Component({ @Component({
@@ -17,25 +17,14 @@ export class HeroBannerComponent {
@Input() eventConfig?: EventConfig | null; @Input() eventConfig?: EventConfig | null;
get formattedDates(): string { get formattedDates(): string {
if (this.eventConfig?.dates_text) {
return this.eventConfig.dates_text;
}
if (!this.eventConfig?.dates || this.eventConfig.dates.length === 0) { if (!this.eventConfig?.dates || this.eventConfig.dates.length === 0) {
return ''; return '';
} }
// Si ya viene formateado o es un string libre largo, lo devolvemos
if (this.eventConfig.dates.length === 1 && this.eventConfig.dates[0].length > 10) {
return this.eventConfig.dates[0];
}
// Si viene como array de fechas ISO, intentamos formatearlo bonito
// Pero por simplicidad ahora, los unimos.
// Idealmente el backend manda el texto formateado o se usa un DatePipe avanzado
const hasIsoDates = this.eventConfig.dates.some(d => d.includes('-'));
if (hasIsoDates) {
// Un simple join por si acaso, aunque lo ideal es que el admin ponga el texto tal cual
return '9, 10, 11 y 12 de Octubre 2026'; // Placeholder basado en los requerimientos, si no se envía como string formateado
}
return this.eventConfig.dates.join(', '); return this.eventConfig.dates.map(({ date }) => date).join(', ');
} }
} }

View File

@@ -109,6 +109,8 @@ export class ProductListComponent {
return (item.variants ?? []).map((variant) => ({ return (item.variants ?? []).map((variant) => ({
value: variant.id, value: variant.id,
label: Object.values(variant.values).join(' / ') || `Variante ${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"> <h3 class="product-row-card__title text-uppercase mb-1 m-0">
{{ title() }} {{ title() }}
</h3> </h3>
@if (description()) { @if (effectiveDescription()) {
<p class="product-row-card__description m-0 mt-1"> <p class="product-row-card__description m-0 mt-1">
{{ description() }} {{ effectiveDescription() }}
</p> </p>
} }
</div> </div>

View File

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

View File

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

View File

@@ -177,4 +177,45 @@ describe('ProductVerticalWithCartCardComponent', () => {
expect(buySpy).toHaveBeenCalledWith({ quantity: 1, variant: 31 }); 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 { export interface VerticalCartVariant {
id: number; id: number;
descripcion?: string | null;
precio?: string | number;
values: Record<string, string>; values: Record<string, string>;
} }
@@ -46,7 +48,18 @@ export class ProductVerticalWithCartCardComponent {
protected readonly selectedValues = signal<Record<string, string>>({}); 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[]>(() => { protected readonly variantSelectors = computed<VariantSelector[]>(() => {
const variants = this.variants(); const variants = this.variants();
const keys = Array.from(new Set(variants.flatMap((variant) => Object.keys(variant.values)))); const keys = Array.from(new Set(variants.flatMap((variant) => Object.keys(variant.values))));