feat(address): refactor address handling across components and services

This commit is contained in:
2026-09-30 10:59:39 -03:00
parent c851272ebe
commit d9bf729a96
12 changed files with 175 additions and 90 deletions

View File

@@ -73,7 +73,7 @@
[logoUrl]="tenant()?.footer_logo ?? null"
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
[storeName]="tenant()?.nombre ?? null"
[address]="tenant()?.address ?? null"
[address]="tenant()?.main_address?.address_text ?? null"
[phone]="tenant()?.phone ?? null"
(logoutClick)="onLogoutClick()"
/>

View File

@@ -35,6 +35,7 @@ const tenant: Tenant = {
nombre: 'Test Tenant',
dominio: 'localhost',
address: 'Calle Test 123, Rosario',
main_address: { id: 1, label: 'Principal', address_text: 'Calle Test 123, Rosario', latitude: null, longitude: null },
phone: '+54 341 555 1234',
primary_color: '#6376F3',
secondary_color: '#A0A0A0',
@@ -563,6 +564,21 @@ describe('StoreLayoutComponent', () => {
);
});
it('uses only the main address in the footer', () => {
tenantState.set({ ...tenant, main_address: {
id: 10, label: 'Principal', address_text: 'Sede principal 456', latitude: null, longitude: null,
} });
const fixture = TestBed.createComponent(StoreLayoutComponent);
fixture.detectChanges();
const footer = fixture.nativeElement.querySelector('app-store-footer') as HTMLElement;
expect(footer.textContent).toContain('Sede principal 456');
expect(footer.textContent).not.toContain(tenant.address);
tenantState.set({ ...tenant, main_address: null });
fixture.detectChanges();
expect(footer.textContent).not.toContain('Sede principal 456');
expect(footer.textContent).not.toContain(tenant.address);
});
it('navigates to search results when the search button is clicked', () => {
const router = TestBed.inject(Router);
vi.spyOn(router, 'navigate');

View File

@@ -0,0 +1,11 @@
export interface Address {
id: number;
label: string;
address_text: string;
latitude: number | null;
longitude: number | null;
}
export interface TenantAddress extends Address {
is_main: boolean;
}

View File

@@ -1,4 +1,5 @@
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
import { Address } from '../address.interface';
export interface StoreEvent {
id: number;
@@ -8,6 +9,7 @@ export interface StoreEvent {
subtitle: string | null;
description: string | null;
location: string | null;
address?: Address | null;
exact_location: { latitude: number; longitude: number } | null;
date_text: string | null;
start_time?: string | null;

View File

@@ -1,4 +1,5 @@
import { ApiResponse } from './api-response.interface';
import { Address, TenantAddress } from './address.interface';
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
@@ -69,6 +70,7 @@ export interface TenantEvent {
subtitle: string | null;
description: string | null;
location: string | null;
address?: Address | null;
date_text: string | null;
dates: ActiveEventDate[];
social_media: SocialMedia[];
@@ -121,6 +123,8 @@ export interface Tenant {
site_title?: string | null;
asset_url?: string | null;
address?: string | null;
addresses?: TenantAddress[];
main_address?: Address | null;
phone?: string | null;
favicon?: string | null;
primary_color: string;

View File

@@ -12,8 +12,8 @@
@if (event().date_text) {
<p class="event-card__meta"><i class="fa-regular fa-calendar" aria-hidden="true"></i>{{ event().date_text }}</p>
}
@if (event().location) {
<p class="event-card__meta"><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ event().location }}</p>
@if (event().address?.address_text; as location) {
<p class="event-card__meta"><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ location }}</p>
}
</div>
</a>

View File

@@ -24,8 +24,8 @@
{{ item.date_text }}@if (item.dates?.length === 1 && item.start_time) { · {{ item.start_time.slice(0, 5) }} h }
</p>
}
@if (item.location) {
<p><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ item.location }}</p>
@if (item.address?.address_text; as location) {
<p><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ location }}</p>
}
</div>
</header>

View File

