feat(product-detail): implement resolver for product details and update component logic for improved error handling

feat(product-carousel): enhance image loading with optimized attributes and improve layout consistency
style: refactor HTML structure for better readability and maintainability
test(product-detail): add unit tests for product detail resolver and component behavior
This commit is contained in:
2026-07-08 16:12:35 -03:00
parent 6c00a3e2bb
commit 993aa5823a
8 changed files with 391 additions and 203 deletions

View File

@@ -1,5 +1,9 @@
import { HttpRequest, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
import {
ApplicationConfig,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
@@ -8,10 +12,10 @@ import { authBootstrap } from './core/services/auth/auth-bootstrap';
import { authInterceptor } from './core/services/auth/auth.interceptor';
import { tenantBootstrap } from './core/services/tenant-bootstrap';
function isStoreHomeProductsRequest(request: HttpRequest<unknown>): boolean {
function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
return (
request.method === 'GET' &&
/\/api\/tenants\/[^/]+\/productos(?:\?|$)/.test(request.urlWithParams)
/\/api\/tenants\/[^/]+\/productos(?:\/\d+)?(?:\?|$)/.test(request.urlWithParams)
);
}
@@ -22,11 +26,11 @@ export const appConfig: ApplicationConfig = {
provideClientHydration(
withHttpTransferCacheOptions({
includeRequestsWithAuthHeaders: true,
filter: isStoreHomeProductsRequest
})
filter: isStoreCatalogRequest,
}),
),
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
provideAppInitializer(authBootstrap),
provideAppInitializer(tenantBootstrap)
]
provideAppInitializer(tenantBootstrap),
],
};

View File

@@ -1,51 +1,70 @@
<div class="product-carousel d-flex flex-column gap-4">
<!-- Active/Main Image Area -->
<div class="product-carousel__main position-relative bg-light overflow-hidden">
<div class="product-carousel__main position-relative bg-light overflow-hidden">
<!-- Main Image -->
@if (images().length > 0) {
<img [src]="images()[activeIndex()]" alt="Product active image"
class="product-carousel__main-image w-100 h-100 object-fit-cover" />
<img
[ngSrc]="images()[activeIndex()]"
alt="Product active image"
fill
priority
sizes="(min-width: 992px) 42vw, 100vw"
class="product-carousel__main-image w-100 h-100 object-fit-cover"
/>
} @else {
<!-- Placeholder -->
<div class="product-carousel__placeholder w-100 h-100 d-flex align-items-center justify-content-center text-muted">
<i class="fa-solid fa-image fa-3x"></i>
</div>
<!-- Placeholder -->
<div
class="product-carousel__placeholder w-100 h-100 d-flex align-items-center justify-content-center text-muted"
>
<i class="fa-solid fa-image fa-3x"></i>
</div>
}
<!-- Discount Badge -->
@if (discount() && discount()! > 0) {
<span
class="product-carousel__discount-badge position-absolute top-0 end-0 bg-primary text-white px-3 py-2 fw-semibold">
-{{ discount() }}%
</span>
<span
class="product-carousel__discount-badge position-absolute top-0 end-0 bg-primary text-white px-3 py-2 fw-semibold"
>
-{{ discount() }}%
</span>
}
<!-- Navigation Arrows -->
@if (images().length > 1) {
<button type="button"
class="product-carousel__nav-btn product-carousel__nav-btn--prev position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
(click)="prevImage()" aria-label="Previous image">
<i class="fa-solid fa-chevron-left"></i>
</button>
<button
type="button"
class="product-carousel__nav-btn product-carousel__nav-btn--prev position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
(click)="prevImage()"
aria-label="Previous image"
>
<i class="fa-solid fa-chevron-left"></i>
</button>
<button type="button"
class="product-carousel__nav-btn product-carousel__nav-btn--next position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
(click)="nextImage()" aria-label="Next image">
<i class="fa-solid fa-chevron-right"></i>
</button>
<button
type="button"
class="product-carousel__nav-btn product-carousel__nav-btn--next position-absolute top-50 translate-middle-y border-0 p-0 d-flex align-items-center justify-content-center"
(click)="nextImage()"
aria-label="Next image"
>
<i class="fa-solid fa-chevron-right"></i>
</button>
}
</div>
<!-- Thumbnails Row -->
@if (images().length > 1) {
<div class="product-carousel__thumbnails">
@for (image of images(); track image; let idx = $index) {
<button type="button" class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
[class.product-carousel__thumbnail--active]="idx === activeIndex()" (click)="selectImage(idx)"
[attr.aria-label]="'Select image ' + (idx + 1)">
<img [src]="image" alt="Product thumbnail" class="w-100 h-100 object-fit-cover" />
</button>
}
</div>
<div class="product-carousel__thumbnails">
@for (image of images(); track image; let idx = $index) {
<button
type="button"
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
[class.product-carousel__thumbnail--active]="idx === activeIndex()"
(click)="selectImage(idx)"
[attr.aria-label]="'Select image ' + (idx + 1)"
>
<img [src]="image" alt="Product thumbnail" class="w-100 h-100 object-fit-cover" />
</button>
}
</div>
}
</div>

