Compare commits

..

4 Commits

15 changed files with 533 additions and 162 deletions

View File

@@ -1,39 +1,52 @@
@if (open() && categories().length) { @if (open() && categories().length) {
<section class="dropdown-menu show p-2 category-dropdown" role="menu" aria-label="Categorías"> <section
@for (category of categories(); track category.id) { class="dropdown-menu show p-2 category-dropdown"
<div class="dropdown-submenu"> role="menu"
aria-label="Categorías"
(pointerleave)="onPointerLeave($event)"
>
<ng-container
*ngTemplateOutlet="categoryTree; context: { $implicit: categories(), depth: 0 }"
/>
</section>
}
<ng-template #categoryTree let-nodes let-depth="depth">
@for (category of nodes; track category.id) {
<div class="dropdown-submenu" (pointerenter)="onPointerEnter($event, category, depth)">
<button <button
type="button" type="button"
class="dropdown-item d-flex align-items-center justify-content-between gap-3" class="dropdown-item d-flex align-items-center justify-content-between gap-3"
[class.active]="activeCategory()?.id === category.id" [class.active]="isExpanded(category, depth)"
role="menuitem" role="menuitem"
[attr.aria-expanded]="category.subcategories.length ? activeCategory()?.id === category.id : null" [attr.aria-expanded]="category.subcategories.length ? isExpanded(category, depth) : null"
[attr.aria-controls]="
category.subcategories.length ? 'store-category-submenu-' + category.id : null
"
(focus)="onFocus(category, depth)"
(click)="selectCategory(category)" (click)="selectCategory(category)"
> >
<span>{{ category.nombre }}</span> <span>{{ category.nombre }}</span>
@if (category.subcategories.length) { @if (category.subcategories.length) {
<i class="fa-solid fa-chevron-right" aria-hidden="true"></i> <i class="fa-solid fa-chevron-right d-none d-md-inline" aria-hidden="true"></i>
} }
</button> </button>
@if (activeCategory()?.id === category.id && subcategories().length) { @if (isExpanded(category, depth) && category.subcategories.length) {
<div class="dropdown-menu show p-2 category-dropdown__submenu"> <div
@for (subcategory of subcategories(); track subcategory.id) { class="dropdown-menu show p-2 category-dropdown__submenu"
<button role="menu"
type="button" [id]="'store-category-submenu-' + category.id"
class="dropdown-item d-flex align-items-center justify-content-between gap-3" [attr.aria-label]="'Subcategorías de ' + category.nombre"
role="menuitem"
(click)="categorySelect.emit(subcategory)"
> >
<span>{{ subcategory.nombre }}</span> <ng-container
@if (subcategory.subcategories.length) { *ngTemplateOutlet="
<i class="fa-solid fa-chevron-right" aria-hidden="true"></i> categoryTree;
} context: { $implicit: category.subcategories, depth: depth + 1 }
</button> "
} />
</div> </div>
} }
</div> </div>
} }
</section> </ng-template>
}

View File