@@ -0,0 +1,67 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ActivatedRoute, convertToParamMap, provideRouter } from '@angular/router';
import { of } from 'rxjs';
import { beforeEach, describe, expect, it } from 'vitest';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { CheckoutService } from '../../../../core/services/checkout.service';
import { StoreEvent } from '../../../../core/services/event/event.interface';
import { EventService } from '../../../../core/services/event/event.service';
import { TenantService } from '../../../../core/services/tenant.service';
import { ToastService } from '../../../../core/services/toast.service';
import { LocationMapComponent } from '../../../../shared/components/location-map/location-map.component';
import { EventDetailPageComponent } from './event-detail-page.component';
const event: StoreEvent = {
id: 1, slug: 'festival', title: 'Festival', event_category_id: null,
subtitle: null, description: null, location: 'Ubicación anterior',
exact_location: { latitude: 10, longitude: 20 }, date_text: null,
attachment_id: null, image: null,
address: { id: 20, label: 'Predio', address_text: 'Dirección del evento 123', latitude: 0, longitude: -60 },
};
describe('EventDetailPageComponent address', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [EventDetailPageComponent],
providers: [
provideRouter([]),
{ provide: ActivatedRoute, useValue: { paramMap: of(convertToParamMap({ slug: 'festival' })) } },
{ provide: EventService, useValue: { get: () => of({ data: event }) } },
{ provide: AuthService, useValue: {} },
{ provide: CheckoutService, useValue: {} },
{ provide: TenantService, useValue: { tenant: signal(null) } },
{ provide: ToastService, useValue: {} },
],
}).compileComponents();
});
it('uses the event address for its text and map including zero coordinates', () => {
const fixture = TestBed.createComponent(EventDetailPageComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Dirección del evento 123');
expect(fixture.nativeElement.textContent).not.toContain('Ubicación anterior');
const map = fixture.debugElement.query(By.directive(LocationMapComponent)).componentInstance as LocationMapComponent;
expect(map.locations).toEqual([{ id: 20, label: 'Predio', latitude: 0, longitude: -60, address: 'Dirección del evento 123' }]);
});
it('shows address text without using old map coordinates when the new address has none', () => {
TestBed.overrideProvider(EventService, { useValue: { get: () => of({ data: {
...event, address: { ...event.address!, latitude: null, longitude: null },
} }) } });
const fixture = TestBed.createComponent(EventDetailPageComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Dirección del evento 123');
expect(fixture.nativeElement.querySelector('app-location-map')).toBeNull();
});
it('does not use old location fields when the event has no address', () => {
TestBed.overrideProvider(EventService, { useValue: { get: () => of({ data: { ...event, address: null } }) } });
const fixture = TestBed.createComponent(EventDetailPageComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).not.toContain('Ubicación anterior');
expect(fixture.nativeElement.querySelector('app-location-map')).toBeNull();
});
});

View File