View File

@@ -1,13 +1,13 @@
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CommonModule, NgOptimizedImage } from '@angular/common';
@Component({
selector: 'app-product-carousel',
standalone: true,
imports: [CommonModule],
imports: [CommonModule, NgOptimizedImage],
templateUrl: './product-carousel.component.html',
styleUrl: './product-carousel.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductCarouselComponent {
readonly images = input<string[]>([]);

View File

@@ -1,12 +1,8 @@
import { TestBed, getTestBed } from '@angular/core/testing';
import {
BrowserTestingModule,
platformBrowserTesting
} from '@angular/platform-browser/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ActivatedRoute, Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { BehaviorSubject, of, throwError } from 'rxjs';
import { convertToParamMap } from '@angular/router';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
@@ -14,6 +10,10 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
import { CartService } from '../../../../core/services/cart/cart.service';
import { ToastService } from '../../../../core/services/toast.service';
import { ProductDetailPageComponent } from './product-detail-page.component';
import {
PRODUCT_DETAIL_ERROR_MESSAGE,
ProductDetailResolvedData,
} from './product-detail-page.resolver';
describe('ProductDetailPageComponent', () => {
const mockProduct: ProductDetail = {
@@ -29,10 +29,10 @@ describe('ProductDetailPageComponent', () => {
images: ['https://example.com/image.png'],
attributes: [],
variants_map: [],
variant: null
variant: null,
};
let paramMapSubject: BehaviorSubject<any>;
let routeDataSubject: BehaviorSubject<{ productDetailData: ProductDetailResolvedData }>;
let catalogServiceStub: any;
let routerStub: any;
let cartServiceStub: any;
@@ -40,10 +40,7 @@ describe('ProductDetailPageComponent', () => {
beforeAll(() => {
try {
getTestBed().initTestEnvironment(
BrowserTestingModule,
platformBrowserTesting()
);
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
} catch {
// Test environment may already be initialized by another setup entrypoint.
}
@@ -51,20 +48,25 @@ describe('ProductDetailPageComponent', () => {
beforeEach(() => {
vi.restoreAllMocks();
paramMapSubject = new BehaviorSubject(convertToParamMap({ id: '1' }));
routeDataSubject = new BehaviorSubject<{ productDetailData: ProductDetailResolvedData }>({
productDetailData: {
product: mockProduct,
error: null,
},
});
catalogServiceStub = {
getProducto: vi.fn().mockReturnValue(of(mockProduct))
getProducto: vi.fn(),
};
routerStub = {
navigate: vi.fn()
navigate: vi.fn(),
};
cartServiceStub = {
addItem: vi.fn().mockReturnValue(of({ message: 'Producto agregado al carrito' }))
addItem: vi.fn().mockReturnValue(of({ message: 'Producto agregado al carrito' })),
};
toastServiceStub = {
success: vi.fn(),
danger: vi.fn(),
info: vi.fn()
info: vi.fn(),
};
});
@@ -75,47 +77,69 @@ describe('ProductDetailPageComponent', () => {
{
provide: ActivatedRoute,
useValue: {
paramMap: paramMapSubject.asObservable()
}
data: routeDataSubject.asObservable(),
},
},
{
provide: CatalogService,
useValue: catalogServiceStub
useValue: catalogServiceStub,
},
{
provide: Router,
useValue: routerStub
useValue: routerStub,
},
{
provide: CartService,
useValue: cartServiceStub
useValue: cartServiceStub,
},
{
provide: ToastService,
useValue: toastServiceStub
}
]
useValue: toastServiceStub,
},
],
}).compileComponents();
}
it('loads the product on init and embeds the carousel', async () => {
function resolveProduct(product: ProductDetail): void {
routeDataSubject.next({
productDetailData: {
product,
error: null,
},
});
}
function resolveProductError(error: string): void {
routeDataSubject.next({
productDetailData: {
product: null,
error,
},
});
}
it('renders the resolved product and embeds the carousel', async () => {
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
expect(catalogServiceStub.getProducto).toHaveBeenCalledWith(1);
expect(catalogServiceStub.getProducto).not.toHaveBeenCalled();
expect(element.querySelector('app-product-carousel')).not.toBeNull();
expect(element.querySelector('.product-detail__title')?.textContent).toContain('Auriculares Bluetooth');
expect(element.querySelector('.product-detail__price-current')?.textContent).toContain('$24.999');
expect(element.querySelector('.product-detail__title')?.textContent).toContain(
'Auriculares Bluetooth',
);
expect(element.querySelector('.product-detail__price-current')?.textContent).toContain(
'$24.999',
);
expect(element.querySelector('.product-detail__price-previous')).toBeNull();
expect(element.querySelector('.product-carousel__discount-badge')).toBeNull();
});
it('shows error message if load fails', async () => {
catalogServiceStub.getProducto.mockReturnValue(throwError(() => new Error('load failed')));
it('shows error message if the resolver cannot load the product', async () => {
resolveProductError(PRODUCT_DETAIL_ERROR_MESSAGE);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
@@ -125,7 +149,6 @@ describe('ProductDetailPageComponent', () => {
expect(element.textContent).toContain('No pudimos cargar los detalles del producto.');
});
it('should use default variant images if present', async () => {
const detailProduct: ProductDetail = {
...mockProduct,
@@ -134,26 +157,29 @@ describe('ProductDetailPageComponent', () => {
id: 123,
cantidad_maxima: 10,
images: ['https://example.com/variant1.png', 'https://example.com/variant2.png'],
definitions: {}
}
definitions: {},
},
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
fixture.detectChanges();
const carousel = fixture.debugElement.query(By.css('app-product-carousel')).componentInstance;
expect(carousel.images()).toEqual(['https://example.com/variant1.png', 'https://example.com/variant2.png']);
expect(carousel.images()).toEqual([
'https://example.com/variant1.png',
'https://example.com/variant2.png',
]);
});
it('should fallback to product images if default variant images are not present', async () => {
const detailProduct: ProductDetail = {
...mockProduct,
images: ['https://example.com/product.png'],
variant: null
variant: null,
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -167,9 +193,9 @@ describe('ProductDetailPageComponent', () => {
const detailProduct: ProductDetail = {
...mockProduct,
images: [],
variant: null
variant: null,
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -196,16 +222,16 @@ describe('ProductDetailPageComponent', () => {
value: 'beige',
label: 'Beige',
sort_order: 1,
metadata: { hex: '#D8D1C7' }
metadata: { hex: '#D8D1C7' },
},
{
id: 11,
value: 'brown',
label: 'Marrón',
sort_order: 2,
metadata: { palette: { primary: '#7E6460' } }
}
]
metadata: { palette: { primary: '#7E6460' } },
},
],
},
{
id: 2,
@@ -220,17 +246,17 @@ describe('ProductDetailPageComponent', () => {
value: 'mesh',
label: 'Mesh',
sort_order: 1,
metadata: null
metadata: null,
},
{
id: 21,
value: 'cuero',
label: 'Cuero',
sort_order: 2,
metadata: null
}
]
}
metadata: null,
},
],
},
],
variant: {
id: 123,
@@ -238,11 +264,11 @@ describe('ProductDetailPageComponent', () => {
images: ['https://example.com/variant1.png'],
definitions: {
color: 'beige',
material: 'Cuero'
}
}
material: 'Cuero',
},
},
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -252,14 +278,16 @@ describe('ProductDetailPageComponent', () => {
const swatches = element.querySelectorAll('.attribute-selector__swatch');
const textOptions = element.querySelectorAll('.attribute-selector__text-option');
const labels = Array.from(element.querySelectorAll('.attribute-selector__label')).map((label) =>
label.textContent?.trim()
label.textContent?.trim(),
);
expect(labels).toEqual(['Color:', 'Material:']);
expect(swatches).toHaveLength(2);
expect(textOptions).toHaveLength(2);
expect(swatches[0].classList.contains('attribute-selector__swatch--selected')).toBe(true);
expect(textOptions[1].classList.contains('attribute-selector__text-option--selected')).toBe(true);
expect(textOptions[1].classList.contains('attribute-selector__text-option--selected')).toBe(
true,
);
expect((swatches[0] as HTMLElement).style.backgroundColor).not.toBe('');
});
@@ -282,16 +310,16 @@ describe('ProductDetailPageComponent', () => {
fixture.componentInstance['selectedVariant'].set({
variant_id: 1,
cantidad_maxima: 10,
attributes: {}
attributes: {},
});
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const decreaseButton = element.querySelector(
'[aria-label="Disminuir cantidad"]'
'[aria-label="Disminuir cantidad"]',
) as HTMLButtonElement;
const increaseButton = element.querySelector(
'[aria-label="Aumentar cantidad"]'
'[aria-label="Aumentar cantidad"]',
) as HTMLButtonElement;
decreaseButton.click();
@@ -316,7 +344,7 @@ describe('ProductDetailPageComponent', () => {
const element = fixture.nativeElement as HTMLElement;
const toggleButton = element.querySelector(
'.product-detail__description-toggle'
'.product-detail__description-toggle',
) as HTMLButtonElement;
expect(toggleButton.textContent?.trim()).toBe('Mostrar más');
@@ -327,7 +355,7 @@ describe('ProductDetailPageComponent', () => {
expect(
element
.querySelector('.product-detail__description-body')
?.classList.contains('product-detail__description-body--expanded')
?.classList.contains('product-detail__description-body--expanded'),
).toBe(true);
expect(toggleButton.textContent?.trim()).toBe('Mostrar menos');
});
@@ -338,12 +366,12 @@ describe('ProductDetailPageComponent', () => {
fixture.detectChanges();
const buttons = Array.from(
fixture.nativeElement.querySelectorAll('app-button button')
fixture.nativeElement.querySelectorAll('app-button button'),
) as HTMLButtonElement[];
expect(buttons.map((button) => button.textContent?.trim())).toEqual([
'Agregar al carrito',
'Comprar'
'Comprar',
]);
buttons[0].click();
@@ -359,17 +387,17 @@ describe('ProductDetailPageComponent', () => {
id: 123,
cantidad_maxima: 5,
images: [],
definitions: {}
definitions: {},
},
variants_map: [
{
variant_id: 123,
cantidad_maxima: 5,
attributes: {}
}
]
attributes: {},
},
],
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
await configureTestingModule();
const fixture = TestBed.createComponent(ProductDetailPageComponent);
@@ -382,7 +410,7 @@ describe('ProductDetailPageComponent', () => {
const element = fixture.nativeElement as HTMLElement;
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
(btn) => btn.textContent?.trim() === 'Agregar al carrito'
(btn) => btn.textContent?.trim() === 'Agregar al carrito',
) as HTMLButtonElement;
expect(addToCartButton).toBeDefined();
@@ -400,17 +428,17 @@ describe('ProductDetailPageComponent', () => {
id: 123,
cantidad_maxima: 5,
images: [],
definitions: {}
definitions: {},
},
variants_map: [
{
variant_id: 123,
cantidad_maxima: 5,
attributes: {}
}
]
attributes: {},
},
],
};
catalogServiceStub.getProducto.mockReturnValue(of(detailProduct));
resolveProduct(detailProduct);
cartServiceStub.addItem.mockReturnValue(throwError(() => new Error('Failed to add')));
await configureTestingModule();
@@ -422,13 +450,15 @@ describe('ProductDetailPageComponent', () => {
const element = fixture.nativeElement as HTMLElement;
const addToCartButton = Array.from(element.querySelectorAll('app-button button')).find(
(btn) => btn.textContent?.trim() === 'Agregar al carrito'
(btn) => btn.textContent?.trim() === 'Agregar al carrito',
) as HTMLButtonElement;
addToCartButton.click();
fixture.detectChanges();
expect(cartServiceStub.addItem).toHaveBeenCalled();
expect(toastServiceStub.danger).toHaveBeenCalledWith('No se pudo agregar el producto al carrito.');
expect(toastServiceStub.danger).toHaveBeenCalledWith(
'No se pudo agregar el producto al carrito.',
);
});
});

View File

@@ -9,7 +9,7 @@ import {
inject,
signal,
viewChild,
PLATFORM_ID
PLATFORM_ID,
} from '@angular/core';
import { CommonModule, isPlatformBrowser } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
@@ -20,16 +20,14 @@ import { CatalogService } from '../../../../core/services/catalog/catalog.servic
import { ToastService } from '../../../../core/services/toast.service';
import { CartService } from '../../../../core/services/cart/cart.service';
import {
ProductAttribute,
ProductAttributeOption,
ProductDetail,
ProductVariant,
ProductVariantMap
ProductVariantMap,
} from '../../../../core/services/catalog/catalog.interface';
import { ProductCarouselComponent } from '../../components/product-carousel/product-carousel.component';
import { ButtonComponent } from '../../../../shared/components/button/button.component';
import { ProductAttributeSelectorComponent } from '../../components/product-attribute-selector/product-attribute-selector.component';
import { QuantitySelectorComponent } from '../../../../shared/components/quantity-selector/quantity-selector.component';
import { ProductDetailResolvedData } from './product-detail-page.resolver';
@Component({
selector: 'app-product-detail-page',
@@ -40,11 +38,11 @@ import { QuantitySelectorComponent } from '../../../../shared/components/quantit
ProductCarouselComponent,
ButtonComponent,
ProductAttributeSelectorComponent,
QuantitySelectorComponent
QuantitySelectorComponent,
],
templateUrl: './product-detail-page.component.html',
styleUrl: './product-detail-page.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductDetailPageComponent implements OnInit, OnDestroy {
private readonly route = inject(ActivatedRoute);
@@ -86,14 +84,14 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
protected readonly descriptionMaxHeight = signal(0);
protected readonly descriptionHasOverflow = signal(false);
protected readonly renderableAttributes = computed(() =>
(this.product()?.attributes ?? []).filter((attribute) => attribute.options.length > 0)
(this.product()?.attributes ?? []).filter((attribute) => attribute.options.length > 0),
);
protected readonly hasRenderableAttributes = computed(
() => this.renderableAttributes().length > 0
() => this.renderableAttributes().length > 0,
);
protected readonly oldPrice = computed<string | null>(() => null);
protected readonly showDescriptionToggle = computed(
() => this.descriptionExpanded() || this.descriptionHasOverflow()
() => this.descriptionExpanded() || this.descriptionHasOverflow(),
);
constructor() {
@@ -113,14 +111,12 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
this.routeSub = this.route.paramMap.subscribe((params) => {
const id = this.parseIntegerParam(params.get('id'));
if (id === null) {
this.error.set('ID de producto inválido');
return;
}
this.routeSub = this.route.data.subscribe((data) => {
const resolvedData = data['productDetailData'] as ProductDetailResolvedData | undefined;
this.loadProduct(id);
if (resolvedData) {
this.applyResolvedData(resolvedData);
}
});
}
@@ -131,38 +127,13 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.clearMeasurementTimer();
}
private loadProduct(id: number): void {
this.loading.set(true);
this.error.set(null);
this.product.set(null);
this.productSub?.unsubscribe();
this.productSub = this.catalogService.getProducto(id).subscribe({
next: (prod) => {
this.product.set(prod);
const matchingVariant = prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
this.selectedVariant.set(matchingVariant);
this.quantity.set(1);
this.descriptionExpanded.set(false);
this.descriptionHasOverflow.set(false);
this.loading.set(false);
},
error: () => {
this.error.set('No pudimos cargar los detalles del producto.');
this.loading.set(false);
}
});
}
private loadProductVariant(productId: number, variantId: number): void {
this.variantLoading.set(true);
this.productSub?.unsubscribe();
this.productSub = this.catalogService.getProducto(productId, variantId).subscribe({
next: (prod) => {
this.product.set(prod);
const matchingVariant = prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
this.selectedVariant.set(matchingVariant);
this.applyProduct(prod, false);
this.variantLoading.set(false);
},
error: (err: HttpErrorResponse) => {
@@ -180,15 +151,44 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
});
return {
...currentProduct,
variants_map: updatedVariantsMap
variants_map: updatedVariantsMap,
};
});
this.attributeSelector()?.reset();
}
},
});
}
private applyResolvedData(resolvedData: ProductDetailResolvedData): void {
this.productSub?.unsubscribe();
this.loading.set(false);
this.variantLoading.set(false);
if (resolvedData.error) {
this.product.set(null);
this.error.set(resolvedData.error);
return;
}
if (resolvedData.product) {
this.applyProduct(resolvedData.product, true);
}
}
private applyProduct(prod: ProductDetail, resetQuantity: boolean): void {
this.product.set(prod);
const matchingVariant =
prod.variants_map.find((v) => v.variant_id === prod.variant?.id) || null;
this.selectedVariant.set(matchingVariant);
if (resetQuantity) {
this.quantity.set(1);
}
this.descriptionExpanded.set(false);
this.descriptionHasOverflow.set(false);
this.error.set(null);
}
protected goBack(): void {
this.router.navigate(['/']);
}
@@ -219,8 +219,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
}
protected addToCart(): void {
const variant = this.selectedVariant();
if (!variant) {
@@ -239,7 +237,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
const errorMessage = err.error?.message || 'No se pudo agregar el producto al carrito.';
this.toastService.danger(errorMessage);
this.addingToCart.set(false);
}
},
});
}
@@ -247,15 +245,6 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
this.descriptionExpanded.update((current) => !current);
}
private parseIntegerParam(value: string | null): number | null {
if (!value) {
return null;
}
const parsed = Number(value);
return Number.isInteger(parsed) ? parsed : null;
}
private bindCarouselResizeObserver(): void {
const previewElement = this.getCarouselPreviewElement();
@@ -315,7 +304,7 @@ export class ProductDetailPageComponent implements OnInit, OnDestroy {
}
this.descriptionHasOverflow.set(
descriptionElement.scrollHeight - descriptionElement.clientHeight > 1
descriptionElement.scrollHeight - descriptionElement.clientHeight > 1,
);
}

View File

@@ -0,0 +1,91 @@
import { TestBed } from '@angular/core/testing';
import { convertToParamMap } from '@angular/router';
import { firstValueFrom, Observable, of, throwError } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
import {
PRODUCT_DETAIL_ERROR_MESSAGE,
PRODUCT_DETAIL_INVALID_ID_MESSAGE,
ProductDetailResolvedData,
productDetailResolver,
} from './product-detail-page.resolver';
describe('productDetailResolver', () => {
const product: ProductDetail = {
id: 1,
category_id: 10,
brand_id: null,
slug: 'auriculares-bluetooth',
nombre: 'Auriculares Bluetooth',
descripcion: 'Auriculares bluetooth de prueba',
precio: '24999',
category: 'Tecnologia',
brand: null,
images: [],
attributes: [],
variants_map: [],
variant: null,
};
let catalogServiceStub: { getProducto: ReturnType<typeof vi.fn> };
beforeEach(() => {
catalogServiceStub = {
getProducto: vi.fn().mockReturnValue(of(product)),
};
TestBed.configureTestingModule({
providers: [
{
provide: CatalogService,
useValue: catalogServiceStub,
},
],
});
});
it('resolves the product detail for the route id', async () => {
const result = TestBed.runInInjectionContext(() =>
productDetailResolver(createRouteSnapshot('1'), {} as never),
);
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
product,
error: null,
});
expect(catalogServiceStub.getProducto).toHaveBeenCalledWith(1);
});
it('returns an error state for invalid ids', async () => {
const result = TestBed.runInInjectionContext(() =>
productDetailResolver(createRouteSnapshot('abc'), {} as never),
);
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
product: null,
error: PRODUCT_DETAIL_INVALID_ID_MESSAGE,
});
expect(catalogServiceStub.getProducto).not.toHaveBeenCalled();
});
it('returns an error state when the request fails', async () => {
catalogServiceStub.getProducto.mockReturnValue(throwError(() => new Error('boom')));
const result = TestBed.runInInjectionContext(() =>
productDetailResolver(createRouteSnapshot('1'), {} as never),
);
await expect(firstValueFrom(result as Observable<ProductDetailResolvedData>)).resolves.toEqual({
product: null,
error: PRODUCT_DETAIL_ERROR_MESSAGE,
});
});
});
function createRouteSnapshot(id: string) {
return {
paramMap: convertToParamMap({ id }),
} as never;
}

View File

@@ -0,0 +1,53 @@
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, ResolveFn } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { ProductDetail } from '../../../../core/services/catalog/catalog.interface';
import { CatalogService } from '../../../../core/services/catalog/catalog.service';
export const PRODUCT_DETAIL_ERROR_MESSAGE = 'No pudimos cargar los detalles del producto.';
export const PRODUCT_DETAIL_INVALID_ID_MESSAGE = 'ID de producto invalido';
export interface ProductDetailResolvedData {
product: ProductDetail | null;
error: string | null;
}
export const productDetailResolver: ResolveFn<ProductDetailResolvedData> = (
route: ActivatedRouteSnapshot,
) => {
const productId = parseIntegerParam(route.paramMap.get('id'));
if (productId === null) {
return of({
product: null,
error: PRODUCT_DETAIL_INVALID_ID_MESSAGE,
});
}
return inject(CatalogService)
.getProducto(productId)
.pipe(
map(
(product): ProductDetailResolvedData => ({
product,
error: null,
}),
),
catchError(() =>
of({
product: null,
error: PRODUCT_DETAIL_ERROR_MESSAGE,
}),
),
);
};
function parseIntegerParam(value: string | null): number | null {
if (!value) {
return null;
}
const parsed = Number(value);
return Number.isInteger(parsed) ? parsed : null;
}

View File

@@ -4,6 +4,7 @@ import { SimpleLayoutComponent } from '../../core/layout/simple-layout/simple-la
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
import { authGuard, guestOnlyGuard } from '../../core/services/auth/auth.guards';
import { LoginPageComponent } from './pages/login-page/login-page.component';
import { productDetailResolver } from './pages/product-detail-page/product-detail-page.resolver';
import { RegisterPageComponent } from './pages/register-page/register-page.component';
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
import { storeHomeProductsResolver } from './pages/store-home-page/store-home-page.resolver';
@@ -17,8 +18,8 @@ export const routes: Routes = [
path: '',
component: StoreHomePageComponent,
resolve: {
productsData: storeHomeProductsResolver
}
productsData: storeHomeProductsResolver,
},
},
{
path: 'login',
@@ -27,9 +28,9 @@ export const routes: Routes = [
children: [
{
path: '',
component: LoginPageComponent
}
]
component: LoginPageComponent,
},
],
},
{
path: 'register',
@@ -38,24 +39,27 @@ export const routes: Routes = [
children: [
{
path: '',
component: RegisterPageComponent
}
]
component: RegisterPageComponent,
},
],
},
{
path: 'producto/:id',
resolve: {
productDetailData: productDetailResolver,
},
loadComponent: () =>
import('./pages/product-detail-page/product-detail-page.component').then(
(m) => m.ProductDetailPageComponent
)
(m) => m.ProductDetailPageComponent,
),
},
{
path: 'checkout',
canActivate: [authGuard],
loadComponent: () =>
import('./pages/checkout-page/checkout-page.component').then(
(m) => m.CheckoutPageComponent
)
(m) => m.CheckoutPageComponent,
),
},
{
path: 'checkout/status',
@@ -65,47 +69,45 @@ export const routes: Routes = [
path: ':id',
loadComponent: () =>
import('./pages/purchase-status-page/purchase-status-page.component').then(
(m) => m.PurchaseStatusPageComponent
)
}
]
(m) => m.PurchaseStatusPageComponent,
),
},
],
},
{
path: 'mi-cuenta',
canActivate: [authGuard],
loadComponent: () =>
import('./pages/account-page/account-layout/account-layout').then(
(m) => m.AccountLayout
),
import('./pages/account-page/account-layout/account-layout').then((m) => m.AccountLayout),
children: [
{
path: 'datos-personales',
loadComponent: () =>
import('./pages/account-page/pages/profile-page/profile-page').then(
(m) => m.ProfilePage
)
(m) => m.ProfilePage,
),
},
{
path: 'compras',
loadComponent: () =>
import('./pages/account-page/pages/purchases-page/purchases-page').then(
(m) => m.PurchasesPage
)
(m) => m.PurchasesPage,
),
},
{
path: 'compras/:id',
loadComponent: () =>
import('./pages/account-page/pages/purchase-detail-page/purchase-detail-page').then(
(m) => m.PurchaseDetailPage
)
(m) => m.PurchaseDetailPage,
),
},
{
path: '',
redirectTo: 'datos-personales',
pathMatch: 'full'
}
]
}
]
}
pathMatch: 'full',
},
],
},
],
},
];