@@ -0,0 +1,95 @@
import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CategoryDropdownComponent } from './category-dropdown.component';
import { Category } from '../../../../services/tenant.interface';
describe('CategoryDropdownComponent', () => {
const parent: Category = {
id: 1,
nombre: 'Indumentaria',
subcategories: [
{
id: 2,
nombre: 'Buzos',
subcategories: [{ id: 3, nombre: 'Con capucha', subcategories: [] }],
},
],
};
const leaf: Category = { id: 4, nombre: 'Accesorios', subcategories: [] };
beforeEach(() => TestBed.configureTestingModule({ imports: [CategoryDropdownComponent] }));
function create() {
const fixture = TestBed.createComponent(CategoryDropdownComponent);
fixture.componentRef.setInput('categories', [parent, leaf]);
fixture.componentRef.setInput('open', true);
fixture.detectChanges();
return fixture;
}
function pointer(element: Element, type: string) {
const event = new Event(type);
Object.defineProperty(event, 'pointerType', { value: 'mouse' });
element.dispatchEvent(event);
}
it('opens subcategories on hover and navigates to the parent on click', () => {
const fixture = create();
const element = fixture.nativeElement as HTMLElement;
const select = vi.fn();
fixture.componentInstance.categorySelect.subscribe(select);
expect(element.querySelector('.category-dropdown__submenu')).toBeNull();
pointer(element.querySelector('.dropdown-submenu')!, 'pointerenter');
fixture.detectChanges();
expect(element.querySelector('.category-dropdown__submenu')?.textContent).toContain('Buzos');
expect(select).not.toHaveBeenCalled();
element.querySelector<HTMLButtonElement>('.dropdown-item')!.click();
expect(select).toHaveBeenCalledWith(parent);
});
it('supports nested hover menus and closes them when leaving the dropdown', () => {
const fixture = create();
const element = fixture.nativeElement as HTMLElement;
pointer(element.querySelector('.dropdown-submenu')!, 'pointerenter');
fixture.detectChanges();
pointer(
element.querySelector('.category-dropdown__submenu .dropdown-submenu')!,
'pointerenter',
);
fixture.detectChanges();
expect(element.textContent).toContain('Con capucha');
pointer(element.querySelector('.category-dropdown')!, 'pointerleave');
fixture.detectChanges();
expect(element.querySelector('.category-dropdown__submenu')).toBeNull();
});
it('opens subcategories with keyboard focus and navigates leaf categories', () => {
const fixture = create();
const element = fixture.nativeElement as HTMLElement;
element.querySelector('.dropdown-item')!.dispatchEvent(new Event('focus'));
fixture.detectChanges();
expect(element.querySelector('.category-dropdown__submenu')).not.toBeNull();
const select = vi.fn();
fixture.componentInstance.categorySelect.subscribe(select);
const buttons = Array.from(element.querySelectorAll<HTMLButtonElement>('.dropdown-item'));
buttons.find((button) => button.textContent?.trim() === 'Accesorios')!.click();
expect(select).toHaveBeenCalledWith(leaf);
});
it('clears expanded menus when closed or when their category is removed', () => {
const fixture = create();
const element = fixture.nativeElement as HTMLElement;
pointer(element.querySelector('.dropdown-submenu')!, 'pointerenter');
fixture.detectChanges();
fixture.componentRef.setInput('open', false);
fixture.detectChanges();
fixture.componentRef.setInput('open', true);
fixture.detectChanges();
expect(element.querySelector('.category-dropdown__submenu')).toBeNull();
pointer(element.querySelector('.dropdown-submenu')!, 'pointerenter');
fixture.detectChanges();
fixture.componentRef.setInput('categories', [leaf]);
fixture.detectChanges();
expect(element.querySelector('.category-dropdown__submenu')).toBeNull();
});
});

View File