@@ -41,15 +41,15 @@ export class EventDetailPageComponent {
protected readonly submitting = signal(false);
protected readonly mapLocations = computed<MapLocation[]>(() => {
const event = this.event();
const coordinates = event?.exact_location;
if (!event || !coordinates) return [];
const address = event?.address;
if (!event || !address || address.latitude === null || address.longitude === null) return [];
return [{
id: event.id,
label: event.title,
latitude: coordinates.latitude,
longitude: coordinates.longitude,
address: event.location ?? undefined,
id: address.id,
label: address.label,
latitude: address.latitude,
longitude: address.longitude,
address: address.address_text,
}];
});
protected readonly total = computed(() => (this.event()?.catalog_items ?? []).reduce((sum, product) => {

View File

@@ -19,6 +19,11 @@ const tenant: Tenant = {
header_logo: '',
footer_logo: '',
categories: [],
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: 3, label: 'San Martín 2450', address_text: 'San Martín 2450, Santa Fe', latitude: -31.63333, longitude: -60.7, is_main: false },
],
menues: [
{
id: 1,
@@ -78,15 +83,17 @@ const tenant: Tenant = {
describe('ContactPage', () => {
let fixture: ComponentFixture<ContactPage>;
let tenantState = signal<Tenant | null>(tenant);
beforeEach(async () => {
tenantState = signal<Tenant | null>(tenant);
await TestBed.configureTestingModule({
imports: [ContactPage],
providers: [
{
provide: TenantService,
useValue: {
tenant: signal<Tenant | null>(tenant).asReadonly(),
tenant: tenantState.asReadonly(),
},
},
],
@@ -112,11 +119,11 @@ describe('ContactPage', () => {
expect(element.querySelector('.contact-page__addresses')?.textContent).toContain(
'Av. Génova 640, Rosario',
);
expect(element.querySelector('.contact-page__addresses')?.textContent).toContain(
expect(element.textContent).toContain(
'Rioja 1150, piso 12, dpto. 3, Rosario',
);
expect(element.textContent).not.toContain('Santa Fe');
expect(element.textContent).not.toContain('San Martín 2450');
expect(element.textContent).toContain('Santa Fe');
expect(element.textContent).toContain('San Martín 2450');
});
it('passes the tenant map coordinates to the reusable map component', () => {
@@ -129,12 +136,41 @@ describe('ContactPage', () => {
expect(map).not.toBeNull();
expect(map?.getAttribute('mapstyle')).toBe('standard');
expect(accessibleLocations).toHaveLength(2);
expect(accessibleLocations).toHaveLength(3);
expect(map?.textContent).toContain('Gigante de Arroyito');
expect(map?.textContent).toContain('Telepagos');
expect(map?.textContent).toContain('Av. Génova 640, Rosario');
expect(map?.textContent).toContain('Rioja 1150, piso 12, dpto. 3, Rosario');
expect(directionsLinks).toHaveLength(2);
expect(map?.textContent).not.toContain('San Martín 2450');
expect(directionsLinks).toHaveLength(3);
expect(map?.textContent).toContain('San Martín 2450');
});
it('shows every canonical address and maps only addresses with coordinates', () => {
tenantState.set({ ...tenant, addresses: [
{ 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();
const element = fixture.nativeElement as HTMLElement;
expect(element.textContent).toContain('Nueva sede 123');
expect(element.textContent).toContain('Otra calle 456');
expect(element.textContent).toContain('Tercera 789');
expect(element.textContent).not.toContain('Av. Génova 640');
expect(element.querySelectorAll('.contact-page__location')).toHaveLength(3);
expect(element.querySelectorAll('app-location-map .visually-hidden li')).toHaveLength(2);
});
it('does not restore old menu addresses when the canonical list is empty', () => {
tenantState.set({ ...tenant, addresses: [] });
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.contact-page__location')).toHaveLength(0);
expect(fixture.nativeElement.querySelector('app-location-map')).toBeNull();
});
it('does not read old menu addresses when the address list is absent', () => {
tenantState.set({ ...tenant, addresses: undefined });
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('.contact-page__location')).toHaveLength(0);
});
});

View File

@@ -18,7 +18,7 @@ type ContactAddress = {
id: string;
label: string;
address: string;
coordinates: [number, number];
coordinates: [number, number] | null;
};
type ContactContent = {
@@ -54,91 +54,40 @@ export class ContactPage {
}
private parseContactContent(value: unknown): ContactContent {
const empty: ContactContent = {
whatsappUrl: null,
whatsappLabel: null,
phone: null,
locations: [],
mapLocations: [],
};
if (!this.isRecord(value)) {
return empty;
}
const whatsapp = this.isRecord(value['whatsapp']) ? value['whatsapp'] : null;
const locations = this.parseLocations(value['locations']).slice(0, 1);
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) => ({
id: String(address.id),
label: address.label,
addresses: [{
id: String(address.id),
label: address.label,
address: address.address_text,
coordinates: address.latitude !== null && address.longitude !== null
? [address.latitude, address.longitude] : null,
}],
}));
return {
whatsappUrl: whatsapp ? this.stringValue(whatsapp['whatsapp_url']) : null,
whatsappLabel: whatsapp ? this.stringValue(whatsapp['whatsapp_label']) : null,
phone: this.stringValue(value['phone']),
phone: this.stringValue(content['phone']) ?? this.tenantService.tenant()?.phone ?? null,
locations,
mapLocations: locations.flatMap((location) =>
location.addresses.map(
(address): MapLocation => ({
location.addresses.flatMap(
(address): MapLocation[] => address.coordinates === null ? [] : [{
id: address.id,
label: address.label,
latitude: address.coordinates[0],
longitude: address.coordinates[1],
address: address.address,
}),
}],
),
),
};
}
private parseLocations(value: unknown): ContactLocation[] {
return this.recordEntries(value).flatMap(([id, item]): ContactLocation[] => {
if (!this.isRecord(item)) {
return [];
}
const label = this.stringValue(item['label']);
const addresses: ContactAddress[] = Array.isArray(item['addresses'])
? item['addresses'].flatMap((address, index): ContactAddress[] => {
if (!this.isRecord(address)) {
return [];
}
const addressLabel = this.stringValue(address['label']);
const addressText = this.stringValue(address['address']);
const coordinates = address['coordinates'];
if (
!addressLabel ||
!addressText ||
!Array.isArray(coordinates) ||
coordinates.length !== 2 ||
typeof coordinates[0] !== 'number' ||
typeof coordinates[1] !== 'number'
) {
return [];
}
return [
{
id: `${id}-${index}`,
label: addressLabel,
address: addressText,
coordinates: [coordinates[0], coordinates[1]],
},
];
})
: [];
return label && addresses.length > 0 ? [{ id, label, addresses }] : [];
});
}
private recordEntries(value: unknown): [string, unknown][] {
if (Array.isArray(value)) {
return value.map((item, index) => [String(index), item]);
}
return this.isRecord(value) ? Object.entries(value) : [];
}
private stringValue(value: unknown): string | null {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}

View File

@@ -81,7 +81,7 @@ export class StoreHomePageComponent implements OnInit, OnDestroy {
return {
id: event.id,
title: event.title,
location: event.location,
location: event.address?.address_text ?? null,
dates_text: event.date_text,
dates: event.dates.map((eventDate) => ({
id: eventDate.id,