@@ -1,10 +1,12 @@
import { ChangeDetectionStrategy, Component, computed, effect, input, output, signal } from '@angular/core'; import { NgTemplateOutlet } from '@angular/common';
import { ChangeDetectionStrategy, Component, effect, input, output, signal } from '@angular/core';
import { Category } from '../../../../services/tenant.interface'; import { Category } from '../../../../services/tenant.interface';
@Component({ @Component({
selector: 'app-category-dropdown', selector: 'app-category-dropdown',
standalone: true, standalone: true,
imports: [NgTemplateOutlet],
templateUrl: './category-dropdown.component.html', templateUrl: './category-dropdown.component.html',
styleUrl: './category-dropdown.component.scss', styleUrl: './category-dropdown.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
@@ -14,33 +16,53 @@ export class CategoryDropdownComponent {
readonly open = input(false); readonly open = input(false);
readonly categorySelect = output<Category>(); readonly categorySelect = output<Category>();
protected readonly activeCategory = signal<Category | null>(null); protected readonly expandedPath = signal<readonly number[]>([]);
protected readonly subcategories = computed(() => this.activeCategory()?.subcategories ?? []);
constructor() { constructor() {
effect(() => { effect(() => {
const categories = this.categories(); const categories = this.categories();
const activeCategory = this.activeCategory();
if (!this.open()) { if (!this.open()) {
this.activeCategory.set(null); this.expandedPath.set([]);
return; return;
} }
let nodes: readonly Category[] = categories;
if (activeCategory && !categories.some((category) => category.id === activeCategory.id)) { const validPath: number[] = [];
this.activeCategory.set(null); for (const id of this.expandedPath()) {
const category = nodes.find((node) => node.id === id);
if (!category?.subcategories.length) break;
validPath.push(id);
nodes = category.subcategories;
}
if (validPath.length !== this.expandedPath().length) {
this.expandedPath.set(validPath);
} }
}); });
} }
protected selectCategory(category: Category): void { protected selectCategory(category: Category): void {
if (category.subcategories.length) {
this.activeCategory.update((activeCategory) =>
activeCategory?.id === category.id ? null : category,
);
return;
}
this.categorySelect.emit(category); this.categorySelect.emit(category);
} }
protected isExpanded(category: Category, depth: number): boolean {
return this.expandedPath()[depth] === category.id;
}
protected expand(category: Category, depth: number): void {
this.expandedPath.update((path) => [
...path.slice(0, depth),
...(category.subcategories.length ? [category.id] : []),
]);
}
protected onPointerEnter(event: PointerEvent, category: Category, depth: number): void {
if (event.pointerType === 'mouse') this.expand(category, depth);
}
protected onPointerLeave(event: PointerEvent): void {
if (event.pointerType === 'mouse') this.expandedPath.set([]);
}
protected onFocus(category: Category, depth: number): void {
this.expand(category, depth);
}
} }

View File

@@ -69,12 +69,12 @@
<app-store-footer <app-store-footer
[currentYear]="currentYear" [currentYear]="currentYear"
[footerSections]="footerSections()" [footerSections]="footerSections()"
[socialMedia]="tenant()?.social_media ?? []" [socialMedia]="tenant()?.tenant_social_media ?? tenant()?.social_media ?? []"
[logoUrl]="tenant()?.footer_logo ?? null" [logoUrl]="tenant()?.footer_logo ?? null"
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null" [backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
[storeName]="tenant()?.nombre ?? null" [storeName]="tenant()?.nombre ?? null"
[address]="tenant()?.main_address?.address_text ?? null" [address]="tenant()?.main_address?.address_text ?? null"
[phone]="tenant()?.phone ?? null" [phone]="tenant()?.main_phone_number?.number ?? null"
(logoutClick)="onLogoutClick()" (logoutClick)="onLogoutClick()"
/> />
</div> </div>

View File

@@ -37,6 +37,7 @@ const tenant: Tenant = {
address: 'Calle Test 123, Rosario', address: 'Calle Test 123, Rosario',
main_address: { id: 1, label: 'Principal', address_text: 'Calle Test 123, Rosario', latitude: null, longitude: null }, main_address: { id: 1, label: 'Principal', address_text: 'Calle Test 123, Rosario', latitude: null, longitude: null },
phone: '+54 341 555 1234', phone: '+54 341 555 1234',
main_phone_number: { id: 1, label: 'Principal', number: '+54 341 555 1234', tel_url: 'tel:+543415551234' },
primary_color: '#6376F3', primary_color: '#6376F3',
secondary_color: '#A0A0A0', secondary_color: '#A0A0A0',
danger_color: '#FF8888', danger_color: '#FF8888',
@@ -579,6 +580,35 @@ describe('StoreLayoutComponent', () => {
expect(footer.textContent).not.toContain(tenant.address); expect(footer.textContent).not.toContain(tenant.address);
}); });
it('uses commerce social networks in the footer and respects an empty collection', () => {
tenantState.set({ ...tenant, tenant_social_media: [
{ ...tenant.social_media![0], url: 'https://instagram.com/commerce-contact' },
] });
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const footer = fixture.nativeElement.querySelector('app-store-footer') as HTMLElement;
expect(footer.querySelector('a[href="https://instagram.com/commerce-contact"]')).not.toBeNull();
tenantState.set({ ...tenant, tenant_social_media: [] });
fixture.detectChanges();
expect(footer.querySelector('a[href="https://instagram.com/commerce-contact"]')).toBeNull();
expect(footer.querySelector('a[href="' + tenant.social_media![0].url + '"]')).toBeNull();
});
it('uses only the main phone number in the footer', () => {
tenantState.set({ ...tenant, main_phone_number: {
id: 10, label: 'Principal', number: '3411234567', tel_url: 'tel:3411234567',
} });
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const footer = fixture.nativeElement.querySelector('app-store-footer') as HTMLElement;
expect(footer.textContent).toContain('3411234567');
expect(footer.textContent).not.toContain(tenant.phone);
tenantState.set({ ...tenant, main_phone_number: null });
fixture.detectChanges();
expect(footer.textContent).not.toContain('3411234567');
expect(footer.textContent).not.toContain(tenant.phone);
});
it('navigates to search results when the search button is clicked', () => { it('navigates to search results when the search button is clicked', () => {
const router = TestBed.inject(Router); const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate'); vi.spyOn(router, 'navigate');

View File

@@ -170,6 +170,7 @@ export interface CatalogCategory {
id: number; id: number;
nombre: string; nombre: string;
categoria_id: number | null; categoria_id: number | null;
banner_url?: string | null;
} }
export interface CategoryItemsResponse extends ApiPaginatedResponse<CatalogFeaturedItem[]> { export interface CategoryItemsResponse extends ApiPaginatedResponse<CatalogFeaturedItem[]> {

View File

@@ -0,0 +1,10 @@
export interface PhoneNumber {
id: number;
label: string;
number: string;
tel_url: string;
}
export interface TenantPhoneNumber extends PhoneNumber {
is_main: boolean;
}

View File

@@ -1,5 +1,6 @@
import { ApiResponse } from './api-response.interface'; import { ApiResponse } from './api-response.interface';
import { Address, TenantAddress } from './address.interface'; import { Address, TenantAddress } from './address.interface';
import { PhoneNumber, TenantPhoneNumber } from './phone-number.interface';
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full'; export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
@@ -126,6 +127,8 @@ export interface Tenant {
addresses?: TenantAddress[]; addresses?: TenantAddress[];
main_address?: Address | null; main_address?: Address | null;
phone?: string | null; phone?: string | null;
phone_numbers?: TenantPhoneNumber[];
main_phone_number?: PhoneNumber | null;
favicon?: string | null; favicon?: string | null;
primary_color: string; primary_color: string;
secondary_color: string; secondary_color: string;
@@ -158,6 +161,7 @@ export interface Tenant {
allow_ticket_partial_refund?: boolean; allow_ticket_partial_refund?: boolean;
ticket_partial_refund_percentage?: string; ticket_partial_refund_percentage?: string;
social_media?: SocialMedia[]; social_media?: SocialMedia[];
tenant_social_media?: SocialMedia[];
menues?: Menu[]; menues?: Menu[];
categories?: Category[]; categories?: Category[];
event_categories?: Category[]; event_categories?: Category[];

View File

@@ -2,7 +2,14 @@
@if (error()) { @if (error()) {
<p class="alert text-center mb-0 category-items__alert-error">{{ error() }}</p> <p class="alert text-center mb-0 category-items__alert-error">{{ error() }}</p>
} @else if (results(); as categoryResults) { } @else if (results(); as categoryResults) {
<header class="category-items__header mb-5"> @if (categoryResults.category.banner_url; as bannerUrl) {
<img
class="category-items__banner"
[src]="bannerUrl"
[alt]="'Banner de ' + categoryResults.category.nombre"
/>
}
<header class="category-items__header">
<h1 id="category-items-title" class="category-items__title mb-0"> <h1 id="category-items-title" class="category-items__title mb-0">
{{ categoryResults.category.nombre }} {{ categoryResults.category.nombre }}
</h1> </h1>

View File

@@ -1,16 +1,30 @@
app-category-items-page {
display: block;
}
// Override the layout's Bootstrap padding only while this page is mounted.
app-store-layout main > section.py-5:has(app-category-items-page) {
padding-top: 0 !important;
}
.category-items__banner {
display: block;
width: 100%;
height: 170px;
object-fit: cover;
}
.category-items__header { .category-items__header {
display: flex; margin: 16px 0;
align-items: center;
justify-content: center;
padding: 16px 28px;
} }
.category-items__title { .category-items__title {
font-size: 24px; font-size: 15px;
font-weight: bold; font-weight: bold;
line-height: 1.2; line-height: 1.2;
text-align: center; text-align: left;
color:var(--bs-primary) text-transform: uppercase;
color: #000;
} }
.category-items__alert-error { .category-items__alert-error {

View File

@@ -106,6 +106,30 @@ describe('CategoryItemsPageComponent', () => {
expect(productList.layout()).toBe('row'); expect(productList.layout()).toBe('row');
expect(productList.groupLayout()).toBe('paginated'); expect(productList.groupLayout()).toBe('paginated');
expect(Array.isArray(productList.items())).toBe(false); expect(Array.isArray(productList.items())).toBe(false);
expect(fixture.nativeElement.querySelector('.category-items__banner')).toBeNull();
});
it('renders the category banner above the title when the API returns its URL', () => {
getCategoryItems.mockReturnValue(
of({
category: {
id: 7,
nombre: 'Remeras',
categoria_id: null,
banner_url: 'https://example.com/banner.jpg',
},
data: [],
}),
);
const fixture = TestBed.createComponent(CategoryItemsPageComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const banner = element.querySelector<HTMLImageElement>('.category-items__banner');
expect(banner?.getAttribute('src')).toBe('https://example.com/banner.jpg');
expect(banner?.alt).toBe('Banner de Remeras');
expect(banner?.nextElementSibling?.querySelector('h1')?.textContent).toContain('Remeras');
}); });
it('reloads the current category page when catalog availability changes', () => { it('reloads the current category page when catalog availability changes', () => {

View File

@@ -4,6 +4,7 @@ import {
Component, Component,
DestroyRef, DestroyRef,
Injector, Injector,
ViewEncapsulation,
inject, inject,
signal, signal,
} from '@angular/core'; } from '@angular/core';
@@ -51,6 +52,7 @@ interface CategoryRouteState {
imports: [ProductListComponent], imports: [ProductListComponent],
templateUrl: './category-items-page.component.html', templateUrl: './category-items-page.component.html',
styleUrl: './category-items-page.component.scss', styleUrl: './category-items-page.component.scss',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class CategoryItemsPageComponent { export class CategoryItemsPageComponent {

View File

@@ -1,22 +1,34 @@
<app-menu-content-section menuCode="help.contact" titleId="contact-page-title"> <app-menu-content-section menuCode="help.contact" titleId="contact-page-title">
<div class="contact-page"> <div class="contact-page">
<div class="contact-page__details"> <div class="contact-page__details">
@if (contact().whatsappUrl && contact().whatsappLabel) { @for (whatsapp of contact().whatsapp; track whatsapp.code) {
<a <a
class="contact-page__contact-link" class="contact-page__contact-link"
[href]="contact().whatsappUrl" [href]="whatsapp.url"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
<i class="fa-brands fa-whatsapp" aria-hidden="true"></i> <i [class]="whatsapp.icon" aria-hidden="true"></i>
<span>{{ contact().whatsappLabel }}</span> <span>{{ whatsapp.name }}</span>
</a> </a>
} }
@if (contact().phone; as phone) { @for (social of contact().socialMedia; track social.code) {
<a class="contact-page__contact-link" [href]="phoneUrl(phone)"> <a
class="contact-page__contact-link"
[href]="social.url"
target="_blank"
rel="noopener noreferrer"
>
<i [class]="social.icon" aria-hidden="true"></i>
<span>{{ social.name }}</span>
</a>
}
@for (phone of contact().phones; track phone.id) {
<a class="contact-page__contact-link" [href]="phone.tel_url">
<i class="fa-solid fa-phone" aria-hidden="true"></i> <i class="fa-solid fa-phone" aria-hidden="true"></i>
<span>{{ phone }}</span> <span>{{ phone.label }}: {{ phone.number }}</span>
</a> </a>
} }
@@ -35,7 +47,12 @@
</article> </article>
} }
@if (!contact().whatsappUrl && !contact().phone && contact().locations.length === 0) { @if (
contact().whatsapp.length === 0 &&
contact().socialMedia.length === 0 &&
contact().phones.length === 0 &&
contact().locations.length === 0
) {
<p class="contact-page__empty">No hay datos de contacto disponibles.</p> <p class="contact-page__empty">No hay datos de contacto disponibles.</p>
} }
</div> </div>

View File

@@ -19,10 +19,55 @@ const tenant: Tenant = {
header_logo: '', header_logo: '',
footer_logo: '', footer_logo: '',
categories: [], categories: [],
social_media: [
{
code: 'whatsapp',
name: 'WhatsApp',
icon: 'fa-brands fa-whatsapp',
url: 'https://wa.me/543412602222',
},
{
code: 'instagram',
name: 'Instagram',
icon: 'fa-brands fa-instagram',
url: 'https://www.instagram.com/comercio',
},
],
phone_numbers: [
{
id: 1,
label: 'Principal',
number: '+54 9 (0341) 6658247',
tel_url: 'tel:+54903416658247',
is_main: true,
},
{ id: 2, label: 'Ventas', number: '3411234567', tel_url: 'tel:3411234567', is_main: false },
],
addresses: [ addresses: [
{ id: 1, label: 'Gigante de Arroyito', address_text: 'Av. Génova 640, Rosario', latitude: -32.913997, longitude: -60.674567, is_main: true }, {
{ id: 2, label: 'Telepagos', address_text: 'Rioja 1150, piso 12, dpto. 3, Rosario', latitude: -32.94682, longitude: -60.63932, is_main: false }, id: 1,
{ id: 3, label: 'San Martín 2450', address_text: 'San Martín 2450, Santa Fe', latitude: -31.63333, longitude: -60.7, is_main: false }, label: 'Gigante de Arroyito',
address_text: 'Av. Génova 640, Rosario',
latitude: -32.913997,
longitude: -60.674567,
is_main: true,
},
{
id: 2,
label: 'Telepagos',
address_text: 'Rioja 1150, piso 12, dpto. 3, Rosario',
latitude: -32.94682,
longitude: -60.63932,
is_main: false,
},
{
id: 3,
label: 'San Martín 2450',
address_text: 'San Martín 2450, Santa Fe',
latitude: -31.63333,
longitude: -60.7,
is_main: false,
},
], ],
menues: [ menues: [
{ {
@@ -38,42 +83,8 @@ const tenant: Tenant = {
code: 'help.contact', code: 'help.contact',
label: 'Contacto', label: 'Contacto',
parent_menu_code: 'help', parent_menu_code: 'help',
content_type: 'static', content_type: 'dynamic',
route: '/ayuda/contacto', route: '/ayuda/contacto',
static_content: {
whatsapp: {
whatsapp_url: 'https://wa.me/543412602222',
whatsapp_label: 'Chatea con nosotros',
},
phone: '+54 9 (0341) 6658247',
locations: {
rosario: {
label: 'Rosario',
addresses: [
{
label: 'Gigante de Arroyito',
address: 'Av. Génova 640, Rosario',
coordinates: [-32.913997, -60.674567],
},
{
label: 'Telepagos',
address: 'Rioja 1150, piso 12, dpto. 3, Rosario',
coordinates: [-32.94682, -60.63932],
},
],
},
santa_fe: {
label: 'Santa Fe',
addresses: [
{
label: 'San Martín 2450',
address: 'San Martín 2450, Santa Fe',
coordinates: [-31.63333, -60.7],
},
],
},
},
},
submenues: [], submenues: [],
}, },
], ],
@@ -111,7 +122,10 @@ describe('ContactPage', () => {
const phone = element.querySelector<HTMLAnchorElement>('a[href="tel:+54903416658247"]'); const phone = element.querySelector<HTMLAnchorElement>('a[href="tel:+54903416658247"]');
expect(element.textContent).toContain('CONTACTO'); expect(element.textContent).toContain('CONTACTO');
expect(whatsapp?.textContent).toContain('Chatea con nosotros'); expect(whatsapp?.textContent).toContain('WhatsApp');
expect(
element.querySelector('a[href="https://www.instagram.com/comercio"]')?.textContent,
).toContain('Instagram');
expect(phone?.textContent).toContain('+54 9 (0341) 6658247'); expect(phone?.textContent).toContain('+54 9 (0341) 6658247');
expect(element.textContent).toContain('Rosario'); expect(element.textContent).toContain('Rosario');
expect(element.textContent).toContain('Gigante de Arroyito'); expect(element.textContent).toContain('Gigante de Arroyito');
@@ -119,13 +133,29 @@ describe('ContactPage', () => {
expect(element.querySelector('.contact-page__addresses')?.textContent).toContain( expect(element.querySelector('.contact-page__addresses')?.textContent).toContain(
'Av. Génova 640, Rosario', 'Av. Génova 640, Rosario',
); );
expect(element.textContent).toContain( expect(element.textContent).toContain('Rioja 1150, piso 12, dpto. 3, Rosario');
'Rioja 1150, piso 12, dpto. 3, Rosario',
);
expect(element.textContent).toContain('Santa Fe'); expect(element.textContent).toContain('Santa Fe');
expect(element.textContent).toContain('San Martín 2450'); expect(element.textContent).toContain('San Martín 2450');
}); });
it('uses commerce networks even when the active event has different networks', () => {
tenantState.set({
...tenant,
tenant_social_media: [{ ...tenant.social_media![0], url: 'https://wa.me/commerce' }],
social_media: [{ ...tenant.social_media![0], url: 'https://wa.me/event' }],
});
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('a[href="https://wa.me/commerce"]')).not.toBeNull();
expect(element.querySelector('a[href="https://wa.me/event"]')).toBeNull();
});
it('does not restore event networks after all commerce networks are removed', () => {
tenantState.set({ ...tenant, tenant_social_media: [] });
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('a[href="https://wa.me/543412602222"]')).toBeNull();
});
it('passes the tenant map coordinates to the reusable map component', () => { it('passes the tenant map coordinates to the reusable map component', () => {
const element = fixture.nativeElement as HTMLElement; const element = fixture.nativeElement as HTMLElement;
const map = element.querySelector('app-location-map'); const map = element.querySelector('app-location-map');
@@ -145,12 +175,47 @@ describe('ContactPage', () => {
expect(map?.textContent).toContain('San Martín 2450'); expect(map?.textContent).toContain('San Martín 2450');
}); });
it('renders canonical numbers with the main first and never restores legacy numbers', () => {
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelectorAll('a[href^="tel:"]')).toHaveLength(2);
expect(element.querySelector('a[href^="tel:"]')?.textContent).toContain('Principal');
tenantState.set({ ...tenant, phone: '999999', phone_numbers: [] });
fixture.detectChanges();
expect(element.querySelectorAll('a[href^="tel:"]')).toHaveLength(0);
expect(element.textContent).not.toContain('999999');
expect(element.textContent).not.toContain('+54 9 (0341) 6658247');
});
it('shows every canonical address and maps only addresses with coordinates', () => { it('shows every canonical address and maps only addresses with coordinates', () => {
tenantState.set({ ...tenant, addresses: [ tenantState.set({
{ id: 10, label: 'Principal', address_text: 'Nueva sede 123', latitude: 0, longitude: 0, is_main: true }, ...tenant,
{ id: 11, label: 'Sucursal sin mapa', address_text: 'Otra calle 456', latitude: null, longitude: null, is_main: false }, addresses: [
{ id: 12, label: 'Otra ciudad', address_text: 'Tercera 789', latitude: -31, longitude: -60, is_main: false }, {
] }); id: 10,
label: 'Principal',
address_text: 'Nueva sede 123',
latitude: 0,
longitude: 0,
is_main: true,
},
{
id: 11,
label: 'Sucursal sin mapa',
address_text: 'Otra calle 456',
latitude: null,
longitude: null,
is_main: false,
},
{
id: 12,
label: 'Otra ciudad',
address_text: 'Tercera 789',
latitude: -31,
longitude: -60,
is_main: false,
},
],
});
fixture.detectChanges(); fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement; const element = fixture.nativeElement as HTMLElement;
expect(element.textContent).toContain('Nueva sede 123'); expect(element.textContent).toContain('Nueva sede 123');
@@ -173,4 +238,75 @@ describe('ContactPage', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.contact-page__location')).toHaveLength(0); expect(fixture.nativeElement.querySelectorAll('.contact-page__location')).toHaveLength(0);
}); });
it('updates contact when the resolved social media changes to the active event channels', () => {
tenantState.set({
...tenant,
social_media: [
{
code: 'whatsapp',
name: 'WhatsApp del evento',
icon: 'fa-brands fa-whatsapp',
url: 'https://wa.me/541111111111',
},
],
});
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(element.querySelector('a[href="https://wa.me/541111111111"]')?.textContent).toContain(
'WhatsApp del evento',
);
expect(element.querySelector('a[href="https://wa.me/543412602222"]')).toBeNull();
expect(element.textContent).not.toContain('Instagram');
});
it('shows the main address first without reordering tenant data', () => {
const addresses = [...tenant.addresses!].reverse();
tenantState.set({ ...tenant, addresses });
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.contact-page__location-title')?.textContent,
).toContain('Gigante de Arroyito');
expect(addresses[0].id).toBe(3);
});
it('ignores legacy static content and shows the empty state when no canonical data exists', () => {
tenantState.set({
...tenant,
addresses: [],
phone_numbers: [],
social_media: [],
menues: [
{
...tenant.menues![0].submenues[0],
static_content: {
whatsapp: {
whatsapp_url: 'https://wa.me/549999999999',
whatsapp_label: 'Legacy WhatsApp',
},
},
},
],
});
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('No hay datos de contacto disponibles.');
expect(fixture.nativeElement.textContent).not.toContain('Legacy WhatsApp');
expect(fixture.nativeElement.querySelector('a')).toBeNull();
expect(fixture.nativeElement.querySelector('app-location-map')).toBeNull();
});
it('shows social-only contact and ignores blank social URLs', () => {
tenantState.set({
...tenant,
addresses: [],
phone_numbers: [],
social_media: [tenant.social_media![1], { ...tenant.social_media![0], url: ' ' }],
});
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Instagram');
expect(fixture.nativeElement.textContent).not.toContain(
'No hay datos de contacto disponibles.',
);
expect(fixture.nativeElement.textContent).not.toContain('WhatsApp');
});
}); });

View File

@@ -1,7 +1,8 @@
import { Component, computed, inject } from '@angular/core'; import { Component, computed, inject } from '@angular/core';
import { findMenu } from '../../../../../../core/services/menu.utils';
import { TenantService } from '../../../../../../core/services/tenant.service'; import { TenantService } from '../../../../../../core/services/tenant.service';
import { TenantPhoneNumber } from '../../../../../../core/services/phone-number.interface';
import { SocialMedia } from '../../../../../../core/services/tenant.interface';
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component'; import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
import { import {
LocationMapComponent, LocationMapComponent,
@@ -22,9 +23,9 @@ type ContactAddress = {
}; };
type ContactContent = { type ContactContent = {
whatsappUrl: string | null; whatsapp: SocialMedia[];
whatsappLabel: string | null; socialMedia: SocialMedia[];
phone: string | null; phones: TenantPhoneNumber[];
locations: ContactLocation[]; locations: ContactLocation[];
mapLocations: MapLocation[]; mapLocations: MapLocation[];
}; };
@@ -42,57 +43,52 @@ export class ContactPage {
() => this.tenantService.tenant()?.primary_color ?? '#6376f3', () => this.tenantService.tenant()?.primary_color ?? '#6376f3',
); );
protected readonly contact = computed(() => protected readonly contact = computed(() => this.buildContactContent());
this.parseContactContent(
findMenu(this.tenantService.tenant()?.menues ?? [], 'help.contact')?.static_content, private buildContactContent(): ContactContent {
), const tenant = this.tenantService.tenant();
const socialMedia = (tenant?.tenant_social_media ?? tenant?.social_media ?? []).filter((social) => social.url.trim());
const addresses = [...(tenant?.addresses ?? [])].sort(
(a, b) => Number(b.is_main) - Number(a.is_main),
); );
protected phoneUrl(phone: string): string {
const normalizedPhone = phone.replace(/[^\d+]/g, '');
return `tel:${normalizedPhone}`;
}
private parseContactContent(value: unknown): ContactContent {
const content = this.isRecord(value) ? value : {};
const whatsapp = this.isRecord(content['whatsapp']) ? content['whatsapp'] : null;
const addresses = this.tenantService.tenant()?.addresses ?? [];
const locations: ContactLocation[] = addresses.map((address) => ({ const locations: ContactLocation[] = addresses.map((address) => ({
id: String(address.id), id: String(address.id),
label: address.label, label: address.label,
addresses: [{ addresses: [
{
id: String(address.id), id: String(address.id),
label: address.label, label: address.label,
address: address.address_text, address: address.address_text,
coordinates: address.latitude !== null && address.longitude !== null coordinates:
? [address.latitude, address.longitude] : null, address.latitude !== null && address.longitude !== null
}], ? [address.latitude, address.longitude]
: null,
},
],
})); }));
return { return {
whatsappUrl: whatsapp ? this.stringValue(whatsapp['whatsapp_url']) : null, whatsapp: socialMedia.filter((social) => social.code === 'whatsapp'),
whatsappLabel: whatsapp ? this.stringValue(whatsapp['whatsapp_label']) : null, socialMedia: socialMedia.filter((social) => social.code !== 'whatsapp'),
phone: this.stringValue(content['phone']) ?? this.tenantService.tenant()?.phone ?? null, phones: [...(tenant?.phone_numbers ?? [])].sort(
(a, b) => Number(b.is_main) - Number(a.is_main),
),
locations, locations,
mapLocations: locations.flatMap((location) => mapLocations: locations.flatMap((location) =>
location.addresses.flatMap( location.addresses.flatMap((address): MapLocation[] =>
(address): MapLocation[] => address.coordinates === null ? [] : [{ address.coordinates === null
? []
: [
{
id: address.id, id: address.id,
label: address.label, label: address.label,
latitude: address.coordinates[0], latitude: address.coordinates[0],
longitude: address.coordinates[1], longitude: address.coordinates[1],
address: address.address, address: address.address,
}], },
],
), ),
), ),
}; };
} }
private stringValue(value: unknown): string | null {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
private isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
} }